Debian Codegraph @

csrf_test.go

raw
1 package csrf
2
3 import (
4 "fmt"
5 "net/http"
6 "net/http/httptest"
7 "strings"
8 "testing"
9 )
10
11 var testKey = []byte("keep-it-secret-keep-it-safe-----")
12 var testHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
13
14 // TestProtect is a high-level test to make sure the middleware returns the
15 // wrapped handler with a 200 OK status.
16 func TestProtect(t *testing.T) {
17 s := http.NewServeMux()
18 s.HandleFunc("/", testHandler)
19
20 r := createRequest("GET", "/", false)
21
22 rr := httptest.NewRecorder()
23 p := Protect(testKey)(s)
24 p.ServeHTTP(rr, r)
25
26 if rr.Code != http.StatusOK {
27 t.Fatalf("middleware failed to pass to the next handler: got %v want %v",
28 rr.Code, http.StatusOK)
29 }
30
31 if rr.Header().Get("Set-Cookie") == "" {
32 t.Fatalf("cookie not set: got %q", rr.Header().Get("Set-Cookie"))
33 }
34
35 cookie := rr.Header().Get("Set-Cookie")
36 if !strings.Contains(cookie, "HttpOnly") || !strings.Contains(cookie,
37 "Secure") {
38 t.Fatalf("cookie does not default to Secure & HttpOnly: got %v", cookie)
39 }
40 }
41
42 // TestCookieOptions is a test to make sure the middleware correctly sets cookie options
43 func TestCookieOptions(t *testing.T) {
44 s := http.NewServeMux()
45 s.HandleFunc("/", testHandler)
46
47 r := createRequest("GET", "/", false)
48
49 rr := httptest.NewRecorder()
50 p := Protect(testKey, CookieName("nameoverride"), Secure(false), HttpOnly(false), Path("/pathoverride"), Domain("domainoverride"), MaxAge(173))(s)
51 p.ServeHTTP(rr, r)
52
53 if rr.Header().Get("Set-Cookie") == "" {
54 t.Fatalf("cookie not set: got %q", rr.Header().Get("Set-Cookie"))
55 }
56
57 cookie := rr.Header().Get("Set-Cookie")
58 if strings.Contains(cookie, "HttpOnly") {
59 t.Fatalf("cookie does not respect HttpOnly option: got %v do not want HttpOnly", cookie)
60 }
61 if strings.Contains(cookie, "Secure") {
62 t.Fatalf("cookie does not respect Secure option: got %v do not want Secure", cookie)
63 }
64 if !strings.Contains(cookie, "nameoverride=") {
65 t.Fatalf("cookie does not respect CookieName option: got %v want %v", cookie, "nameoverride=")
66 }
67 if !strings.Contains(cookie, "Domain=domainoverride") {
68 t.Fatalf("cookie does not respect Domain option: got %v want %v", cookie, "Domain=domainoverride")
69 }
70 if !strings.Contains(cookie, "Max-Age=173") {
71 t.Fatalf("cookie does not respect MaxAge option: got %v want %v", cookie, "Max-Age=173")
72 }
73 }
74
75 // Test that idempotent methods return a 200 OK status and that non-idempotent
76 // methods return a 403 Forbidden status when a CSRF cookie is not present.
77 func TestMethods(t *testing.T) {
78 s := http.NewServeMux()
79 s.HandleFunc("/", testHandler)
80 p := Protect(testKey)(s)
81
82 // Test idempontent ("safe") methods
83 for _, method := range safeMethods {
84 r := createRequest(method, "/", false)
85
86 rr := httptest.NewRecorder()
87 p.ServeHTTP(rr, r)
88
89 if rr.Code != http.StatusOK {
90 t.Fatalf("middleware failed to pass to the next handler: got %v want %v",
91 rr.Code, http.StatusOK)
92 }
93
94 if rr.Header().Get("Set-Cookie") == "" {
95 t.Fatalf("cookie not set: got %q", rr.Header().Get("Set-Cookie"))
96 }
97 }
98
99 // Test non-idempotent methods (should return a 403 without a cookie set)
100 nonIdempotent := []string{"POST", "PUT", "DELETE", "PATCH"}
101 for _, method := range nonIdempotent {
102 r := createRequest(method, "/", false)
103
104 rr := httptest.NewRecorder()
105 p.ServeHTTP(rr, r)
106
107 if rr.Code != http.StatusForbidden {
108 t.Fatalf("middleware failed to pass to the next handler: got %v want %v",
109 rr.Code, http.StatusOK)
110 }
111
112 if rr.Header().Get("Set-Cookie") == "" {
113 t.Fatalf("cookie not set: got %q", rr.Header().Get("Set-Cookie"))
114 }
115 }
116 }
117
118 // Tests for failure if the cookie containing the session does not exist on a
119 // POST request.
120 func TestNoCookie(t *testing.T) {
121 s := http.NewServeMux()
122 p := Protect(testKey)(s)
123
124 // POST the token back in the header.
125 r := createRequest("POST", "/", false)
126
127 rr := httptest.NewRecorder()
128 p.ServeHTTP(rr, r)
129
130 if rr.Code != http.StatusForbidden {
131 t.Fatalf("middleware failed to reject a non-existent cookie: got %v want %v",
132 rr.Code, http.StatusForbidden)
133 }
134 }
135
136 // TestBadCookie tests for failure when a cookie header is modified (malformed).
137 func TestBadCookie(t *testing.T) {
138 s := http.NewServeMux()
139 p := Protect(testKey)(s)
140
141 var token string
142 s.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
143 token = Token(r)
144 }))
145
146 // Obtain a CSRF cookie via a GET request.
147 r := createRequest("GET", "/", false)
148
149 rr := httptest.NewRecorder()
150 p.ServeHTTP(rr, r)
151
152 // POST the token back in the header.
153 r = createRequest("POST", "/", false)
154
155 // Replace the cookie prefix
156 badHeader := strings.Replace(cookieName+"=", rr.Header().Get("Set-Cookie"), "_badCookie", -1)
157 r.Header.Set("Cookie", badHeader)
158 r.Header.Set("X-CSRF-Token", token)
159 r.Header.Set("Referer", "http://www.gorillatoolkit.org/")
160
161 rr = httptest.NewRecorder()
162 p.ServeHTTP(rr, r)
163
164 if rr.Code != http.StatusForbidden {
165 t.Fatalf("middleware failed to reject a bad cookie: got %v want %v",
166 rr.Code, http.StatusForbidden)
167 }
168 }
169
170 // Responses should set a "Vary: Cookie" header to protect client/proxy caching.
171 func TestVaryHeader(t *testing.T) {
172 s := http.NewServeMux()
173 s.HandleFunc("/", testHandler)
174 p := Protect(testKey)(s)
175
176 r := createRequest("GET", "/", true)
177
178 rr := httptest.NewRecorder()
179 p.ServeHTTP(rr, r)
180
181 if rr.Code != http.StatusOK {
182 t.Fatalf("middleware failed to pass to the next handler: got %v want %v",
183 rr.Code, http.StatusOK)
184 }
185
186 if rr.Header().Get("Vary") != "Cookie" {
187 t.Fatalf("vary header not set: got %q want %q", rr.Header().Get("Vary"), "Cookie")
188 }
189 }
190
191 // TestNoReferer checks that HTTPS requests with no Referer header fail.
192 func TestNoReferer(t *testing.T) {
193 s := http.NewServeMux()
194 s.HandleFunc("/", testHandler)
195 p := Protect(testKey)(s)
196
197 r := createRequest("POST", "https://golang.org/", true)
198
199 rr := httptest.NewRecorder()
200 p.ServeHTTP(rr, r)
201
202 if rr.Code != http.StatusForbidden {
203 t.Fatalf("middleware failed reject an empty Referer header: got %v want %v",
204 rr.Code, http.StatusForbidden)
205 }
206 }
207
208 // TestBadReferer checks that HTTPS requests with a Referer that does not
209 // match the request URL correctly fail CSRF validation.
210 func TestBadReferer(t *testing.T) {
211 s := http.NewServeMux()
212 p := Protect(testKey)(s)
213
214 var token string
215 s.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
216 token = Token(r)
217 }))
218
219 // Obtain a CSRF cookie via a GET request.
220 r := createRequest("GET", "/", true)
221 rr := httptest.NewRecorder()
222 p.ServeHTTP(rr, r)
223
224 // POST the token back in the header.
225 r = createRequest("POST", "/", true)
226 setCookie(rr, r)
227 r.Header.Set("X-CSRF-Token", token)
228
229 // Set a non-matching Referer header.
230 r.Header.Set("Referer", "http://golang.org/")
231
232 rr = httptest.NewRecorder()
233 p.ServeHTTP(rr, r)
234
235 if rr.Code != http.StatusForbidden {
236 t.Fatalf("middleware failed reject a non-matching Referer header: got %v want %v",
237 rr.Code, http.StatusForbidden)
238 }
239 }
240
241 // TestTrustedReferer checks that HTTPS requests with a Referer that does not
242 // match the request URL correctly but is a trusted origin pass CSRF validation.
243 func TestTrustedReferer(t *testing.T) {
244
245 testTable := []struct {
246 trustedOrigin []string
247 shouldPass bool
248 }{
249 {[]string{"golang.org"}, true},
250 {[]string{"api.example.com", "golang.org"}, true},
251 {[]string{"http://golang.org"}, false},
252 {[]string{"https://golang.org"}, false},
253 {[]string{"http://example.com"}, false},
254 {[]string{"example.com"}, false},
255 }
256
257 for _, item := range testTable {
258 t.Run(fmt.Sprintf("TrustedOrigin: %v", item.trustedOrigin), func(t *testing.T) {
259
260 s := http.NewServeMux()
261
262 p := Protect(testKey, TrustedOrigins(item.trustedOrigin))(s)
263
264 var token string
265 s.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
266 token = Token(r)
267 }))
268
269 // Obtain a CSRF cookie via a GET request.
270 r := createRequest("GET", "/", true)
271
272 rr := httptest.NewRecorder()
273 p.ServeHTTP(rr, r)
274
275 // POST the token back in the header.
276 r = createRequest("POST", "/", true)
277
278 setCookie(rr, r)
279 r.Header.Set("X-CSRF-Token", token)
280
281 // Set a non-matching Referer header.
282 r.Header.Set("Referer", "https://golang.org/")
283
284 rr = httptest.NewRecorder()
285 p.ServeHTTP(rr, r)
286
287 if item.shouldPass {
288 if rr.Code != http.StatusOK {
289 t.Fatalf("middleware failed to pass to the next handler: got %v want %v",
290 rr.Code, http.StatusOK)
291 }
292 } else {
293 if rr.Code != http.StatusForbidden {
294 t.Fatalf("middleware failed reject a non-matching Referer header: got %v want %v",
295 rr.Code, http.StatusForbidden)
296 }
297 }
298 })
299 }
300 }
301
302 // Requests with a valid Referer should pass.
303 func TestWithReferer(t *testing.T) {
304 s := http.NewServeMux()
305 p := Protect(testKey)(s)
306
307 var token string
308 s.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
309 token = Token(r)
310 }))
311
312 // Obtain a CSRF cookie via a GET request.
313 r := createRequest("GET", "/", true)
314 rr := httptest.NewRecorder()
315 p.ServeHTTP(rr, r)
316
317 // POST the token back in the header.
318 r = createRequest("POST", "/", true)
319
320 setCookie(rr, r)
321 r.Header.Set("X-CSRF-Token", token)
322 r.Header.Set("Referer", "https://www.gorillatoolkit.org/")
323
324 rr = httptest.NewRecorder()
325 p.ServeHTTP(rr, r)
326
327 if rr.Code != http.StatusOK {
328 t.Fatalf("middleware failed to pass to the next handler: got %v want %v",
329 rr.Code, http.StatusOK)
330 }
331 }
332
333 // Requests without a token should fail with ErrNoToken.
334 func TestNoTokenProvided(t *testing.T) {
335 var finalErr error
336
337 s := http.NewServeMux()
338 p := Protect(testKey, ErrorHandler(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
339 finalErr = FailureReason(r)
340 })))(s)
341
342 var token string
343 s.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
344 token = Token(r)
345 }))
346 // Obtain a CSRF cookie via a GET request.
347 r := createRequest("GET", "/", true)
348
349 rr := httptest.NewRecorder()
350 p.ServeHTTP(rr, r)
351
352 // POST the token back in the header.
353 r = createRequest("POST", "/", true)
354
355 setCookie(rr, r)
356 // By accident we use the wrong header name for the token...
357 r.Header.Set("X-CSRF-nekot", token)
358 r.Header.Set("Referer", "https://www.gorillatoolkit.org/")
359
360 rr = httptest.NewRecorder()
361 p.ServeHTTP(rr, r)
362
363 if finalErr != nil && finalErr != ErrNoToken {
364 t.Fatalf("middleware failed to return correct error: got '%v' want '%v'", finalErr, ErrNoToken)
365 }
366 }
367
368 func setCookie(rr *httptest.ResponseRecorder, r *http.Request) {
369 r.Header.Set("Cookie", rr.Header().Get("Set-Cookie"))
370 }
371
372 func TestProtectScenarios(t *testing.T) {
373 tests := []struct {
374 name string
375 safeMethod bool
376 originUntrusted bool
377 originHTTP bool
378 originTrusted bool
379 secureRequest bool
380 refererTrusted bool
381 refererUntrusted bool
382 refererHTTPDowngrade bool
383 refererRelative bool
384 tokenValid bool
385 tokenInvalid bool
386 want bool
387 }{
388 {
389 name: "safe method pass",
390 safeMethod: true,
391 want: true,
392 },
393 {
394 name: "cleartext POST with trusted origin & valid token pass",
395 originHTTP: true,
396 tokenValid: true,
397 want: true,
398 },
399 {
400 name: "cleartext POST with untrusted origin reject",
401 originUntrusted: true,
402 tokenValid: true,
403 },
404 {
405 name: "cleartext POST with HTTP origin & invalid token reject",
406 originHTTP: true,
407 },
408 {
409 name: "cleartext POST without origin with valid token pass",
410 tokenValid: true,
411 want: true,
412 },
413 {
414 name: "cleartext POST without origin with invalid token reject",
415 },
416 {
417 name: "TLS POST with HTTP origin & no referer & valid token reject",
418 tokenValid: true,
419 secureRequest: true,
420 originHTTP: true,
421 },
422 {
423 name: "TLS POST without origin and without referer reject",
424 secureRequest: true,
425 tokenValid: true,
426 },
427 {
428 name: "TLS POST without origin with untrusted referer reject",
429 secureRequest: true,
430 refererUntrusted: true,
431 tokenValid: true,
432 },
433 {
434 name: "TLS POST without origin with trusted referer & valid token pass",
435 secureRequest: true,
436 refererTrusted: true,
437 tokenValid: true,
438 want: true,
439 },
440 {
441 name: "TLS POST without origin from _cleartext_ same domain referer with valid token reject",
442 secureRequest: true,
443 refererHTTPDowngrade: true,
444 tokenValid: true,
445 },
446 {
447 name: "TLS POST without origin from relative referer with valid token pass",
448 secureRequest: true,
449 refererRelative: true,
450 tokenValid: true,
451 want: true,
452 },
453 {
454 name: "TLS POST without origin from relative referer with invalid token reject",
455 secureRequest: true,
456 refererRelative: true,
457 tokenInvalid: true,
458 },
459 }
460
461 for _, tt := range tests {
462 t.Run(tt.name, func(t *testing.T) {
463 var token string
464 var flag bool
465 mux := http.NewServeMux()
466 mux.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
467 token = Token(r)
468 }))
469 mux.Handle("/submit", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
470 flag = true
471 }))
472 p := Protect(testKey)(mux)
473
474 // Obtain a CSRF cookie via a GET request.
475 r := createRequest("GET", "/", tt.secureRequest)
476 rr := httptest.NewRecorder()
477 p.ServeHTTP(rr, r)
478
479 r = createRequest("POST", "/submit", tt.secureRequest)
480 if tt.safeMethod {
481 r = createRequest("GET", "/submit", tt.secureRequest)
482 }
483
484 // Set the Origin header
485 switch {
486 case tt.originUntrusted:
487 r.Header.Set("Origin", "http://www.untrusted-origin.org")
488 case tt.originTrusted:
489 r.Header.Set("Origin", "https://www.gorillatoolkit.org")
490 case tt.originHTTP:
491 r.Header.Set("Origin", "http://www.gorillatoolkit.org")
492 }
493
494 // Set the Referer header
495 switch {
496 case tt.refererTrusted:
497 p = Protect(testKey, TrustedOrigins([]string{"external-trusted-origin.test"}))(mux)
498 r.Header.Set("Referer", "https://external-trusted-origin.test/foobar")
499 case tt.refererUntrusted:
500 r.Header.Set("Referer", "http://www.invalid-referer.org")
501 case tt.refererHTTPDowngrade:
502 r.Header.Set("Referer", "http://www.gorillatoolkit.org/foobar")
503 case tt.refererRelative:
504 r.Header.Set("Referer", "/foobar")
505 }
506
507 // Set the CSRF token & associated cookie
508 switch {
509 case tt.tokenInvalid:
510 setCookie(rr, r)
511 r.Header.Set("X-CSRF-Token", "this-is-an-invalid-token")
512 case tt.tokenValid:
513 setCookie(rr, r)
514 r.Header.Set("X-CSRF-Token", token)
515 }
516
517 rr = httptest.NewRecorder()
518 p.ServeHTTP(rr, r)
519
520 if tt.want && rr.Code != http.StatusOK {
521 t.Fatalf("middleware failed to pass to the next handler: got %v want %v",
522 rr.Code, http.StatusOK)
523 }
524
525 if tt.want && !flag {
526 t.Fatalf("middleware failed to pass to the next handler: got %v want %v",
527 flag, true)
528
529 }
530 if !tt.want && flag {
531 t.Fatalf("middleware failed to reject the request: got %v want %v", flag, false)
532 }
533 })
534 }
535 }
536
537 func createRequest(method, path string, useTLS bool) *http.Request {
538 r := httptest.NewRequest(method, path, nil)
539 r.Host = "www.gorillatoolkit.org"
540 if !useTLS {
541 return PlaintextHTTPRequest(r)
542 }
543 return r
544 }