forked from MicahParks/keyfunc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get.go
223 lines (178 loc) · 5.36 KB
/
get.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
package keyfunc
import (
"bytes"
"context"
"io/ioutil"
"net/http"
"sync"
"time"
)
var (
// defaultRefreshTimeout is the default duration for the context used to create the HTTP request for a refresh of
// the JWKs.
defaultRefreshTimeout = time.Minute
)
// Get loads the JWKs at the given URL.
func Get(jwksURL string, options ...Options) (jwks *JWKs, err error) {
// Create the JWKs.
jwks = &JWKs{
jwksURL: jwksURL,
}
// Apply the options to the JWKs.
for _, opts := range options {
applyOptions(jwks, opts)
}
// Apply some defaults if options were not provided.
if jwks.client == nil {
jwks.client = http.DefaultClient
}
if jwks.refreshTimeout == nil {
jwks.refreshTimeout = &defaultRefreshTimeout
}
// Get the keys for the JWKs.
if err = jwks.refresh(); err != nil {
return nil, err
}
// Check to see if a background refresh of the JWKs should happen.
if jwks.refreshInterval != nil || jwks.refreshUnknownKID {
// Attach a context used to end the background goroutine.
jwks.ctx, jwks.cancel = context.WithCancel(context.Background())
// Create a channel that will accept requests to refresh the JWKs.
jwks.refreshRequests = make(chan context.CancelFunc, 1)
// Start the background goroutine for data refresh.
go jwks.backgroundRefresh()
}
return jwks, nil
}
// backgroundRefresh is meant to be a separate goroutine that will update the keys in a JWKs over a given interval of
// time.
func (j *JWKs) backgroundRefresh() {
// Create some rate limiting assets.
var lastRefresh time.Time
var queueOnce sync.Once
var refreshMux sync.Mutex
if j.refreshRateLimit != nil {
lastRefresh = time.Now().Add(-*j.refreshRateLimit)
}
// 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.refreshInterval != nil {
refreshInterval = time.After(*j.refreshInterval)
}
// 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 send another request.
}
// Accept refresh requests.
case cancel := <-j.refreshRequests:
// Rate limit, if needed.
refreshMux.Lock()
if j.refreshRateLimit != nil && lastRefresh.Add(*j.refreshRateLimit).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.refreshRateLimit))
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.refreshErrorHandler != nil {
j.refreshErrorHandler(err)
}
// 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.refreshErrorHandler != nil {
j.refreshErrorHandler(err)
}
// 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 *JWKs) 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.refreshTimeout)
} else {
ctx, cancel = context.WithTimeout(context.Background(), *j.refreshTimeout)
}
defer cancel()
// Create the HTTP request.
var req *http.Request
if req, err = http.NewRequestWithContext(ctx, http.MethodGet, j.jwksURL, 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 updated *JWKs
if updated, err = NewJSON(jwksBytes); err != nil {
return err
}
// Lock the JWKs for async safe usage.
j.mux.Lock()
defer j.mux.Unlock()
// Update the keys.
j.keys = updated.keys
// If given keys were provided, add them back into the refreshed JWKs.
var ok bool
if j.givenKeys != nil {
for kid, key := range j.givenKeys {
// Only overwrite the key if configured to do so.
if !j.givenKIDOverride {
if _, ok = j.keys[kid]; ok {
continue
}
}
// Write the given key to the JWKs.
j.keys[kid] = &jsonKey{
precomputed: key.precomputed,
}
}
}
return nil
}