-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathjwks_token_decoder.go
More file actions
294 lines (248 loc) · 8 KB
/
jwks_token_decoder.go
File metadata and controls
294 lines (248 loc) · 8 KB
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package authentication
import (
"context"
"errors"
"fmt"
"net/http"
"slices"
"time"
"golang.org/x/time/rate"
"github.com/MicahParks/jwkset"
"github.com/MicahParks/keyfunc/v3"
"github.com/golang-jwt/jwt/v5"
"github.com/wundergraph/cosmo/router/internal/httpclient"
"go.uber.org/zap"
)
type TokenDecoder interface {
Decode(token string) (Claims, error)
}
type jwksTokenDecoder struct {
jwks jwt.Keyfunc
}
// Decode implements TokenDecoder.
func (j *jwksTokenDecoder) Decode(tokenString string) (Claims, error) {
token, err := jwt.Parse(tokenString, j.jwks)
if err != nil {
return nil, fmt.Errorf("could not validate token: %w", err)
}
if !token.Valid {
return nil, fmt.Errorf("token is invalid")
}
claims := token.Claims.(jwt.MapClaims)
return Claims(claims), nil
}
type JWKSConfig struct {
URL string
RefreshInterval time.Duration
AllowedAlgorithms []string
AllowedUse []string
Secret string
Algorithm string
KeyId string
Audiences []string
RefreshUnknownKID RefreshUnknownKIDConfig
}
type RefreshUnknownKIDConfig struct {
Enabled bool
Interval time.Duration
Burst int
MaxWait time.Duration
}
type configKey struct {
kid string
url string
}
type audienceSet map[string]struct{}
type keyFuncEntry struct {
jwks keyfunc.Keyfunc
aud audienceSet
allowedAlgorithms []string
allowedUse []string
}
func NewJwksTokenDecoder(ctx context.Context, logger *zap.Logger, configs []JWKSConfig) (TokenDecoder, error) {
// Audience map is used to validate duplicate configs
audiencesMap := make(map[configKey]audienceSet, len(configs))
entries := make([]keyFuncEntry, 0, len(configs))
for _, c := range configs {
if c.URL != "" {
key := configKey{url: c.URL}
if _, ok := audiencesMap[key]; ok {
return nil, fmt.Errorf("duplicate JWK URL found: %s", c.URL)
}
l := logger.With(zap.String("url", c.URL))
jwksetHTTPStorageOptions := jwkset.HTTPClientStorageOptions{
Client: newOIDCDiscoveryClient(httpclient.NewRetryableHTTPClient(l)),
Ctx: ctx, // Used to end background refresh goroutine.
HTTPExpectedStatus: http.StatusOK,
HTTPMethod: http.MethodGet,
HTTPTimeout: 15 * time.Second,
RefreshErrorHandler: func(_ context.Context, err error) {
l.Error("Failed to refresh HTTP JWK Set from remote HTTP resource.", zap.Error(err))
},
RefreshInterval: c.RefreshInterval,
Storage: jwkset.NewMemoryStorage(),
}
store, err := jwkset.NewStorageFromHTTP(c.URL, jwksetHTTPStorageOptions)
if err != nil {
return nil, fmt.Errorf("failed to create HTTP client storage for JWK provider: %w", err)
}
audiencesMap[key] = getAudienceSet(c.Audiences)
jwksetHTTPClientOptions := jwkset.HTTPClientOptions{
HTTPURLs: map[string]jwkset.Storage{
c.URL: store,
},
PrioritizeHTTP: true,
}
// Configure the rate limiter for refreshing unknown KIDs
if c.RefreshUnknownKID.Enabled {
jwksetHTTPClientOptions.RefreshUnknownKID = rate.NewLimiter(rate.Every(c.RefreshUnknownKID.Interval), c.RefreshUnknownKID.Burst)
jwksetHTTPClientOptions.RateLimitWaitMax = c.RefreshUnknownKID.MaxWait
}
jwks, err := createKeyFunc(ctx, jwksetHTTPClientOptions, getUseWhitelist(c.AllowedUse))
if err != nil {
return nil, err
}
entries = append(entries, keyFuncEntry{
jwks: jwks,
aud: audiencesMap[key],
allowedAlgorithms: c.AllowedAlgorithms,
allowedUse: c.AllowedUse,
})
} else if c.Secret != "" {
key := configKey{kid: c.KeyId}
if _, ok := audiencesMap[key]; ok {
return nil, fmt.Errorf("duplicate JWK keyid specified found: %s", c.KeyId)
}
given := jwkset.NewMemoryStorage()
marshalOptions := jwkset.JWKMarshalOptions{
Private: true,
}
if len(c.Secret) < 32 {
logger.Warn("Using a short secret for JWKs may lead to weak security. Consider using a longer secret.")
}
alg := jwkset.ALG(c.Algorithm)
if !alg.IANARegistered() {
return nil, fmt.Errorf("unsupported algorithm: %s", c.Algorithm)
}
metadata := jwkset.JWKMetadataOptions{
ALG: alg,
KID: c.KeyId,
USE: jwkset.UseSig,
}
jwkOptions := jwkset.JWKOptions{
Marshal: marshalOptions,
Metadata: metadata,
}
jwk, err := jwkset.NewJWKFromKey([]byte(c.Secret), jwkOptions)
if err != nil {
return nil, fmt.Errorf("failed to create JWK from secret: %w", err)
}
audiencesMap[key] = getAudienceSet(c.Audiences)
err = given.KeyWrite(ctx, jwk)
if err != nil {
return nil, fmt.Errorf("failed to write JWK to storage: %w", err)
}
jwksetHTTPClientOptions := jwkset.HTTPClientOptions{
Given: given,
PrioritizeHTTP: false,
}
jwks, err := createKeyFunc(ctx, jwksetHTTPClientOptions, getUseWhitelist(c.AllowedUse))
if err != nil {
return nil, err
}
entries = append(entries, keyFuncEntry{
jwks: jwks,
aud: audiencesMap[key],
allowedUse: c.AllowedUse,
})
}
}
keyFuncWrapper := jwt.Keyfunc(func(token *jwt.Token) (any, error) {
var errJoin error
for _, entry := range entries {
if len(entry.aud) > 0 {
tokenAudiences, err := token.Claims.GetAudience()
if err != nil {
errJoin = errors.Join(errJoin, fmt.Errorf("could not get audiences from token claims: %w", err))
continue
}
if !hasAudience(tokenAudiences, entry.aud) {
errJoin = errors.Join(errJoin, errUnacceptableAud)
continue
}
}
// When an algorithm is actually provided in the jwks the current keyfunc will validate the
// jwks algorithm with it. But when no algorithm is provided (alg: none or missing alg)
// the default keyfunc will not validate the algorithm as it has nothing to cross check.
if len(entry.allowedAlgorithms) > 0 {
algInter, ok := token.Header["alg"]
if !ok {
errJoin = errors.Join(errJoin, fmt.Errorf("%w: could not find alg in JWT header", keyfunc.ErrKeyfunc))
continue
}
alg, ok := algInter.(string)
if !ok {
errJoin = errors.Join(errJoin, fmt.Errorf(`%w: the JWT header did not contain the "alg" parameter, which is required by RFC 7515 section 4.1.1`, keyfunc.ErrKeyfunc))
continue
}
// This is a custom validation different from the original keyfunc.Keyfunc
if !slices.Contains(entry.allowedAlgorithms, alg) {
errJoin = errors.Join(errJoin, fmt.Errorf("%w: could not find alg %s in allow list", keyfunc.ErrKeyfunc, alg))
continue
}
}
pub, err := entry.jwks.Keyfunc(token)
if err != nil {
errJoin = errors.Join(errJoin, err)
continue
}
return pub, nil
}
return nil, fmt.Errorf("no key found for token: %w", errors.Join(errJoin, jwt.ErrTokenUnverifiable))
})
return &jwksTokenDecoder{
jwks: keyFuncWrapper,
}, nil
}
func getAudienceSet(audiences []string) audienceSet {
audSet := make(audienceSet, len(audiences))
for _, aud := range audiences {
audSet[aud] = struct{}{}
}
return audSet
}
func getUseWhitelist(allowedUse []string) []jwkset.USE {
if allowedUse == nil {
return []jwkset.USE{jwkset.UseSig}
}
useWhitelist := make([]jwkset.USE, len(allowedUse))
for i, u := range allowedUse {
useWhitelist[i] = jwkset.USE(u)
}
return useWhitelist
}
func createKeyFunc(ctx context.Context, options jwkset.HTTPClientOptions, useWhitelist []jwkset.USE) (keyfunc.Keyfunc, error) {
combined, err := jwkset.NewHTTPClient(options)
if err != nil {
return nil, fmt.Errorf("failed to create HTTP client storage for JWK provider: %w", err)
}
keyfuncOptions := keyfunc.Options{
Ctx: ctx,
Storage: combined,
UseWhitelist: useWhitelist,
}
jwks, err := keyfunc.New(keyfuncOptions)
if err != nil {
return nil, fmt.Errorf("error initializing JWK: %w", err)
}
return jwks, nil
}
// hasAudience is a common intersection function to check on the token's audiences
func hasAudience(tokenAudiences []string, expectedAudiences audienceSet) bool {
for _, item := range tokenAudiences {
if _, found := expectedAudiences[item]; found {
return true
}
}
return false
}