-
Notifications
You must be signed in to change notification settings - Fork 9
/
jwt.go
66 lines (54 loc) · 1.94 KB
/
jwt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package github
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"namespacelabs.dev/foundation/internal/fnerrors"
)
const (
userAgent = "actions/oidc-client"
)
func JWT(ctx context.Context, audience string) (string, error) {
idTokenURL := os.Getenv("ACTIONS_ID_TOKEN_REQUEST_URL")
if idTokenURL == "" {
return "", fnerrors.UsageError("Please add `id-token: write` to your workflow permissions. See also https://github.com/namespacelabs/nscloud-setup#example", "empty GitHub ID token request URL")
}
idToken := os.Getenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN")
if idToken == "" {
return "", fnerrors.BadDataError("empty GitHub ID token request token")
}
if audience != "" {
idTokenURL += fmt.Sprintf("&audience=%s", url.QueryEscape(audience))
}
req, err := http.NewRequestWithContext(ctx, "GET", idTokenURL, nil)
if err != nil {
return "", fnerrors.InvocationError("jwt", "failed to create HTTP request: %w", err)
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("User-Agent", userAgent)
req.Header.Add("Authorization", "Bearer "+idToken)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", fnerrors.InvocationError("jwt", "failed to request github JWT: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fnerrors.InvocationError("jwt", "failed to obtain token: %v", resp.Status)
}
var idTokenResponse struct {
Value string `json:"value"`
}
if err := json.NewDecoder(resp.Body).Decode(&idTokenResponse); err != nil {
return "", fnerrors.InvocationError("jwt", "bad response: %w", err)
}
if idTokenResponse.Value == "" {
return "", fnerrors.InvocationError("jwt", "bad response: empty ID token")
}
return idTokenResponse.Value, nil
}