-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathclient.go
152 lines (125 loc) · 3.47 KB
/
client.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package auth_interceptor
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
"time"
"github.com/lestrrat-go/jwx/v2/jwt"
)
type ClientInterceptor interface {
GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)
RequireTransportSecurity() bool
}
var _ ClientInterceptor = &APIKeyInterceptor{}
type APIKeyInterceptor struct {
APIKey []byte
RequireTLS bool
Team string
}
func (c *APIKeyInterceptor) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
timestamp := time.Now().Format(time.RFC3339Nano)
return map[string]string{
"authorization": sign([]byte(timestamp), c.APIKey),
"timestamp": timestamp,
"team": c.Team,
}, nil
}
func (t *APIKeyInterceptor) RequireTransportSecurity() bool {
return t.RequireTLS
}
var _ ClientInterceptor = &JWTInterceptor{}
type JWTInterceptor struct {
JWT string
RequireTLS bool
Team string
}
func (c *JWTInterceptor) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{
"jwt": c.JWT,
"team": c.Team,
}, nil
}
func (t *JWTInterceptor) RequireTransportSecurity() bool {
return t.RequireTLS
}
type GitHubTokenInterceptor struct {
BearerToken string
RequireTLS bool
TokenURL string
Team string
token string
tokenExpiresAt time.Time
mu sync.Mutex
}
func (g *GitHubTokenInterceptor) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
token, err := g.Token(ctx)
if err != nil {
return nil, fmt.Errorf("getting GitHub JWT: %w", err)
}
return map[string]string{
"jwt": token,
"team": g.Team,
}, nil
}
func (g *GitHubTokenInterceptor) RequireTransportSecurity() bool {
return g.RequireTLS
}
func (g *GitHubTokenInterceptor) Token(ctx context.Context) (string, error) {
g.mu.Lock()
defer g.mu.Unlock()
const renewBefore = 1 * time.Minute
shouldRenew := g.tokenExpiresAt.IsZero() || time.Now().After(g.tokenExpiresAt.Add(-renewBefore))
if g.token != "" && !shouldRenew {
return g.token, nil
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, g.TokenURL, nil)
if err != nil {
return "", fmt.Errorf("creating request: %w", err)
}
q := req.URL.Query()
q.Add("audience", "hookd")
req.URL.RawQuery = q.Encode()
req.Header.Set("Authorization", "bearer "+g.BearerToken)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", fmt.Errorf("fetching token: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return "", fmt.Errorf("unexpected status code: %s", resp.Status)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("reading body: %w", err)
}
var tokenResponse struct {
Token string `json:"value"`
}
err = json.Unmarshal(body, &tokenResponse)
if err != nil {
return "", fmt.Errorf("unmarshalling json: %w", err)
}
// Skip signature verification; we only care about the expiration time here.
// The receiving party (i.e., server) must verify the token anyway.
j, err := jwt.ParseString(tokenResponse.Token,
jwt.WithVerify(false),
)
if err != nil {
return "", fmt.Errorf("parsing JWT: %w", err)
}
g.token = tokenResponse.Token
g.tokenExpiresAt = j.Expiration()
return tokenResponse.Token, nil
}
func sign(data, key []byte) string {
hasher := hmac.New(sha256.New, key)
hasher.Write(data)
sum := hasher.Sum(nil)
return hex.EncodeToString(sum)
}