File: CVE-2025-24358.patch

package info (click to toggle)
golang-github-gorilla-csrf 1.7.2%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 332 kB
  • sloc: javascript: 38; makefile: 30
file content (713 lines) | stat: -rw-r--r-- 21,828 bytes parent folder | download
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
From: Patrick O'Doherty <hello@patrickod.com>
Date: Thu, 23 Jan 2025 12:14:50 -0800
Subject: Merge commit from fork

* csrf: use context to determine TLS state

r.URL.Scheme is never populated for "server" requests, and so the
referer check never runs.

Instead we now ask the caller application to signal this explicitly via
request conext, and then enforce the check accordingly.

Separately, browsers do not always send the full URL as a Referer,
especially in the same-origin context meaning we cannot compare its host
against our trusted origin list. If the referer does not contain a host
we populate r.URL.Host with r.Host which is expected to be sent by all
clients as the first header of their request.

Add tests against the Origin header before attempting to enforce
same-origin restrictions using the Referer header.

Matching the Django CSRF behavior: if the Origin is present in either
the cleartext or TLS case we will evaluate it.

IFF we are in TLS and we have no Origin we will evaluate the Referer
against the allowlist. In doing so we take care to permit "path only"
Referers that are sent in same-origin context.

* add csrf.TLSRequest helper API to set request TLS context

Add a csrf.TLSRequest public API method that sets the appropriate TLS
context key and signals to the midldeware the need to run the
additiontal Referer checks.

* Enable Referer-based origin checks by default

Reverse the default position and presume that that the server is using
TLS either directly or via an upstream proxy and require the user to
explicitly disable referer-based checks.

This safe default means that users that upgrade the library without
making any other code changes will benefit from the Referer checks that
they thought were active already. Without this change we risk that some
codebases will mistakenly remain vulnerable even while using a patched
version of the library.

Origin: upstream, https://github.com/gorilla/csrf/commit/9dd6af1f6d30fc79fb0d972394deebdabad6b5eb

diff --git a/csrf.go b/csrf.go
index 97a3925..5dda254 100644
--- a/csrf.go
+++ b/csrf.go
@@ -1,10 +1,12 @@
 package csrf

 import (
+	"context"
 	"errors"
 	"fmt"
 	"net/http"
 	"net/url"
+	"slices"

 	"github.com/gorilla/securecookie"
 )
@@ -22,6 +24,14 @@ const (
 	errorPrefix  string = "gorilla/csrf: "
 )

