-
Notifications
You must be signed in to change notification settings - Fork 106
/
jwt.go
252 lines (221 loc) · 6.99 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
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package auth
import (
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
"github.com/MicahParks/keyfunc"
"github.com/go-jose/go-jose/v3"
"github.com/golang-jwt/jwt/v4"
"go.uber.org/zap"
)
// Issuer creates JWTs with claims for an Audience.
// The Issuer is used by the admin server to create JWTs for the runtimes it manages based on a user's control-plane permissions.
type Issuer struct {
issuerURL string
signingKey jose.JSONWebKey
publicJWKS []byte
}
// NewIssuer creates an issuer from a JWKS. The JWKS must contain private keys.
// The key identified by signingKeyID will be used to sign new JWTs.
func NewIssuer(issuerURL, signingKeyID string, jwksJSON []byte) (*Issuer, error) {
// Parse the private JWKS
var jwks jose.JSONWebKeySet
err := json.Unmarshal(jwksJSON, &jwks)
if err != nil {
return nil, fmt.Errorf("invalid JWKS: %w", err)
}
// Extract signing key (must be a valid, private key)
var signingKey jose.JSONWebKey
for i := 0; i < len(jwks.Keys); i++ {
if jwks.Keys[i].KeyID == signingKeyID {
signingKey = jwks.Keys[i]
break
}
}
if !signingKey.Valid() || signingKey.IsPublic() {
return nil, fmt.Errorf("invalid signing key %q", signingKeyID)
}
// Map JWKS to public keys and serialize to JSON
var publicJWKS jose.JSONWebKeySet
for i := 0; i < len(jwks.Keys); i++ {
publicKey := jwks.Keys[i].Public()
if !publicKey.Valid() {
return nil, fmt.Errorf("invalid signing key in JWKS")
}
publicJWKS.Keys = append(publicJWKS.Keys, publicKey)
}
publicJSON, err := json.Marshal(publicJWKS)
if err != nil {
return nil, err
}
return &Issuer{
issuerURL: issuerURL,
signingKey: signingKey,
publicJWKS: publicJSON,
}, nil
}
// NewEphemeralIssuer creates an Issuer using a generated JWKS.
// It is useful for development and testing, but should not be used in production.
func NewEphemeralIssuer(issuerURL string) (*Issuer, error) {
// NOTE: JWKS generation based on: https://github.com/go-jose/go-jose/blob/v3/jose-util/generate.go
// Generate RSA private key
rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}
// Create JWK
jwk := jose.JSONWebKey{
Key: rsaKey,
Algorithm: string(jose.RS256),
Use: "sig",
}
// Set key ID based on JWK thumbprint
thumb, err := jwk.Thumbprint(crypto.SHA256)
if err != nil {
return nil, err
}
jwk.KeyID = base64.URLEncoding.EncodeToString(thumb)
// Create JWKS JSON
jwks := jose.JSONWebKeySet{Keys: []jose.JSONWebKey{jwk}}
jwksJSON, err := json.Marshal(jwks)
if err != nil {
return nil, err
}
return NewIssuer(issuerURL, jwk.KeyID, jwksJSON)
}
// TokenOptions provides options for Issuer.NewToken.
type TokenOptions struct {
AudienceURL string
Subject string
TTL time.Duration
SystemPermissions []Permission
InstancePermissions map[string][]Permission
Attributes map[string]any
}
// NewToken issues a new JWT based on the provided options.
func (i *Issuer) NewToken(opts TokenOptions) (string, error) {
now := time.Now()
claims := &jwtClaims{
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now.Add(opts.TTL)),
IssuedAt: jwt.NewNumericDate(now),
NotBefore: jwt.NewNumericDate(now),
Issuer: i.issuerURL,
Subject: opts.Subject,
Audience: []string{opts.AudienceURL},
},
System: opts.SystemPermissions,
Instances: opts.InstancePermissions,
Attrs: opts.Attributes,
}
token := jwt.NewWithClaims(jwt.GetSigningMethod(i.signingKey.Algorithm), claims)
token.Header["kid"] = i.signingKey.KeyID
res, err := token.SignedString(i.signingKey.Key)
if err != nil {
return "", err
}
return res, nil
}
// WellKnownHandler serves the public keys of the Issuer's JWKS.
// The Audience expects it to be mounted on {issuerURL}/.well-known/jwks.json.
func (i *Issuer) WellKnownHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(i.publicJWKS)
})
}
// Audience represents a receiver of tokens from Issuer.
// The Audience is used by the runtime to parse claims from a JWT.
// It parses and validates tokens and resolves permissions.
// It refreshes its JWKS in the background from {issuerURL}/.well-known/jwks.json.
type Audience struct {
issuerURL string
audienceURL string
jwks *keyfunc.JWKS
}
// OpenAudience creates an Audience. Remember to call Close() when done.
// The issuerURL should be the external URL of the issuing admin server.
// The issuerURL is expected to serve a JWKS on /.well-known/jwks.json.
// The audienceURL should be the external URL of the receiving runtime server.
func OpenAudience(ctx context.Context, logger *zap.Logger, issuerURL, audienceURL string) (*Audience, error) {
// To be safe, require issuer and audience is provided
if issuerURL == "" {
return nil, fmt.Errorf("issuerURL is not set")
}
if audienceURL == "" {
return nil, fmt.Errorf("audienceURL is not set")
}
// The JWKS is assumed to be served on issuer
jwksURL, err := url.JoinPath(issuerURL, ".well-known/jwks.json")
if err != nil {
return nil, err
}
// Setup keyfunc that refreshes the JWKS in the background.
// It returns an error if the initial fetch fails. So we wrap it with a retry in case the admin server is not ready.
var jwks *keyfunc.JWKS
for i := 0; i < 5; i++ {
jwks, err = keyfunc.Get(jwksURL, keyfunc.Options{
Ctx: ctx,
RefreshErrorHandler: func(err error) {
logger.Error("JWK refresh failed", zap.Error(err))
},
RefreshInterval: time.Hour,
RefreshRateLimit: time.Minute * 5,
RefreshTimeout: time.Second * 10,
RefreshUnknownKID: true,
})
if err != nil {
logger.Info("JWKS fetch failed, retrying in 5s", zap.Error(err))
select {
case <-time.After(time.Second * 5):
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
if err != nil {
return nil, err
}
return &Audience{
issuerURL: issuerURL,
audienceURL: audienceURL,
jwks: jwks,
}, nil
}
// Close stops background refresh of the JWKS.
func (a *Audience) Close() {
a.jwks.EndBackground()
}
// ParseAndValidate parses and validates a JWT and returns Claims if successful.
func (a *Audience) ParseAndValidate(tokenStr string) (Claims, error) {
claims := &jwtClaims{}
_, err := jwt.ParseWithClaims(tokenStr, claims, a.jwks.Keyfunc) // NOTE: also validates claims
if err != nil {
return nil, err
}
if !claims.VerifyIssuer(a.issuerURL, true) {
return nil, fmt.Errorf("invalid token issuer %q (expected %q)", claims.Issuer, a.issuerURL)
}
if !claims.VerifyAudience(a.audienceURL, true) {
return nil, fmt.Errorf("invalid token audience %q (expected %q)", claims.Audience, a.audienceURL)
}
return claims, nil
}
func NewDevToken(attr map[string]any) (string, error) {
claims := &devJWTClaims{
Attrs: attr,
}
token := jwt.NewWithClaims(jwt.SigningMethodNone, claims)
res, err := token.SignedString(jwt.UnsafeAllowNoneSignatureType)
if err != nil {
return "", err
}
return res, nil
}