forked from jub0bs/cors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil_test.go
278 lines (251 loc) · 7.38 KB
/
util_test.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
package cors_test
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"slices"
"sync/atomic"
"testing"
"github.com/jub0bs/cors"
)
const (
// common request headers
headerOrigin = "Origin"
// preflight-only request headers
headerACRPN = "Access-Control-Request-Private-Network"
headerACRM = "Access-Control-Request-Method"
headerACRH = "Access-Control-Request-Headers"
// common response headers
headerACAO = "Access-Control-Allow-Origin"
headerACAC = "Access-Control-Allow-Credentials"
// preflight-only response headers
headerACAPN = "Access-Control-Allow-Private-Network"
headerACAM = "Access-Control-Allow-Methods"
headerACAH = "Access-Control-Allow-Headers"
headerACMA = "Access-Control-Max-Age"
// actual-only response headers
headerACEH = "Access-Control-Expose-Headers"
headerVary = "Vary"
)
const (
varyPreflightValue = headerACRH + ", " + headerACRM + ", " +
headerACRPN + ", " + headerOrigin
wildcard = "*"
wildcardAndAuth = "*,authorization"
)
type MiddlewareTestCase struct {
desc string
outerMw *middleware
newHandler func() http.Handler
cfg *cors.Config
invalid bool
debug bool
cases []ReqTestCase
}
type ReqTestCase struct {
desc string
// request
reqMethod string
reqHeaders Headers
// expectations
preflight bool
preflightPassesCORSCheck bool
preflightFails bool
respHeaders Headers
}
// Headers represent a set of HTTP-header name-value pairs
// in which there are no duplicate names.
type Headers = map[string]string
func newRequest(method string, headers Headers) *http.Request {
const dummyEndpoint = "https://example.com/whatever"
req := httptest.NewRequest(method, dummyEndpoint, nil)
for name, value := range headers {
req.Header.Add(name, value)
}
return req
}
type spyHandler struct {
called atomic.Bool
statusCode int
respHeaders Headers
body string
handler http.Handler
}
func newSpyHandler(statusCode int, respHeaders Headers, body string) func() http.Handler {
f := func() http.Handler {
h := func(w http.ResponseWriter, r *http.Request) {
for k, v := range respHeaders {
w.Header().Add(k, v)
}
w.WriteHeader(statusCode)
if len(body) > 0 {
io.WriteString(w, body)
}
}
return &spyHandler{
statusCode: statusCode,
respHeaders: respHeaders,
body: body,
handler: http.HandlerFunc(h),
}
}
return f
}
func (s *spyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.called.Store(true)
s.handler.ServeHTTP(w, r)
}
var varyMiddleware = middleware{
hdrs: Headers{headerVary: "before"},
}
type middleware struct {
hdrs Headers
}
func (m middleware) Wrap(next http.Handler) http.Handler {
f := func(w http.ResponseWriter, r *http.Request) {
for k, v := range m.hdrs {
w.Header().Add(k, v)
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(f)
}
func assertPreflightStatus(t *testing.T, spyStatus, gotStatus int, mwtc *MiddlewareTestCase, tc *ReqTestCase) {
t.Helper()
var wantStatusCode int
switch {
case mwtc.cfg == nil:
wantStatusCode = spyStatus
case !tc.preflightPassesCORSCheck || !mwtc.debug && tc.preflightFails:
wantStatusCode = http.StatusForbidden
case mwtc.cfg.PreflightSuccessStatus == 0:
wantStatusCode = http.StatusNoContent
default:
wantStatusCode = mwtc.cfg.PreflightSuccessStatus
}
if gotStatus != wantStatusCode {
const tmpl = "got %d; want status code %d"
t.Errorf(tmpl, gotStatus, wantStatusCode)
}
}
// note: this function mutates got (to ease subsequent assertions)
func assertResponseHeaders(t *testing.T, got http.Header, want Headers) {
t.Helper()
for k, v := range want {
if !deleteHeaderValue(got, k, v) {
t.Errorf(`missing header value "%s: %s"`, k, v)
}
// clean up: remove headers whose values are empty but non-nil
if vs, found := got[k]; found && len(vs) == 0 {
delete(got, k)
}
}
}
func assertNoMoreResponseHeaders(t *testing.T, left http.Header) {
t.Helper()
for k, v := range left {
t.Errorf("unexpected header value(s) %q: %q", k, v)
}
}
func assertBody(t *testing.T, body io.ReadCloser, want string) {
t.Helper()
var buf bytes.Buffer
_, err := io.Copy(&buf, body)
if got := buf.String(); err != nil || got != want {
t.Errorf("got body %q; want body %q", got, want)
}
}
// deleteHeaderValue reports whether h contains a header named key
// that contains value.
// If that's the case, the key-value pair in question is removed from h.
func deleteHeaderValue(h http.Header, key, value string) bool {
vs, ok := h[key]
if !ok {
return false
}
i := slices.Index(vs, value)
if i == -1 {
return false
}
h[key] = slices.Delete(vs, i, i+1)
return true
}
func newMutatingHandler() http.Handler {
f := func(w http.ResponseWriter, r *http.Request) {
resHdrs := w.Header()
keys := []string{
headerACAO,
headerACAC,
headerACEH,
headerVary,
}
for _, k := range keys {
if v, ok := resHdrs[k]; ok && len(v) > 0 {
v[0] = "mutated!"
}
}
}
return http.HandlerFunc(f)
}
func assertConfigEqual(t *testing.T, got, want *cors.Config) {
t.Helper()
if got == nil && want != nil {
t.Fatal("got nil *Config; want non-nil")
}
if got != nil && want == nil {
t.Fatal("got non-nil *Config; want nil")
}
if want == nil {
return
}
// origins
if !slices.Equal(got.Origins, want.Origins) {
t.Errorf("Origins: got %q; want %q", got.Origins, want.Origins)
}
// credentialed
if got.Credentialed != want.Credentialed {
const tmpl = "Credentialed: got %t; want %t"
t.Errorf(tmpl, got.Credentialed, want.Credentialed)
}
// methods
if !slices.Equal(got.Methods, want.Methods) {
t.Errorf("Methods: got %q; want %q", got.Methods, want.Methods)
}
// request headers
if !slices.Equal(got.RequestHeaders, want.RequestHeaders) {
const tmpl = "RequestHeaders: got %q; want %q"
t.Errorf(tmpl, got.RequestHeaders, want.RequestHeaders)
}
// max age
if got.MaxAgeInSeconds != want.MaxAgeInSeconds {
const tmpl = "MaxAgeInSeconds: got %d; want %d"
t.Errorf(tmpl, got.MaxAgeInSeconds, want.MaxAgeInSeconds)
}
// response headers
if !slices.Equal(got.ResponseHeaders, want.ResponseHeaders) {
const tmpl = "ResponseHeaders: got %q; want %q"
t.Errorf(tmpl, got.ResponseHeaders, want.ResponseHeaders)
}
// extra config
if got.PreflightSuccessStatus != want.PreflightSuccessStatus {
const tmpl = "PreflightSuccessStatus: got %d; want %d"
t.Errorf(tmpl, got.PreflightSuccessStatus, want.PreflightSuccessStatus)
}
if got.PrivateNetworkAccess != want.PrivateNetworkAccess {
const tmpl = "PrivateNetworkAccess: got %t; want %t"
t.Errorf(tmpl, got.PrivateNetworkAccess, want.PrivateNetworkAccess)
}
if got.PrivateNetworkAccessInNoCORSModeOnly != want.PrivateNetworkAccessInNoCORSModeOnly {
const tmpl = "PrivateNetworkAccessInNoCORSModeOnly: got %t; want %t"
t.Errorf(tmpl, got.PrivateNetworkAccessInNoCORSModeOnly, want.PrivateNetworkAccessInNoCORSModeOnly)
}
if got.DangerouslyTolerateInsecureOrigins != want.DangerouslyTolerateInsecureOrigins {
const tmpl = "DangerouslyTolerateInsecureOrigins: got %t; want %t"
t.Errorf(tmpl, got.DangerouslyTolerateInsecureOrigins, want.DangerouslyTolerateInsecureOrigins)
}
if got.DangerouslyTolerateSubdomainsOfPublicSuffixes != want.DangerouslyTolerateSubdomainsOfPublicSuffixes {
const tmpl = "DangerouslyTolerateSubdomainsOfPublicSuffixes: got %t; want %t"
t.Errorf(tmpl, got.DangerouslyTolerateSubdomainsOfPublicSuffixes, want.DangerouslyTolerateSubdomainsOfPublicSuffixes)
}
}