-
Notifications
You must be signed in to change notification settings - Fork 0
/
cors.go
488 lines (392 loc) · 12.6 KB
/
cors.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
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
481
482
483
484
485
486
487
488
// Package cors CORS filter middleware for Golang `net/http` handler.
// Like some other CORS filters (e.g. the Jetty's CORS filter), you can define your AllowedMethod list, even non standard. As default, AllowedMethods list is "GET,POST,HEAD,OPTIONS".
package cors
import (
"bytes"
"log"
"net/http"
"regexp"
"strconv"
"strings"
)
const (
// DefaultAllowedOrigin default origin allowed, as default all origins are allowed
DefaultAllowedOrigin = "*"
// DefaultAllowedMethods default allowed method, "OPTIONS" method must added if you want handle preflight request
DefaultAllowedMethods = http.MethodGet + "," + http.MethodPost + "," + http.MethodHead + "," + http.MethodOptions
// DefaultAllowedHeaders default allowed headers
DefaultAllowedHeaders = "Origin,Accept,Content-Type,Accept-Language,Content-Language,Last-Event-ID"
// DefaultMaxAge default number of seconds that preflight requests can be cached by the client.
DefaultMaxAge = 1800
// AccessControlAllowOrigin header
AccessControlAllowOrigin = "Access-Control-Allow-Origin"
// AccessControlExposeHeaders header
AccessControlExposeHeaders = "Access-Control-Expose-Headers"
// AccessControlControlMaxAge header
AccessControlControlMaxAge = "Access-Control-Max-Age"
// AccessControlAllowMethods header
AccessControlAllowMethods = "Access-Control-Allow-Methods"
// AccessControlAllowHeaders header
AccessControlAllowHeaders = "Access-Control-Allow-Headers"
// AccessControlAllowCredentials header
AccessControlAllowCredentials = "Access-Control-Allow-Credentials"
// AccessControlRequestMethod header
AccessControlRequestMethod = "Access-Control-Request-Method"
// AccessControlRequestHeaders header
AccessControlRequestHeaders = "Access-Control-Request-Headers"
// OriginHeader header
OriginHeader = "Origin"
// AcceptHeader header
AcceptHeader = "Accept"
// ContentTypeHeader header
ContentTypeHeader = "Content-Type"
// AllowHeader header
AllowHeader = "Allow"
// VaryHeader header
VaryHeader = "Vary"
// HostHeader header
HostHeader = "Header"
// OriginMatchAll header
OriginMatchAll = "*"
)
// Config cors filter configuration
type Config struct {
// AllowedOrigins comma separated list of allowed origins (default "*"), may contain whildchar ("*") for e.g. http://*.example.com
AllowedOrigins,
// AllowedMethods comma separated list of methods the client is allowed to use
AllowedMethods,
// AllowedHeaders comma separated list of non simple headers the client is allowed to use
AllowedHeaders,
// ExposedHeaders headers safe to expose
ExposedHeaders string
// MaxAge in seconds (exposed only if > 0) indicates how long the results of a preflight request can be cached
MaxAge int
// AllowCredentials if true, indicates that request whether include credentials
AllowCredentials bool
// ForwardRequest forward request after preflight
ForwardRequest bool
// Logger optional logger
Logger *log.Logger
}
// cors the filter struct
type cors struct {
logWrap func(format string, v ...interface{})
allowedRegexOrigins []*regexp.Regexp // store pre-compiled regular expression to match
allowedStaticOrigins []string // store static origin to match
allowedSuffixOrigins []string // store suffix origin to match
// the next tho maps are used to speedup match of headers and methods
allowedMethods map[string]bool
allowedHeaders map[string]bool
// the next two variable store the original strings, header can be in any case, but the match is byte-case-insensitive
allowedHeadersString string
allowedMethodsString string
hostName string
maxAge string
exposedHeaders string
exposeHeader bool
allowAllOrigins bool
allowAllHeaders bool
allowCredentials bool
forwardRequest bool
}
// allowed build maps of allowed values
func allowed(allowed [][]byte) (m map[string]bool) {
m = make(map[string]bool)
for _, a := range allowed {
m[string(a)] = true
}
return m
}
// toLowerCase convert s to lower case, s must contains only ASCII chars
func toLowerCase(s []byte) []byte {
for i, c := range s {
if 'A' <= c && c <= 'Z' {
s[i] = c ^ 0x20
}
}
return s
}
// trimSpace trim space of an ASCII array of byte (like the http headers)
func trimSpace(s []byte) []byte {
start := 0
end := len(s) - 1
if end > 0 && s[start] != ' ' && s[end] != ' ' {
return s
}
for ; start < len(s) && s[start] == ' '; start++ {
}
for ; end > start && s[end] == ' '; end-- {
}
return s[start : end+1]
}
// normalizeHeaders return an array of headers, in lower case and space trimmed.
// the header match is byte-case-insensitive
func normalizeHeaders(headers string) (ss [][]byte) {
const sep byte = ',' // headers separator
if len(headers) == 0 {
return
}
ss = make([][]byte, 0, 32) // assume that usually an header value contains less then 32 distinct values
start := 0
s := []byte(headers)
for i, c := range s {
// to lower case
if 'A' <= c && c <= 'Z' {
s[i] = c ^ 0x20
continue
}
// Skip separator in the head, in the tail, and or sequence like ",,,,"
if start == i && s[i] == sep {
start++
continue
}
if s[i] == sep {
tmp := trimSpace(s[start:i])
if len(tmp) > 0 {
ss = append(ss, tmp) // si può evitare l'append?
}
start = i + 1
}
}
// if start < len(s) , we need to copy the tail of the string
if start < len(s) {
tmp := trimSpace(s[start:])
if len(tmp) > 0 {
ss = append(ss, tmp)
}
}
return ss
}
// logInit convenient log wrapper initializer
func logInit(logger *log.Logger) func(format string, v ...interface{}) {
if logger == nil {
return func(format string, v ...interface{}) {}
}
return func(format string, v ...interface{}) {
logger.Printf("[cors] "+format, v...)
}
}
// initialize initialize the cors filter
func initialize(config Config) (c *cors) {
// assume some dafault
c = &cors{
allowedMethods: allowed(bytes.Split([]byte(DefaultAllowedMethods), []byte(","))),
allowedMethodsString: DefaultAllowedMethods,
allowedHeaders: allowed(normalizeHeaders(DefaultAllowedHeaders)),
allowedHeadersString: DefaultAllowedHeaders,
allowAllOrigins: true,
maxAge: "1800",
}
c.logWrap = logInit(config.Logger)
c.forwardRequest = config.ForwardRequest
if len(config.AllowedOrigins) > 0 && config.AllowedOrigins != "*" {
// origin match are key sensitive
origins := strings.Split(config.AllowedOrigins, ",")
// different type of origins...
for _, o := range origins {
if !strings.ContainsAny(o, "*") {
c.allowedStaticOrigins = append(c.allowedStaticOrigins, o)
} else if strings.Index(o, "*.") == 0 {
c.allowedSuffixOrigins = append(c.allowedSuffixOrigins, o[2:])
} else if strings.Count(o, "*") > 0 || strings.Count(o, "?") > 0 {
p := regexp.QuoteMeta(strings.TrimSpace(o))
p = strings.Replace(p, "\\*", ".*", -1)
p = strings.Replace(p, "\\?", ".", -1)
r := regexp.MustCompile(p)
c.allowedRegexOrigins = append(c.allowedRegexOrigins, r)
}
}
c.allowAllOrigins = false
}
if len(config.AllowedMethods) > 0 {
c.allowedMethods = allowed(bytes.Split(bytes.ToUpper([]byte(config.AllowedMethods)), []byte(",")))
c.allowedMethodsString = config.AllowedMethods
}
if len(config.AllowedHeaders) > 0 {
if config.AllowedHeaders == strings.TrimSpace("*") {
c.allowAllHeaders = true
c.allowedHeadersString = "*"
} else {
headers := normalizeHeaders(config.AllowedHeaders)
c.allowedHeaders = allowed(headers)
c.allowedHeadersString = config.AllowedHeaders
}
}
if config.MaxAge > 0 {
c.maxAge = strconv.Itoa(config.MaxAge)
}
if len(config.ExposedHeaders) > 0 {
c.exposedHeaders = config.ExposedHeaders
c.exposeHeader = true
}
if config.AllowCredentials && c.allowAllOrigins {
c.logWrap("Ignore AllowCredentials = true. It's a security issue set up AllowOrigin==* and AllowCredientials==true.")
} else {
c.allowCredentials = config.AllowCredentials
}
c.logWrap("Filter configuration [%s]", c)
return c
}
func (c *cors) String() string {
var s string
if c.allowAllOrigins {
s += "AllowedOrigins: *;"
} else {
s += "AllowedOrigins: "
for _, r := range c.allowedRegexOrigins {
s += r.String() + ","
}
s = s[:len(s)-1] + ";"
}
s += " AllowedHeaders: "
for k, v := range c.allowedHeaders {
if v {
s += k + ","
}
}
s = s[:len(s)-1] + ";"
s += " AllowedMethods: "
for k, v := range c.allowedMethods {
if v {
s += k + ","
}
}
s = s[:len(s)-1] + ";"
if c.exposeHeader {
s += " ExposeHeader: true;"
} else {
s += " ExposeHeader: false;"
}
s += " ExposedHeaders: " + c.exposedHeaders + ";"
s += " MaxAge: " + c.maxAge + ";"
if c.forwardRequest {
s += " ForwardRequest: true"
} else {
s += " ForwardRequest: false"
}
return s
}
// isOriginAllowed return true if the origin is allowed
func (c *cors) isOriginAllowed(origin string) bool {
if c.allowAllOrigins {
return true
}
for _, o := range c.allowedStaticOrigins {
if o == origin {
return true
}
}
for _, o := range c.allowedSuffixOrigins {
if len(origin) >= len(o) && strings.HasSuffix(origin, o) {
return true
}
}
for _, o := range c.allowedRegexOrigins {
if o.MatchString(origin) {
return true
}
}
return false
}
// isMethodAllowed return true if the method is allowed
func (c *cors) isMethodAllowed(method string) bool {
return c.allowedMethods[method]
}
// areReqHeadersAllowed return true if the request headers are allowed
func (c *cors) areReqHeadersAllowed(reqHeaders string) bool {
if c.allowAllHeaders || len(reqHeaders) == 0 {
return true
}
for _, header := range normalizeHeaders(reqHeaders) {
// check if header are allowed
// The compiler recognizes m[string(byteSlice)] as a special case, no conversion happens
if !c.allowedHeaders[string(header)] {
return false
}
}
return true
}
// Filter cors filter middleware
func Filter(config Config) (fn func(next http.Handler) http.Handler) {
c := initialize(config)
fn = func(next http.Handler) http.Handler {
// TODO: scorporare questa funzione per rendere più semplice l'integrazione con GIn e framework che usano HandlerFunc per i middleware
filter := func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get(OriginHeader)
// It's a same origin request ?
if origin == "" {
next.ServeHTTP(w, r)
return
}
// Allways add "Vary:Origin" header
w.Header().Add(VaryHeader, OriginHeader)
if !c.isOriginAllowed(origin) {
c.logWrap("Origin %+v from %s not allowed", origin, r.RemoteAddr)
w.WriteHeader(http.StatusForbidden)
// exit chain
return
}
// handle cors request common parts
if !c.isMethodAllowed(r.Method) {
c.logWrap("Request method %+v from %s not allowed", r.Method, r.RemoteAddr)
w.WriteHeader(http.StatusMethodNotAllowed)
// exit chain
return
}
// Ok, origin and method are allowed
w.Header().Add(AccessControlAllowOrigin, origin)
// if it's a simple cross-origin request, handle them
if r.Method != http.MethodOptions {
c.logWrap("Request from %+v", r.RemoteAddr)
if c.exposeHeader {
w.Header().Add(AccessControlExposeHeaders, c.exposedHeaders)
}
if c.allowCredentials {
w.Header().Add(AccessControlAllowCredentials, "true")
}
next.ServeHTTP(w, r)
return
}
// No, it's a prefligth request, handle them
// Add others value to Vary header
w.Header().Add(VaryHeader, AccessControlRequestMethod+", "+AccessControlRequestHeaders)
c.logWrap("Preflight request from %s", r.RemoteAddr)
acReqMethod := r.Header.Get(AccessControlRequestMethod)
if !c.isMethodAllowed(acReqMethod) {
c.logWrap("Preflight request not valid, requested method %s non allowed", acReqMethod)
w.WriteHeader(http.StatusMethodNotAllowed)
// exit chain
return
}
acReqHeaders := r.Header.Get(AccessControlRequestHeaders)
if !c.areReqHeadersAllowed(acReqHeaders) {
c.logWrap("Preflight request not valid, request headers not allowed")
w.WriteHeader(http.StatusForbidden)
// exit chain
return
}
w.Header().Add(AccessControlAllowMethods, c.allowedMethodsString)
if c.allowAllHeaders {
// return the list of requested headers
w.Header().Add(AccessControlAllowHeaders, acReqHeaders)
} else {
w.Header().Add(AccessControlAllowHeaders, c.allowedHeadersString)
}
if c.allowCredentials {
w.Header().Add(AccessControlAllowCredentials, "true")
}
if c.maxAge != "0" {
w.Header().Add(AccessControlControlMaxAge, c.maxAge)
}
// forward request if required
if c.forwardRequest {
next.ServeHTTP(w, r)
return
}
// exit chain with status HTTP 200
w.WriteHeader(http.StatusOK)
}
return http.HandlerFunc(filter)
}
return fn
}