-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmiddleware.go
More file actions
480 lines (446 loc) · 16.6 KB
/
Copy pathmiddleware.go
File metadata and controls
480 lines (446 loc) · 16.6 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
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
package cors
import (
"net/http"
"sync/atomic"
"github.com/jub0bs/cors/internal/headers"
"github.com/jub0bs/cors/internal/methods"
"github.com/jub0bs/cors/internal/origins"
)
// A Middleware is a CORS middleware.
// Call [*Middleware.Wrap] to apply a middleware to a [http.Handler].
//
// The zero value is ready to use but is a mere "passthrough" middleware,
// i.e. a middleware that simply delegates to the handler(s) it wraps.
// To obtain a proper CORS middleware, you should call [NewMiddleware]
// and pass it a valid [Config].
//
// Middleware have a debug mode, which can be turned on or off via
// [*Middleware.SetDebug] and queried via [*Middleware.Debug].
// You should turn debug mode on whenever you're struggling to troubleshoot
// some [CORS-preflight] issue:
// - When debug mode is off, the information that the middleware includes in
// preflight responses is minimal, for better performance;
// however, when preflight fails, the browser then lacks enough contextual
// information about the failure to produce a helpful CORS error message.
// - When debug mode is on and preflight fails,
// the middleware includes enough contextual information about the
// preflight failure in the response for browsers to produce
// a helpful CORS error message.
//
// However, be aware that keeping debug mode on may lead to observably poorer
// middleware performance, especially in the face of some adversarial preflight
// requests.
//
// Note that, even when debug mode is off, a middleware's configuration is not
// considered confidential; in particular, any endpoint configured for CORS can
// be abused as an oracle in order to reveal, perhaps at the cost of spoofing
// many CORS requests, which origins its CORS configuration allows.
//
// A Middleware must not be copied after first use.
//
// Middleware are safe for concurrent use by multiple goroutines.
// Therefore, you are free to expose some or all of their methods
// so you can exercise them without having to restart your server;
// however, if you do expose those methods, you should only do so on some
// internal or authorized endpoints, for security reasons.
//
// [CORS-preflight]: https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
type Middleware struct {
icfg atomic.Pointer[internalConfig]
debug atomic.Bool
}
// NewMiddleware creates a CORS middleware that behaves in accordance with cfg.
// If cfg is invalid, it returns a nil [*Middleware] and some non-nil error.
// Otherwise, it returns a pointer to a CORS [Middleware] and a nil error.
//
// The debug mode of the resulting middleware is off.
//
// Mutating the fields of cfg after NewMiddleware has returned a functioning
// middleware does not alter the latter's behavior.
// However, you can reconfigure a [Middleware] via its
// [*Middleware.Reconfigure] method.
//
// If you need to programmatically handle the configuration errors constitutive
// of the resulting error, rely on package [github.com/jub0bs/cors/cfgerrors].
func NewMiddleware(cfg Config) (*Middleware, error) {
var m Middleware
if err := m.Reconfigure(&cfg); err != nil {
return nil, err
}
return &m, nil
}
// Reconfigure reconfigures m in accordance with cfg,
// leaving m's debug mode unchanged.
// If cfg is nil, it turns m into a passthrough middleware.
// If *cfg is invalid, it leaves m unchanged and returns some non-nil error.
// Otherwise, it successfully reconfigures m and returns a nil error.
// The following statement is guaranteed to be a no-op
// (albeit a relatively expensive one):
//
// m.Reconfigure(m.Config())
//
// Note that
//
// mw := new(cors.Middleware)
// err := mw.Reconfigure(&cfg)
//
// is functionally equivalent to
//
// mw, err := cors.NewMiddleware(cfg)
//
// You can safely reconfigure a middleware
// even as it's concurrently handling requests.
//
// Mutating the fields of cfg after Reconfigure has returned does not alter
// m's behavior.
//
// If you need to programmatically handle the configuration errors constitutive
// of the resulting error, rely on package [github.com/jub0bs/cors/cfgerrors].
func (m *Middleware) Reconfigure(cfg *Config) error {
// Rather than attempt to diff the new config against the current one,
// we simply start from scratch; for common configurations, doing so indeed
// is performant enough.
icfg, err := newInternalConfig(cfg)
if err != nil {
return err
}
m.icfg.Store(icfg)
return nil
}
// Wrap applies the CORS middleware to the specified handler.
func (m *Middleware) Wrap(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
icfg := m.icfg.Load()
if icfg == nil { // passthrough middleware
h.ServeHTTP(w, r)
return
}
isOPTIONS := r.Method == http.MethodOptions
// Fetch-compliant browsers send at most one Origin header;
// see https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
// (step 12).
origin, found := headers.First(r.Header, headers.Origin)
if !found {
// r is NOT a CORS request;
// see https://fetch.spec.whatwg.org/#cors-request.
icfg.prehandleActual(w.Header(), nil, isOPTIONS)
h.ServeHTTP(w, r)
return
}
// r is a CORS request (and possibly a CORS-preflight request);
// see https://fetch.spec.whatwg.org/#cors-request.
// Fetch-compliant browsers send at most one ACRM header;
// see https://fetch.spec.whatwg.org/#cors-preflight-fetch (step 3).
acrm, found := headers.First(r.Header, headers.ACRM)
if isOPTIONS && found {
// r is a CORS-preflight request;
// see https://fetch.spec.whatwg.org/#cors-preflight-request.
icfg.handleCORSPreflight(w, r.Header, origin, acrm, m.debug.Load())
return
}
// r is an "actual" (i.e. non-preflight) CORS request.
icfg.prehandleActual(w.Header(), origin, isOPTIONS)
h.ServeHTTP(w, r)
})
}
func (icfg *internalConfig) prehandleActual(
resHdrs http.Header,
origin *[1]string,
isOPTIONS bool,
) {
if icfg.allowsAnyOrigin() {
resHdrs[headers.ACAO] = []string{headers.ValueWildcard}
if icfg.aceh != "" {
// If any origin is allowed, do include ACEH even in responses to
// non-CORS requests; see
// https://github.com/whatwg/fetch/issues/1601#issuecomment-1420881527.
resHdrs[headers.ACEH] = []string{icfg.aceh}
}
return
}
// Not all origins are allowed.
if isOPTIONS {
// Even though some caching intermediaries can be configured to cache
// responses to OPTIONS requests, such caching contravenes RFC 9110;
// see https://httpwg.org/specs/rfc9110.html#rfc.section.9.3.7.
// Some CORS middleware libraries (such as github.com/rs/cors) do cater
// for such non-compliant behavior; let's not.
} else {
// See https://fetch.spec.whatwg.org/#cors-protocol-and-http-caches.
// Note that we deliberately list "Origin" in the Vary header of
// responses to actual requests even in cases where a single origin is
// allowed, because doing so is simpler to implement and unlikely to
// be detrimental to Web caches. Moreover, official guidance about this
// special case is likely to change; see
// https://github.com/whatwg/fetch/issues/1601#issuecomment-1418899997.
//
// Note that we must add (rather than set) a Vary header here, because
// outer middleware may have already added/set a Vary header, which we
// wouldn't want to clobber.
resHdrs.Add(headers.Vary, headers.Origin)
}
if isCORSRequest := origin != nil; !isCORSRequest {
return
}
// This is a CORS request.
o, ok := origins.Parse(origin[0])
if !ok || !icfg.tree.Contains(&o) {
return
}
// origin is allowed.
resHdrs[headers.ACAO] = origin[:]
if icfg.credentialed {
// We make no attempt to infer whether the request is credentialed;
// in fact, a request’s credentials mode is not necessarily observable
// on the server.
// Instead, we systematically include "ACAC: true" if credentialed
// access is enabled and request's origin is allowed.
// See https://fetch.spec.whatwg.org/#example-xhr-credentials.
resHdrs[headers.ACAC] = []string{headers.ValueTrue}
}
if icfg.aceh != "" {
resHdrs[headers.ACEH] = []string{icfg.aceh}
}
}
func (icfg *internalConfig) handleCORSPreflight(
w http.ResponseWriter,
reqHdrs http.Header,
origin *[1]string,
acrm *[1]string,
debug bool,
) {
// Some notes about Vary in the context of CORS preflight:
// - Contrary to popular belief, the presence of a Vary header in
// responses to preflight requests has no bearing on the behavior of
// browsers' CORS-preflight cache;
// see https://fetch.spec.whatwg.org/#concept-cache and
// https://stackoverflow.com/a/42849375/2541573.
// - Even though some caching intermediaries can be configured to cache
// responses to OPTIONS requests, such caching contravenes RFC 9110;
// see https://httpwg.org/specs/rfc9110.html#rfc.section.9.3.7.
// Some CORS middleware libraries (such as github.com/rs/cors) do cater
// for such non-compliant behavior; let's not.
// When debug is on and a preflight step fails,
// we omit the remaining CORS response headers
// and let the browser fail the CORS-preflight fetch;
// however, for easier troubleshooting on the client side,
// we do respond with an ok status.
//
// When debug is off and preflight fails,
// we omit all CORS headers from the preflight response.
if !icfg.preflight && !debug {
w.WriteHeader(preflightFailStatus)
return
}
var buf preflightBuffer
resHdrs := w.Header()
// For details about the order in which we perform the following checks,
// see https://fetch.spec.whatwg.org/#cors-preflight-fetch, item 7.
if !icfg.performCORSCheckForPreflight(&buf, origin) {
if debug {
buf.flushTo(resHdrs)
}
w.WriteHeader(preflightFailStatus)
return
}
// At this stage, browsers fail the CORS-preflight check
// (see https://fetch.spec.whatwg.org/#cors-preflight-fetch-0, step 7)
// if the response status is not an ok status
// (see https://fetch.spec.whatwg.org/#ok-status).
if !icfg.processACRM(&buf, acrm) {
if debug {
buf.flushTo(resHdrs)
w.WriteHeader(preflightOKStatus)
return
}
w.WriteHeader(preflightFailStatus)
return
}
if !icfg.processACRH(&buf, reqHdrs, debug) {
if debug {
buf.flushTo(resHdrs)
w.WriteHeader(preflightOKStatus)
return
}
w.WriteHeader(preflightFailStatus)
return
}
// Preflight was successful.
buf.flushTo(resHdrs)
if icfg.acma != "" {
resHdrs[headers.ACMA] = []string{icfg.acma}
}
w.WriteHeader(preflightOKStatus)
}
func (icfg *internalConfig) performCORSCheckForPreflight(
buf *preflightBuffer,
origin *[1]string,
) bool {
if icfg.allowsAnyOrigin() {
buf.add(headers.ACAO, []string{headers.ValueWildcard})
return true
}
// Not all origins are allowed.
o, ok := origins.Parse(origin[0])
if !ok || !icfg.tree.Contains(&o) {
return false
}
// origin is allowed.
buf.add(headers.ACAO, origin[:])
if icfg.credentialed {
// We make no attempt to infer whether the request is credentialed,
// simply because preflight requests don't carry credentials;
// see https://fetch.spec.whatwg.org/#example-xhr-credentials.
buf.add(headers.ACAC, []string{headers.ValueTrue})
}
return true
}
func (icfg *internalConfig) allowsAnyOrigin() bool {
return icfg.tree.IsEmpty()
}
func (icfg *internalConfig) processACRM(
buf *preflightBuffer,
acrm *[1]string,
) bool {
// Note that middleware only ever list a single method in the ACAM header.
// One inconvenience of this behavior is that it leads to less than ideal
// utilization of the CORS-preflight cache;
// see https://fetch.spec.whatwg.org/#cors-preflight-cache.
//
// However, one advantage of this behavior is that responses to
// CORS-preflight requests disclose no other allowed methods than the one
// required for preflight to succeed.
switch method := acrm[0]; {
case methods.IsSafelisted(method):
// CORS-safelisted methods get a free pass; see
// https://fetch.spec.whatwg.org/#ref-for-cors-safelisted-method%E2%91%A2.
// Therefore, no ACAM header needs be set in this case.
return true
case icfg.allowAnyMethod && !icfg.credentialed:
buf.add(headers.ACAM, []string{headers.ValueWildcard})
return true
case icfg.allowAnyMethod || icfg.allowedMethods.Contains(method):
buf.add(headers.ACAM, acrm[:])
return true
default:
return false
}
}
func (icfg *internalConfig) processACRH(
buf *preflightBuffer,
reqHdrs http.Header,
debug bool,
) bool {
// Fetch-compliant browsers send at most one ACRH header line;
// see https://fetch.spec.whatwg.org/#cors-preflight-fetch-0 (step 5).
// However, some intermediaries may well
// (and some reportedly do) split it into multiple ACRH header lines;
// see https://github.com/rs/cors/issues/184.
acrh, found := reqHdrs[headers.ACRH]
if !found {
return true
}
switch {
case icfg.wildcardRequestHeaders && icfg.credentialed:
// If credentialed access is enabled, the single-asterisk pattern
// denotes all request-header names, including Authorization.
// Therefore, users of jub0bs/cors cannot both
// - allow credentialed access, and
// - allow all request-header names other than Authorization.
//
// This limitation is the result of a deliberate design choice:
// 1. Rare are the cases where all request-header names other than
// Authorization should be allowed with credentialed access
// enabled.
// 2. Because jub0bs/cors prohibits its users from allowing all
// origins with credentialed access, allowing all request headers
// from select origins along with credentialed access presents
// little risk for security.
// 3. If we followed an alternative approach in which * doesn't cover
// Authorization, we would need to scan the ACRH header in search
// of "authorization"; such a computation would introduce
// performance issues. Moreover, if "authorization" were found in
// ACRH, we couldn't simply echo ACRH in ACAH, because we'd have
// to omit "authorization" in ACAH. Incidentally, this could be
// achieved without incurring heap allocations, e.g. by cutting
// ACRH around "authorization" and echoing the results in up to two
// ACAH header(s); but the whole alternative approach is not worth
// the trouble anyway.
//
// We can simply reflect all the ACRH header lines as ACAH header lines
// because the Fetch standard requires browsers to handle multiple ACAH
// header lines;
// see https://fetch.spec.whatwg.org/#cors-preflight-fetch-0.
buf.add(headers.ACAH, acrh)
return true
case icfg.wildcardRequestHeaders && !icfg.credentialed:
buf.add(headers.ACAH, []string{icfg.acah})
return true
case debug:
if icfg.acah == "" {
return false
}
buf.add(headers.ACAH, []string{icfg.acah})
return true
case headers.Check(icfg.allowedRequestHeaders, acrh):
// We can simply reflect all the ACRH header lines as ACAH header lines
// because the Fetch standard requires browsers to handle multiple ACAH
// header lines;
// see https://fetch.spec.whatwg.org/#cors-preflight-fetch-0.
buf.add(headers.ACAH, acrh)
return true
default:
return false
}
}
// A preflightBuffer accumulates up to four header name-value pairs destined to
// later be flushed to a preflight response's headers.
//
// Benchmark results indicate that this is faster than a buffer simply
// consisting in a http.Header (or even a slice).
type preflightBuffer struct {
pairs [4]pair // enough to hold ACAO, ACAC, ACAM, and ACAH
len uint
}
type pair struct {
name string
val []string
}
// add adds a header name-value pair to buf. Caution: it
// - doesn't check for duplicate names, and
// - must not be called more than four times.
func (buf *preflightBuffer) add(name string, val []string) {
i := buf.len % 4 // Eliminate bounds check below.
buf.pairs[i] = pair{name: name, val: val}
buf.len++
}
// flushTo iterates over the header name-value pairs stored in buf
// and upserts each one of them in hdrs.
func (buf preflightBuffer) flushTo(hdrs http.Header) {
hi := min(buf.len, 4) // Eliminate bounds check below.
for _, pair := range buf.pairs[:hi] {
hdrs[pair.name] = pair.val
}
}
// SetDebug turns debug mode on (if b is true) or off (otherwise).
func (m *Middleware) SetDebug(b bool) {
m.debug.Store(b)
}
// Debug reports whether m's debug mode is on.
func (m *Middleware) Debug() bool {
return m.debug.Load()
}
// Config returns a pointer to a deep copy of m's current configuration;
// if m is a passthrough middleware, Config simply returns nil.
// The result may differ from the [Config] with which m was created or last
// reconfigured, but the following statement is guaranteed to be a no-op
// (albeit a relatively expensive one):
//
// m.Reconfigure(m.Config())
//
// Mutating the fields of the result does not alter m's behavior.
// However, you can reconfigure a [Middleware] via its
// [*Middleware.Reconfigure] method.
func (m *Middleware) Config() *Config {
return newConfig(m.icfg.Load())
}