+type contextKey string
+
+// PlaintextHTTPContextKey is the context key used to store whether the request
+// is being served via plaintext HTTP. This is used to signal to the middleware
+// that strict Referer checking should not be enforced as is done for HTTPS by
+// default.
+const PlaintextHTTPContextKey contextKey = "plaintext"
+
 var (
 	// The name value used in form fields.
 	fieldName = tokenKey
@@ -41,6 +51,9 @@ var (
 	// ErrNoReferer is returned when a HTTPS request provides an empty Referer
 	// header.
 	ErrNoReferer = errors.New("referer not supplied")
+	// ErrBadOrigin is returned when the Origin header is present and is not a
+	// trusted origin.
+	ErrBadOrigin = errors.New("origin invalid")
 	// ErrBadReferer is returned when the scheme & host in the URL do not match
 	// the supplied Referer header.
 	ErrBadReferer = errors.New("referer invalid")
@@ -242,10 +255,50 @@ func (cs *csrf) ServeHTTP(w http.ResponseWriter, r *http.Request) {
 	// HTTP methods not defined as idempotent ("safe") under RFC7231 require
 	// inspection.
 	if !contains(safeMethods, r.Method) {
-		// Enforce an origin check for HTTPS connections. As per the Django CSRF
-		// implementation (https://goo.gl/vKA7GE) the Referer header is almost
-		// always present for same-domain HTTP requests.
-		if r.URL.Scheme == "https" {
+		var isPlaintext bool
+		val := r.Context().Value(PlaintextHTTPContextKey)
+		if val != nil {
+			isPlaintext, _ = val.(bool)
+		}
+
+		// take a copy of the request URL to avoid mutating the original
+		// attached to the request.
+		// set the scheme & host based on the request context as these are not
+		// populated by default for server requests
+		// ref: https://pkg.go.dev/net/http#Request
+		requestURL := *r.URL // shallow clone
+
+		requestURL.Scheme = "https"
+		if isPlaintext {
+			requestURL.Scheme = "http"
+		}
+		if requestURL.Host == "" {
+			requestURL.Host = r.Host
+		}
+
+		// if we have an Origin header, check it against our allowlist
+		origin := r.Header.Get("Origin")
+		if origin != "" {
+			parsedOrigin, err := url.Parse(origin)
+			if err != nil {
+				r = envError(r, ErrBadOrigin)
+				cs.opts.ErrorHandler.ServeHTTP(w, r)
+				return
+			}
+			if !sameOrigin(&requestURL, parsedOrigin) && !slices.Contains(cs.opts.TrustedOrigins, parsedOrigin.Host) {
+				r = envError(r, ErrBadOrigin)
+				cs.opts.ErrorHandler.ServeHTTP(w, r)
+				return
+			}
+		}
+
+		// If we are serving via TLS and have no Origin header, prevent against
+		// CSRF via HTTP machine in the middle attacks by enforcing strict
+		// Referer origin checks. Consider an attacker who performs a
+		// successful HTTP Machine-in-the-Middle attack and uses this to inject
+		// a form and cause submission to our origin. We strictly disallow
+		// cleartext HTTP origins and evaluate the domain against an allowlist.
+		if origin == "" && !isPlaintext {
 			// Fetch the Referer value. Call the error handler if it's empty or
 			// otherwise fails to parse.
 			referer, err := url.Parse(r.Referer())
@@ -255,18 +308,17 @@ func (cs *csrf) ServeHTTP(w http.ResponseWriter, r *http.Request) {
 				return
 			}

-			valid := sameOrigin(r.URL, referer)
-
-			if !valid {
-				for _, trustedOrigin := range cs.opts.TrustedOrigins {
-					if referer.Host == trustedOrigin {
-						valid = true
-						break
-					}
-				}
+			// disallow cleartext HTTP referers when serving via TLS
+			if referer.Scheme == "http" {
+				r = envError(r, ErrBadReferer)
+				cs.opts.ErrorHandler.ServeHTTP(w, r)
+				return
 			}

-			if !valid {
+			// If the request is being served via TLS and the Referer is not the
+			// same origin, check the domain against our allowlist. We only
+			// check when we have host information from the referer.
+			if referer.Host != "" && referer.Host != r.Host && !slices.Contains(cs.opts.TrustedOrigins, referer.Host) {
 				r = envError(r, ErrBadReferer)
 				cs.opts.ErrorHandler.ServeHTTP(w, r)
 				return
@@ -308,6 +360,15 @@ func (cs *csrf) ServeHTTP(w http.ResponseWriter, r *http.Request) {
 	contextClear(r)
 }

+// PlaintextHTTPRequest accepts as input a http.Request and returns a new
+// http.Request with the PlaintextHTTPContextKey set to true. This is used to
+// signal to the CSRF middleware that the request is being served over plaintext
+// HTTP and that Referer-based origin allow-listing checks should be skipped.
+func PlaintextHTTPRequest(r *http.Request) *http.Request {
+	ctx := context.WithValue(r.Context(), PlaintextHTTPContextKey, true)
+	return r.WithContext(ctx)
+}
+
 // unauthorizedhandler sets a HTTP 403 Forbidden status and writes the
 // CSRF failure reason to the response.
 func unauthorizedHandler(w http.ResponseWriter, r *http.Request) {
diff --git a/csrf_test.go b/csrf_test.go
index 0559a59..0281680 100644
--- a/csrf_test.go
+++ b/csrf_test.go
@@ -1,6 +1,7 @@
 package csrf

 import (
+	"fmt"
 	"net/http"
 	"net/http/httptest"
 	"strings"
@@ -16,10 +17,7 @@ func TestProtect(t *testing.T) {
 	s := http.NewServeMux()
 	s.HandleFunc("/", testHandler)

-	r, err := http.NewRequest("GET", "/", nil)
-	if err != nil {
-		t.Fatal(err)
-	}
+	r := createRequest("GET", "/", false)

 	rr := httptest.NewRecorder()
 	p := Protect(testKey)(s)
@@ -46,10 +44,7 @@ func TestCookieOptions(t *testing.T) {
 	s := http.NewServeMux()
 	s.HandleFunc("/", testHandler)

-	r, err := http.NewRequest("GET", "/", nil)
-	if err != nil {
-		t.Fatal(err)
-	}
+	r := createRequest("GET", "/", false)

 	rr := httptest.NewRecorder()
 	p := Protect(testKey, CookieName("nameoverride"), Secure(false), HttpOnly(false), Path("/pathoverride"), Domain("domainoverride"), MaxAge(173))(s)
@@ -86,10 +81,7 @@ func TestMethods(t *testing.T) {

 	// Test idempontent ("safe") methods
 	for _, method := range safeMethods {
-		r, err := http.NewRequest(method, "/", nil)
-		if err != nil {
-			t.Fatal(err)
-		}
+		r := createRequest(method, "/", false)

 		rr := httptest.NewRecorder()
 		p.ServeHTTP(rr, r)
@@ -107,10 +99,7 @@ func TestMethods(t *testing.T) {
 	// Test non-idempotent methods (should return a 403 without a cookie set)
 	nonIdempotent := []string{"POST", "PUT", "DELETE", "PATCH"}
 	for _, method := range nonIdempotent {
-		r, err := http.NewRequest(method, "/", nil)
-		if err != nil {
-			t.Fatal(err)
-		}
+		r := createRequest(method, "/", false)

 		rr := httptest.NewRecorder()
 		p.ServeHTTP(rr, r)
@@ -133,10 +122,7 @@ func TestNoCookie(t *testing.T) {
 	p := Protect(testKey)(s)

 	// POST the token back in the header.
-	r, err := http.NewRequest("POST", "http://www.gorillatoolkit.org/", nil)
-	if err != nil {
-		t.Fatal(err)
-	}
+	r := createRequest("POST", "/", false)

 	rr := httptest.NewRecorder()
 	p.ServeHTTP(rr, r)
@@ -158,19 +144,13 @@ func TestBadCookie(t *testing.T) {
 	}))

 	// Obtain a CSRF cookie via a GET request.
-	r, err := http.NewRequest("GET", "http://www.gorillatoolkit.org/", nil)
-	if err != nil {
-		t.Fatal(err)
-	}
+	r := createRequest("GET", "/", false)

 	rr := httptest.NewRecorder()
 	p.ServeHTTP(rr, r)

 	// POST the token back in the header.
-	r, err = http.NewRequest("POST", "http://www.gorillatoolkit.org/", nil)
-	if err != nil {
-		t.Fatal(err)
-	}
+	r = createRequest("POST", "/", false)

 	// Replace the cookie prefix
 	badHeader := strings.Replace(cookieName+"=", rr.Header().Get("Set-Cookie"), "_badCookie", -1)
@@ -193,10 +173,7 @@ func TestVaryHeader(t *testing.T) {
 	s.HandleFunc("/", testHandler)
 	p := Protect(testKey)(s)

-	r, err := http.NewRequest("HEAD", "https://www.golang.org/", nil)
-	if err != nil {
-		t.Fatal(err)
-	}
+	r := createRequest("GET", "/", true)

 	rr := httptest.NewRecorder()
 	p.ServeHTTP(rr, r)
@@ -211,16 +188,13 @@ func TestVaryHeader(t *testing.T) {
 	}
 }

-// Requests with no Referer header should fail.
+// TestNoReferer checks that HTTPS requests with no Referer header fail.
 func TestNoReferer(t *testing.T) {
 	s := http.NewServeMux()
 	s.HandleFunc("/", testHandler)
 	p := Protect(testKey)(s)

-	r, err := http.NewRequest("POST", "https://golang.org/", nil)
-	if err != nil {
-		t.Fatal(err)
-	}
+	r := createRequest("POST", "https://golang.org/", true)

 	rr := httptest.NewRecorder()
 	p.ServeHTTP(rr, r)
@@ -243,20 +217,12 @@ func TestBadReferer(t *testing.T) {
 	}))

 	// Obtain a CSRF cookie via a GET request.
-	r, err := http.NewRequest("GET", "https://www.gorillatoolkit.org/", nil)
-	if err != nil {
-		t.Fatal(err)
-	}
-
+	r := createRequest("GET", "/", true)
 	rr := httptest.NewRecorder()
 	p.ServeHTTP(rr, r)

 	// POST the token back in the header.
-	r, err = http.NewRequest("POST", "https://www.gorillatoolkit.org/", nil)
-	if err != nil {
-		t.Fatal(err)
-	}
-
+	r = createRequest("POST", "/", true)
 	setCookie(rr, r)
 	r.Header.Set("X-CSRF-Token", token)

@@ -289,50 +255,47 @@ func TestTrustedReferer(t *testing.T) {
 	}

 	for _, item := range testTable {
-		s := http.NewServeMux()
+		t.Run(fmt.Sprintf("TrustedOrigin: %v", item.trustedOrigin), func(t *testing.T) {

-		p := Protect(testKey, TrustedOrigins(item.trustedOrigin))(s)
+			s := http.NewServeMux()

-		var token string
-		s.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
-			token = Token(r)
-		}))
+			p := Protect(testKey, TrustedOrigins(item.trustedOrigin))(s)

-		// Obtain a CSRF cookie via a GET request.
-		r, err := http.NewRequest("GET", "https://www.gorillatoolkit.org/", nil)
-		if err != nil {
-			t.Fatal(err)
-		}
+			var token string
+			s.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
+				token = Token(r)
+			}))

-		rr := httptest.NewRecorder()
-		p.ServeHTTP(rr, r)
+			// Obtain a CSRF cookie via a GET request.
+			r := createRequest("GET", "/", true)

-		// POST the token back in the header.
-		r, err = http.NewRequest("POST", "https://www.gorillatoolkit.org/", nil)
-		if err != nil {
-			t.Fatal(err)
-		}
+			rr := httptest.NewRecorder()
+			p.ServeHTTP(rr, r)

-		setCookie(rr, r)
-		r.Header.Set("X-CSRF-Token", token)
+			// POST the token back in the header.
+			r = createRequest("POST", "/", true)

-		// Set a non-matching Referer header.
-		r.Header.Set("Referer", "http://golang.org/")
+			setCookie(rr, r)
+			r.Header.Set("X-CSRF-Token", token)

-		rr = httptest.NewRecorder()
-		p.ServeHTTP(rr, r)
+			// Set a non-matching Referer header.
+			r.Header.Set("Referer", "https://golang.org/")

-		if item.shouldPass {
-			if rr.Code != http.StatusOK {
-				t.Fatalf("middleware failed to pass to the next handler: got %v want %v",
-					rr.Code, http.StatusOK)
-			}
-		} else {
-			if rr.Code != http.StatusForbidden {
-				t.Fatalf("middleware failed reject a non-matching Referer header: got %v want %v",
-					rr.Code, http.StatusForbidden)
+			rr = httptest.NewRecorder()
+			p.ServeHTTP(rr, r)
+
+			if item.shouldPass {
+				if rr.Code != http.StatusOK {
+					t.Fatalf("middleware failed to pass to the next handler: got %v want %v",
+						rr.Code, http.StatusOK)
+				}
+			} else {
+				if rr.Code != http.StatusForbidden {
+					t.Fatalf("middleware failed reject a non-matching Referer header: got %v want %v",
+						rr.Code, http.StatusForbidden)
+				}
 			}
-		}
+		})
 	}
 }

@@ -347,23 +310,16 @@ func TestWithReferer(t *testing.T) {
 	}))

 	// Obtain a CSRF cookie via a GET request.
-	r, err := http.NewRequest("GET", "http://www.gorillatoolkit.org/", nil)
-	if err != nil {
-		t.Fatal(err)
-	}
-
+	r := createRequest("GET", "/", true)
 	rr := httptest.NewRecorder()
 	p.ServeHTTP(rr, r)

 	// POST the token back in the header.
-	r, err = http.NewRequest("POST", "http://www.gorillatoolkit.org/", nil)
-	if err != nil {
-		t.Fatal(err)
-	}
+	r = createRequest("POST", "/", true)

 	setCookie(rr, r)
 	r.Header.Set("X-CSRF-Token", token)
-	r.Header.Set("Referer", "http://www.gorillatoolkit.org/")
+	r.Header.Set("Referer", "https://www.gorillatoolkit.org/")

 	rr = httptest.NewRecorder()
 	p.ServeHTTP(rr, r)
@@ -387,26 +343,19 @@ func TestNoTokenProvided(t *testing.T) {
 	s.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
 		token = Token(r)
 	}))
-
 	// Obtain a CSRF cookie via a GET request.
-	r, err := http.NewRequest("GET", "http://www.gorillatoolkit.org/", nil)
-	if err != nil {
-		t.Fatal(err)
-	}
+	r := createRequest("GET", "/", true)

 	rr := httptest.NewRecorder()
 	p.ServeHTTP(rr, r)

 	// POST the token back in the header.
-	r, err = http.NewRequest("POST", "http://www.gorillatoolkit.org/", nil)
-	if err != nil {
-		t.Fatal(err)
-	}
+	r = createRequest("POST", "/", true)

 	setCookie(rr, r)
 	// By accident we use the wrong header name for the token...
 	r.Header.Set("X-CSRF-nekot", token)
-	r.Header.Set("Referer", "http://www.gorillatoolkit.org/")
+	r.Header.Set("Referer", "https://www.gorillatoolkit.org/")

 	rr = httptest.NewRecorder()
 	p.ServeHTTP(rr, r)
@@ -419,3 +368,177 @@ func TestNoTokenProvided(t *testing.T) {
 func setCookie(rr *httptest.ResponseRecorder, r *http.Request) {
 	r.Header.Set("Cookie", rr.Header().Get("Set-Cookie"))
 }
+
+func TestProtectScenarios(t *testing.T) {
+	tests := []struct {
+		name                 string
+		safeMethod           bool
+		originUntrusted      bool
+		originHTTP           bool
+		originTrusted        bool
+		secureRequest        bool
+		refererTrusted       bool
+		refererUntrusted     bool
+		refererHTTPDowngrade bool
+		refererRelative      bool
+		tokenValid           bool
+		tokenInvalid         bool
+		want                 bool
+	}{
+		{
+			name:       "safe method pass",
+			safeMethod: true,
+			want:       true,
+		},
+		{
+			name:       "cleartext POST with trusted origin & valid token pass",
+			originHTTP: true,
+			tokenValid: true,
+			want:       true,
+		},
+		{
+			name:            "cleartext POST with untrusted origin reject",
+			originUntrusted: true,
+			tokenValid:      true,
+		},
+		{
+			name:       "cleartext POST with HTTP origin & invalid token reject",
+			originHTTP: true,
+		},
+		{
+			name:       "cleartext POST without origin with valid token pass",
+			tokenValid: true,
+			want:       true,
+		},
+		{
+			name: "cleartext POST without origin with invalid token reject",
+		},
+		{
+			name:          "TLS POST with HTTP origin & no referer & valid token reject",
+			tokenValid:    true,
+			secureRequest: true,
+			originHTTP:    true,
+		},
+		{
+			name:          "TLS POST without origin and without referer reject",
+			secureRequest: true,
+			tokenValid:    true,
+		},
+		{
+			name:             "TLS POST without origin with untrusted referer reject",
+			secureRequest:    true,
+			refererUntrusted: true,
+			tokenValid:       true,
+		},
+		{
+			name:           "TLS POST without origin with trusted referer & valid token pass",
+			secureRequest:  true,
+			refererTrusted: true,
+			tokenValid:     true,
+			want:           true,
+		},
+		{
+			name:                 "TLS POST without origin from _cleartext_ same domain referer with valid token reject",
+			secureRequest:        true,
+			refererHTTPDowngrade: true,
+			tokenValid:           true,
+		},
+		{
+			name:            "TLS POST without origin from relative referer with valid token pass",
+			secureRequest:   true,
+			refererRelative: true,
+			tokenValid:      true,
+			want:            true,
+		},
+		{
+			name:            "TLS POST without origin from relative referer with invalid token reject",
+			secureRequest:   true,
+			refererRelative: true,
+			tokenInvalid:    true,
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			var token string
+			var flag bool
+			mux := http.NewServeMux()
+			mux.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
+				token = Token(r)
+			}))
+			mux.Handle("/submit", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+				flag = true
+			}))
+			p := Protect(testKey)(mux)
+
+			// Obtain a CSRF cookie via a GET request.
+			r := createRequest("GET", "/", tt.secureRequest)
+			rr := httptest.NewRecorder()
+			p.ServeHTTP(rr, r)
+
+			r = createRequest("POST", "/submit", tt.secureRequest)
+			if tt.safeMethod {
+				r = createRequest("GET", "/submit", tt.secureRequest)
+			}
+
+			// Set the Origin header
+			switch {
+			case tt.originUntrusted:
+				r.Header.Set("Origin", "http://www.untrusted-origin.org")
+			case tt.originTrusted:
+				r.Header.Set("Origin", "https://www.gorillatoolkit.org")
+			case tt.originHTTP:
+				r.Header.Set("Origin", "http://www.gorillatoolkit.org")
+			}
+
+			// Set the Referer header
+			switch {
+			case tt.refererTrusted:
+				p = Protect(testKey, TrustedOrigins([]string{"external-trusted-origin.test"}))(mux)
+				r.Header.Set("Referer", "https://external-trusted-origin.test/foobar")
+			case tt.refererUntrusted:
+				r.Header.Set("Referer", "http://www.invalid-referer.org")
+			case tt.refererHTTPDowngrade:
+				r.Header.Set("Referer", "http://www.gorillatoolkit.org/foobar")
+			case tt.refererRelative:
+				r.Header.Set("Referer", "/foobar")
+			}
+
+			// Set the CSRF token & associated cookie
+			switch {
+			case tt.tokenInvalid:
+				setCookie(rr, r)
+				r.Header.Set("X-CSRF-Token", "this-is-an-invalid-token")
+			case tt.tokenValid:
+				setCookie(rr, r)
+				r.Header.Set("X-CSRF-Token", token)
+			}
+
+			rr = httptest.NewRecorder()
+			p.ServeHTTP(rr, r)
+
+			if tt.want && rr.Code != http.StatusOK {
+				t.Fatalf("middleware failed to pass to the next handler: got %v want %v",
+					rr.Code, http.StatusOK)
+			}
+
+			if tt.want && !flag {
+				t.Fatalf("middleware failed to pass to the next handler: got %v want %v",
+					flag, true)
+
+			}
+			if !tt.want && flag {
+				t.Fatalf("middleware failed to reject the request: got %v want %v", flag, false)
+			}
+		})
+	}
+}
+
+func createRequest(method, path string, useTLS bool) *http.Request {
+	r := httptest.NewRequest(method, path, nil)
+	r.Host = "www.gorillatoolkit.org"
+	if !useTLS {
+		return PlaintextHTTPRequest(r)
+	}
+	return r
+}
diff --git a/helpers_test.go b/helpers_test.go
index 399db8d..f40c996 100644
--- a/helpers_test.go
+++ b/helpers_test.go
@@ -83,10 +83,7 @@ func TestMultipartFormToken(t *testing.T) {
 		}
 	}))

