-
Notifications
You must be signed in to change notification settings - Fork 2
/
cors.go
285 lines (242 loc) · 8.1 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
// Copyright (c) Jeevanandam M. (https://github.com/jeevatkm)
// go-aah/router source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package router
import (
"bytes"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"aahframework.org/ahttp.v0"
"aahframework.org/config.v0"
"aahframework.org/essentials.v0"
"aahframework.org/log.v0"
)
const allowAll = "*"
// CORS errors
var (
ErrCORSOriginIsInvalid = errors.New("cors: invalid origin")
ErrCORSMethodNotAllowed = errors.New("cors: method not allowed")
ErrCORSHeaderNotAllowed = errors.New("cors: header not allowed")
ErrCORSContentTypeNotAllowed = errors.New("cors: content-type not allowed")
// Excluded simple allowed headers and adding sensiable allowed headers.
// Refer to: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
defaultAllowHeaders = []string{ahttp.HeaderOrigin, ahttp.HeaderAccept,
ahttp.HeaderAcceptLanguage, ahttp.HeaderAuthorization}
// Sensiable default allowed methods
defaultAllowMethods = []string{ahttp.MethodGet, ahttp.MethodHead, ahttp.MethodPost}
)
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// CORS
//______________________________________________________________________________
// CORS struct holds Cross-Origin Resource Sharing (CORS) configuration
// values and verification methods for the route.
//
// Spec: https://www.w3.org/TR/cors/
// Friendly Read: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
type CORS struct {
AllowCredentials bool
allowAllOrigins bool
allowAllMethods bool
allowAllHeaders bool
MaxAge string
maxAgeStr string
AllowOrigins []string
AllowMethods []string
AllowHeaders []string
ExposeHeaders []string
}
// AddOrigins method adds the given origin into allow origin list.
func (c *CORS) AddOrigins(origins []string) *CORS {
for _, o := range origins {
if o == allowAll {
c.allowAllOrigins = true
c.AllowOrigins = []string{allowAll}
break
}
o = strings.ToLower(o)
if !ess.IsSliceContainsString(c.AllowOrigins, o) {
c.AllowOrigins = append(c.AllowOrigins, o)
}
}
return c
}
// AddAllowHeaders method adds the given HTTP header into allow headers list.
func (c *CORS) AddAllowHeaders(hdrs []string) *CORS {
c.AllowHeaders = c.addHeaders(c.AllowHeaders, hdrs)
if ess.IsSliceContainsString(c.AllowHeaders, allowAll) {
c.allowAllHeaders = true
c.AllowHeaders = []string{allowAll}
}
return c
}
// AddAllowMethods method adds the given HTTP verb into allow methods list.
func (c *CORS) AddAllowMethods(methods []string) *CORS {
for _, m := range methods {
if m == allowAll {
c.allowAllMethods = true
c.AllowMethods = []string{allowAll}
break
}
m = strings.ToUpper(strings.TrimSpace(m))
if !ess.IsStrEmpty(m) && !ess.IsSliceContainsString(c.AllowMethods, m) {
c.AllowMethods = append(c.AllowMethods, m)
}
}
return c
}
// AddExposeHeaders method adds the given HTTP header into expose headers list.
func (c *CORS) AddExposeHeaders(hdrs []string) *CORS {
c.ExposeHeaders = c.addHeaders(c.ExposeHeaders, hdrs)
return c
}
// SetMaxAge method parses the given duration string into seconds and adds to CORS.
// `time.ParseDuration` method time units are supported.
func (c *CORS) SetMaxAge(age string) *CORS {
if dur, err := time.ParseDuration(age); err == nil {
c.MaxAge = strconv.Itoa(int(dur.Seconds()))
} else {
log.Errorf("Unable to parse CORS 'max_age' value '%v'", age)
}
return c
}
// SetAllowCredentials method sets the given boolean into allow credentials.
func (c *CORS) SetAllowCredentials(b bool) *CORS {
c.AllowCredentials = b
return c
}
// IsOriginAllowed method check given origin is allowed or not.
func (c *CORS) IsOriginAllowed(origin string) bool {
if len(origin) == 0 {
return false
}
if c.allowAllOrigins {
return true
}
return ess.IsSliceContainsString(c.AllowOrigins, strings.ToLower(origin))
}
// IsMethodAllowed method returns true if preflight method is allowed otherwise
// false.
func (c *CORS) IsMethodAllowed(method string) bool {
if c.allowAllMethods {
return true
}
return ess.IsSliceContainsString(c.AllowMethods, method)
}
// IsHeadersAllowed method returns true if preflight headers are allowed otherwise
// false.
func (c *CORS) IsHeadersAllowed(hdrs string) bool {
if c.allowAllHeaders || len(hdrs) == 0 {
return true
}
for _, h := range strings.Split(hdrs, ",") {
h = http.CanonicalHeaderKey(strings.TrimSpace(h))
allowed := false
if ess.IsSliceContainsString(c.AllowHeaders, h) {
allowed = true
}
if !allowed {
return false
}
}
return true
}
// String method returns string representation of CORS configuration values.
func (c CORS) String() string {
buf := new(bytes.Buffer)
buf.WriteString("cors(allow-origins:")
buf.WriteString(strings.Join(c.AllowOrigins, ","))
buf.WriteString(" allow-headers:")
buf.WriteString(strings.Join(c.AllowHeaders, ","))
buf.WriteString(" allow-methods:")
buf.WriteString(strings.Join(c.AllowMethods, ","))
buf.WriteString(" expose-headers:")
buf.WriteString(strings.Join(c.ExposeHeaders, ","))
buf.WriteString(fmt.Sprintf(" allow-credentials:%v", c.AllowCredentials))
buf.WriteString(fmt.Sprintf(" max-age:%s", c.maxAgeStr))
buf.WriteByte(')')
return buf.String()
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Unexported CORS methods
//______________________________________________________________________________
func (c *CORS) addHeaders(dst []string, src []string) []string {
for _, h := range src {
if h == allowAll {
return []string{allowAll}
}
h = http.CanonicalHeaderKey(strings.TrimSpace(h))
if !ess.IsStrEmpty(h) && !ess.IsSliceContainsString(dst, h) {
dst = append(dst, h)
}
}
return dst
}
func processBaseCORSSection(cfg *config.Config) *CORS {
cors := &CORS{}
// Access-Control-Allow-Origin
if origins, found := cfg.StringList("allow_origins"); found {
cors.AddOrigins(origins)
} else {
cors.AddOrigins([]string{allowAll})
}
// Access-Control-Allow-Headers
if hdrs, found := cfg.StringList("allow_headers"); found {
cors.AddAllowHeaders(hdrs)
} else {
cors.AddAllowHeaders(defaultAllowHeaders)
}
// Access-Control-Allow-Methods
if methods, found := cfg.StringList("allow_methods"); found {
cors.AddAllowMethods(methods)
} else {
cors.AddAllowMethods(defaultAllowMethods)
}
cors.AddAllowMethods([]string{ahttp.MethodOptions})
// Access-Control-Allow-Credentials
cors.SetAllowCredentials(cfg.BoolDefault("allow_credentials", false))
// Access-Control-Expose-Headers
if hdrs, found := cfg.StringList("expose_headers"); found {
cors.AddExposeHeaders(hdrs)
}
// Access-Control-Max-Age
cors.maxAgeStr = cfg.StringDefault("max_age", "24h")
cors.SetMaxAge(cors.maxAgeStr)
return cors
}
func processCORSSection(cfg *config.Config, parent *CORS) *CORS {
cors := &CORS{}
// Access-Control-Allow-Origin
if origins, found := cfg.StringList("allow_origins"); found {
cors.AddOrigins(origins)
} else {
cors.AddOrigins(parent.AllowOrigins)
}
// Access-Control-Allow-Headers
if hdrs, found := cfg.StringList("allow_headers"); found {
cors.AddAllowHeaders(hdrs)
} else {
cors.AddAllowHeaders(parent.AllowHeaders)
}
// Access-Control-Allow-Methods
if methods, found := cfg.StringList("allow_methods"); found {
cors.AddAllowMethods(methods)
} else {
cors.AddAllowMethods(parent.AllowMethods)
}
// Access-Control-Allow-Credentials
cors.SetAllowCredentials(cfg.BoolDefault("allow_credentials", parent.AllowCredentials))
// Access-Control-Expose-Headers
if hdrs, found := cfg.StringList("expose_headers"); found {
cors.AddExposeHeaders(hdrs)
} else {
cors.AddExposeHeaders(parent.ExposeHeaders)
}
// Access-Control-Max-Age
cors.maxAgeStr = cfg.StringDefault("max_age", parent.maxAgeStr)
cors.SetMaxAge(cors.maxAgeStr)
return cors
}