forked from gofiber/jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwks.go
336 lines (281 loc) · 9.28 KB
/
jwks.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
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package jwtware
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"sync"
"time"
"github.com/golang-jwt/jwt/v4"
)
var ( // ErrKID indicates that the JWT had an invalid kid.
errMissingKeySet = errors.New("not able to download JWKs")
// errKID indicates that the JWT had an invalid kid.
errKID = errors.New("the JWT has an invalid kid")
// errUnsupportedKeyType indicates the JWT key type is an unsupported type.
errUnsupportedKeyType = errors.New("the JWT key type is unsupported")
// errKIDNotFound indicates that the given key ID was not found in the JWKs.
errKIDNotFound = errors.New("the given key ID was not found in the JWKs")
// errMissingAssets indicates there are required assets missing to create a public key.
errMissingAssets = errors.New("required assets are missing to create a public key")
)
// rawJWK represents a raw key inside a JWKs.
type rawJWK struct {
Curve string `json:"crv"`
Exponent string `json:"e"`
ID string `json:"kid"`
Modulus string `json:"n"`
X string `json:"x"`
Y string `json:"y"`
precomputed interface{}
}
// rawJWKs represents a JWKs in JSON format.
type rawJWKs struct {
Keys []rawJWK `json:"keys"`
}
// KeySet represents a JSON Web Key Set.
type KeySet struct {
Keys map[string]*rawJWK
Config *Config
cancel context.CancelFunc
client *http.Client
ctx context.Context
mux sync.RWMutex
refreshRequests chan context.CancelFunc
}
// keyFunc is a compatibility function that matches the signature of github.com/dgrijalva/jwt-go's keyFunc function.
func (j *KeySet) keyFunc() jwt.Keyfunc {
return func(token *jwt.Token) (interface{}, error) {
if j.Keys == nil {
err := j.downloadKeySet()
if err != nil {
return nil, fmt.Errorf("%w: key set URL is not accessible", errMissingKeySet)
}
}
// Get the kid from the token header.
kidInter, ok := token.Header["kid"]
if !ok {
return nil, fmt.Errorf("%w: could not find kid in JWT header", errKID)
}
kid, ok := kidInter.(string)
if !ok {
return nil, fmt.Errorf("%w: could not convert kid in JWT header to string", errKID)
}
// Get the JSONKey.
jsonKey, err := j.getKey(kid)
if err != nil {
return nil, err
}
// Determine the key's algorithm and return the appropriate public key.
switch keyAlg := token.Header["alg"]; keyAlg {
case ES256, ES384, ES512:
return jsonKey.getECDSA()
case PS256, PS384, PS512, RS256, RS384, RS512:
return jsonKey.getRSA()
default:
return nil, fmt.Errorf("%w: %s: feel free to add a feature request or contribute to https://github.com/MicahParks/keyfunc", errUnsupportedKeyType, keyAlg)
}
}
}
// downloadKeySet loads the JWKs at the given URL.
func (j *KeySet) downloadKeySet() (err error) {
// Apply some defaults if options were not provided.
if j.client == nil {
j.client = http.DefaultClient
}
// Get the keys for the JWKs.
if err = j.refresh(); err != nil {
return err
}
// Check to see if a background refresh of the JWKs should happen.
if j.Config.KeyRefreshInterval != nil || j.Config.KeyRefreshRateLimit != nil {
// Attach a context used to end the background goroutine.
j.ctx, j.cancel = context.WithCancel(context.Background())
// Create a channel that will accept requests to refresh the JWKs.
j.refreshRequests = make(chan context.CancelFunc, 1)
// Start the background goroutine for data refresh.
go j.startRefreshing()
}
return nil
}
// New creates a new JWKs from a raw JSON message.
func parseKeySet(jwksBytes json.RawMessage) (keys map[string]*rawJWK, err error) {
// Turn the raw JWKs into the correct Go type.
var rawKS rawJWKs
if err = json.Unmarshal(jwksBytes, &rawKS); err != nil {
return nil, err
}
// Iterate through the keys in the raw JWKs. Add them to the JWKs.
keys = make(map[string]*rawJWK, len(rawKS.Keys))
for _, key := range rawKS.Keys {
key := key
keys[key.ID] = &key
}
return keys, nil
}
// getKey gets the JSONKey from the given KID from the JWKs. It may refresh the JWKs if configured to.
func (j *KeySet) getKey(kid string) (jsonKey *rawJWK, err error) {
// Get the JSONKey from the JWKs.
var ok bool
j.mux.RLock()
jsonKey, ok = j.Keys[kid]
j.mux.RUnlock()
// Check if the key was present.
if !ok {
// Check to see if configured to refresh on unknown kid.
if *j.Config.KeyRefreshUnknownKID {
// Create a context for refreshing the JWKs.
ctx, cancel := context.WithCancel(j.ctx)
// Refresh the JWKs.
select {
case <-j.ctx.Done():
return
case j.refreshRequests <- cancel:
default:
// If the j.refreshRequests channel is full, return the error early.
return nil, errKIDNotFound
}
// Wait for the JWKs refresh to done.
<-ctx.Done()
// Lock the JWKs for async safe use.
j.mux.RLock()
defer j.mux.RUnlock()
// Check if the JWKs refresh contained the requested key.
if jsonKey, ok = j.Keys[kid]; ok {
return jsonKey, nil
}
}
return nil, errKIDNotFound
}
return jsonKey, nil
}
// startRefreshing is meant to be a separate goroutine that will update the keys in a JWKs over a given interval of
// time.
func (j *KeySet) startRefreshing() {
// Create some rate limiting assets.
var lastRefresh time.Time
var queueOnce sync.Once
var refreshMux sync.Mutex
if j.Config.KeyRefreshRateLimit != nil {
lastRefresh = time.Now().Add(-*j.Config.KeyRefreshRateLimit)
}
// Create a channel that will never send anything unless there is a refresh interval.
refreshInterval := make(<-chan time.Time)
// Enter an infinite loop that ends when the background ends.
for {
// If there is a refresh interval, create the channel for it.
if j.Config.KeyRefreshInterval != nil {
refreshInterval = time.After(*j.Config.KeyRefreshInterval)
}
// Wait for a refresh to occur or the background to end.
select {
// Send a refresh request the JWKs after the given interval.
case <-refreshInterval:
select {
case <-j.ctx.Done():
return
case j.refreshRequests <- func() {}:
default: // If the j.refreshRequests channel is full, don't don't send another request.
}
// Accept refresh requests.
case cancel := <-j.refreshRequests:
// Rate limit, if needed.
refreshMux.Lock()
if j.Config.KeyRefreshRateLimit != nil && lastRefresh.Add(*j.Config.KeyRefreshRateLimit).After(time.Now()) {
// Don't make the JWT parsing goroutine wait for the JWKs to refresh.
cancel()
// Only queue a refresh once.
queueOnce.Do(func() {
// Launch a goroutine that will get a reservation for a JWKs refresh or fail to and immediately return.
go func() {
// Wait for the next time to refresh.
refreshMux.Lock()
wait := time.Until(lastRefresh.Add(*j.Config.KeyRefreshRateLimit))
refreshMux.Unlock()
select {
case <-j.ctx.Done():
return
case <-time.After(wait):
}
// Refresh the JWKs.
refreshMux.Lock()
defer refreshMux.Unlock()
if err := j.refresh(); err != nil && j.Config.KeyRefreshErrorHandler != nil {
j.Config.KeyRefreshErrorHandler(j, err)
} else if err == nil && j.Config.KeyRefreshSuccessHandler != nil {
j.Config.KeyRefreshSuccessHandler(j)
}
// Reset the last time for the refresh to now.
lastRefresh = time.Now()
// Allow another queue.
queueOnce = sync.Once{}
}()
})
} else {
// Refresh the JWKs.
if err := j.refresh(); err != nil && j.Config.KeyRefreshErrorHandler != nil {
j.Config.KeyRefreshErrorHandler(j, err)
} else if err == nil && j.Config.KeyRefreshSuccessHandler != nil {
j.Config.KeyRefreshSuccessHandler(j)
}
// Reset the last time for the refresh to now.
lastRefresh = time.Now()
// Allow the JWT parsing goroutine to continue with the refreshed JWKs.
cancel()
}
refreshMux.Unlock()
// Clean up this goroutine when its context expires.
case <-j.ctx.Done():
return
}
}
}
// refresh does an HTTP GET on the JWKs URL to rebuild the JWKs.
func (j *KeySet) refresh() (err error) {
// Create a context for the request.
var ctx context.Context
var cancel context.CancelFunc
if j.ctx != nil {
ctx, cancel = context.WithTimeout(j.ctx, *j.Config.KeyRefreshTimeout)
} else {
ctx, cancel = context.WithTimeout(context.Background(), *j.Config.KeyRefreshTimeout)
}
defer cancel()
// Create the HTTP request.
var req *http.Request
if req, err = http.NewRequestWithContext(ctx, http.MethodGet, j.Config.KeySetURL, bytes.NewReader(nil)); err != nil {
return err
}
// Get the JWKs as JSON from the given URL.
var resp *http.Response
if resp, err = j.client.Do(req); err != nil {
return err
}
defer resp.Body.Close() // Ignore any error.
// Read the raw JWKs from the body of the response.
var jwksBytes []byte
if jwksBytes, err = ioutil.ReadAll(resp.Body); err != nil {
return err
}
// Create an updated JWKs.
var keys map[string]*rawJWK
if keys, err = parseKeySet(jwksBytes); err != nil {
return err
}
// Lock the JWKs for async safe usage.
j.mux.Lock()
defer j.mux.Unlock()
// Update the keys.
j.Keys = keys
return nil
}
// StopRefreshing ends the background goroutine to update the JWKs. It can only happen once and is only effective if the
// JWKs has a background goroutine refreshing the JWKs keys.
func (j *KeySet) StopRefreshing() {
if j.cancel != nil {
j.cancel()
}
}