-	r, err := http.NewRequest("GET", "/", nil)
-	if err != nil {
-		t.Fatal(err)
-	}
+	r := createRequest("GET", "/", true)

 	rr := httptest.NewRecorder()
 	p := Protect(testKey)(s)
@@ -107,13 +104,13 @@ func TestMultipartFormToken(t *testing.T) {

 	mp.Close()

-	r, err = http.NewRequest("POST", "http://www.gorillatoolkit.org/", &b)
-	if err != nil {
-		t.Fatal(err)
-	}
+	r = httptest.NewRequest("POST", "/", &b)
+	r.Host = "www.gorillatoolkit.org"

 	// Add the multipart header.
 	r.Header.Set("Content-Type", mp.FormDataContentType())
+	// Add Origin to pass the same-origin check.
+	r.Header.Set("Origin", "https://www.gorillatoolkit.org")

 	// Send back the issued cookie.
 	setCookie(rr, r)
@@ -246,10 +243,8 @@ func TestTemplateField(t *testing.T) {
 	}))

 	testFieldName := "custom_field_name"
-	r, err := http.NewRequest("GET", "/", nil)
-	if err != nil {
-		t.Fatal(err)
-	}
+	r := createRequest("GET", "/", false)
+	// r, err := http.NewRequest("GET", "/", nil)

 	rr := httptest.NewRecorder()
 	p := Protect(testKey, FieldName(testFieldName))(s)
@@ -299,10 +294,7 @@ func TestUnsafeSkipCSRFCheck(t *testing.T) {
 		w.WriteHeader(teapot)
 	}))

-	r, err := http.NewRequest("POST", "/", nil)
-	if err != nil {
-		t.Fatal(err)
-	}
+	r := createRequest("POST", "/", false)

 	// Must be used prior to the CSRF handler being invoked.
 	p := skipCheck(Protect(testKey)(s))