Debian Codegraph @

helpers_test.go

raw ◀ ▶
1 Debian patch touch this file
1 package csrf
2
3 import (
4 "bytes"
5 "encoding/base64"
6 "fmt"
7 "log"
8 "mime/multipart"
9 "net/http"
10 "net/http/httptest"
11 "net/url"
12 "strings"
13 "testing"
14 "text/template"
15 )
16
17 var testTemplate = `
18 <html>
19 <body>
20 <form action="/" method="POST">
21 {{ .csrfField }}
22 </form>
23 </body>
24 </html>
25 `
26
27 // Test that our form helpers correctly inject a token into the response body.
28 func TestFormToken(t *testing.T) {
29 s := http.NewServeMux()
30
31 // Make the token available outside of the handler for comparison.
32 var token string
33 s.HandleFunc("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
34 token = Token(r)
35 t := template.Must((template.New("base").Parse(testTemplate)))
36 err := t.Execute(w, map[string]interface{}{
37 TemplateTag: TemplateField(r),
38 })
39 if err != nil {
40 log.Printf("errored during executing the template: %v", err)
41 }
42 }))
43
44 r, err := http.NewRequest("GET", "/", nil)
45 if err != nil {
46 t.Fatal(err)
47 }
48
49 rr := httptest.NewRecorder()
50 p := Protect(testKey)(s)
51 p.ServeHTTP(rr, r)
52
53 if rr.Code != http.StatusOK {
54 t.Fatalf("middleware failed to pass to the next handler: got %v want %v",
55 rr.Code, http.StatusOK)
56 }
57
58 if len(token) != base64.StdEncoding.EncodedLen(tokenLength*2) {
59 t.Fatalf("token length invalid: got %v want %v", len(token), base64.StdEncoding.EncodedLen(tokenLength*2))
60 }
61
62 if !strings.Contains(rr.Body.String(), token) {
63 t.Fatalf("token not in response body: got %v want %v", rr.Body.String(), token)
64 }
65 }
66
67 // Test that we can extract a CSRF token from a multipart form.
68 func TestMultipartFormToken(t *testing.T) {
69 s := http.NewServeMux()
70
71 // Make the token available outside of the handler for comparison.
72 var token string
73 s.HandleFunc("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
74 token = Token(r)
75 t := template.Must((template.New("base").Parse(testTemplate)))
76 err := t.Execute(w, map[string]interface{}{
77 TemplateTag: TemplateField(r),
78 })
79 if err != nil {
80 log.Printf("errored during executing the template: %v", err)
81 }
82 }))
83
84 r := createRequest("GET", "/", true)
85
86 rr := httptest.NewRecorder()
87 p := Protect(testKey)(s)
88 p.ServeHTTP(rr, r)
89
90 // Set up our multipart form
91 var b bytes.Buffer
92 mp := multipart.NewWriter(&b)
93 wr, err := mp.CreateFormField(fieldName)
94 if err != nil {
95 t.Fatal(err)
96 }
97
98 _, err = wr.Write([]byte(token))
99 if err != nil {
100 t.Fatal(err)
101 }
102
103 mp.Close()
104
105 r = httptest.NewRequest("POST", "/", &b)
106 r.Host = "www.gorillatoolkit.org"
107
108 // Add the multipart header.
109 r.Header.Set("Content-Type", mp.FormDataContentType())
110 // Add Origin to pass the same-origin check.
111 r.Header.Set("Origin", "https://www.gorillatoolkit.org")
112
113 // Send back the issued cookie.
114 setCookie(rr, r)
115
116 rr = httptest.NewRecorder()
117 p.ServeHTTP(rr, r)
118
119 if rr.Code != http.StatusOK {
120 t.Fatalf("middleware failed to pass to the next handler: got %v want %v",
121 rr.Code, http.StatusOK)
122 }
123
124 if body := rr.Body.String(); !strings.Contains(body, token) {
125 t.Fatalf("token not in response body: got %v want %v", body, token)
126 }
127 }
128
129 // TestMaskUnmaskTokens tests that a token traversing the mask -> unmask process
130 // is correctly unmasked to the original 'real' token.
131 func TestMaskUnmaskTokens(t *testing.T) {
132 realToken, err := generateRandomBytes(tokenLength)
133 if err != nil {
134 t.Fatal(err)
135 }
136
137 issued := mask(realToken, nil)
138 decoded, err := base64.StdEncoding.DecodeString(issued)
139 if err != nil {
140 t.Fatal(err)
141 }
142
143 unmasked := unmask(decoded)
144 if !compareTokens(unmasked, realToken) {
145 t.Fatalf("tokens do not match: got %x want %x", unmasked, realToken)
146 }
147 }
148
149 // Tests domains that should (or should not) return true for a
150 // same-origin check.
151 func TestSameOrigin(t *testing.T) {
152 var originTests = []struct {
153 o1 string
154 o2 string
155 expected bool
156 }{
157 {"https://gorillatoolkit.org/", "https://gorillatoolkit.org", true},
158 {"http://golang.org/", "http://golang.org/pkg/net/http", true},
159 {"https://gorillatoolkit.org/", "http://gorillatoolkit.org", false},
160 {"https://gorillatoolkit.org:3333/", "http://gorillatoolkit.org:4444", false},
161 }
162
163 for _, origins := range originTests {
164 a, err := url.Parse(origins.o1)
165 if err != nil {
166 t.Fatal(err)
167 }
168
169 b, err := url.Parse(origins.o2)
170 if err != nil {
171 t.Fatal(err)
172 }
173
174 if sameOrigin(a, b) != origins.expected {
175 t.Fatalf("origin checking failed: %v and %v, expected %v",
176 origins.o1, origins.o2, origins.expected)
177 }
178 }
179 }
180
181 func TestXOR(t *testing.T) {
182 testTokens := []struct {
183 a []byte
184 b []byte
185 expected []byte
186 }{
187 {[]byte("goodbye"), []byte("hello"), []byte{15, 10, 3, 8, 13}},
188 {[]byte("gophers"), []byte("clojure"), []byte{4, 3, 31, 2, 16, 0, 22}},
189 {nil, []byte("requestToken"), nil},
190 }
191
192 for _, token := range testTokens {
193 if res := xorToken(token.a, token.b); res != nil {
194 if !bytes.Equal(res, token.expected) {
195 t.Fatalf("xorBytes failed to return the expected result: got %v want %v",
196 res, token.expected)
197 }
198 }
199 }
200 }
201
202 // Since go 1.24 crypto/rand throws a non-recoverable fatal error when it fails
203 // to read random data, so this test needs to be disabled.
204 // See https://go.dev/issue/66821
•205
206 /*
207 // shortReader provides a broken implementation of io.Reader for testing.
208 type shortReader struct{}
209
210 func (sr shortReader) Read(p []byte) (int, error) {
211 return len(p) % 2, io.ErrUnexpectedEOF
212 }
213
214 // TestGenerateRandomBytes tests the (extremely rare) case that crypto/rand does
215 // not return the expected number of bytes.
216 func TestGenerateRandomBytes(t *testing.T) {
217 // Pioneered from https://github.com/justinas/nosurf
218 original := rand.Reader
219 rand.Reader = shortReader{}
220 defer func() {
221 rand.Reader = original
222 }()
223
224 b, err := generateRandomBytes(tokenLength)
225 if err == nil {
226 t.Fatalf("generateRandomBytes did not report a short read: only read %d bytes", len(b))
227 }
228 }
229 */
230
231 func TestTemplateField(t *testing.T) {
•232 s := http.NewServeMux()
233
234 // Make the token & template field available outside of the handler.
235 var token string
236 var templateField string
237 s.HandleFunc("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
238 token = Token(r)
239 templateField = string(TemplateField(r))
240 t := template.Must((template.New("base").Parse(testTemplate)))
241 err := t.Execute(w, map[string]interface{}{
242 TemplateTag: TemplateField(r),
243 })
244 if err != nil {
245 log.Printf("errored during executing the template: %v", err)
246 }
247 }))
248
249 testFieldName := "custom_field_name"
250 r := createRequest("GET", "/", false)
251 // r, err := http.NewRequest("GET", "/", nil)
252
253 rr := httptest.NewRecorder()
254 p := Protect(testKey, FieldName(testFieldName))(s)
255 p.ServeHTTP(rr, r)
256
257 expectedField := fmt.Sprintf(`<input type="hidden" name="%s" value="%s">`,
258 testFieldName, token)
259
260 if rr.Code != http.StatusOK {
261 t.Fatalf("middleware failed to pass to the next handler: got %v want %v",
262 rr.Code, http.StatusOK)
263 }
264
265 if templateField != expectedField {
266 t.Fatalf("custom FieldName was not set correctly: got %v want %v",
267 templateField, expectedField)
268 }
269 }
270
271 func TestCompareTokens(t *testing.T) {
272 // Go's subtle.ConstantTimeCompare prior to 1.3 did not check for matching
273 // lengths.
274 a := []byte("")
275 b := []byte("an-actual-token")
276
277 if v := compareTokens(a, b); v == true {
278 t.Fatalf("compareTokens failed on different tokens: got %v want %v", v, !v)
279 }
280 }
281
282 func TestUnsafeSkipCSRFCheck(t *testing.T) {
283 s := http.NewServeMux()
284 skipCheck := func(h http.Handler) http.Handler {
285 fn := func(w http.ResponseWriter, r *http.Request) {
286 r = UnsafeSkipCheck(r)
287 h.ServeHTTP(w, r)
288 }
289
290 return http.HandlerFunc(fn)
291 }
292
293 var teapot = 418
294
295 // Issue a POST request without a CSRF token in the request.
296 s.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
297 // Set a non-200 header to make the test explicit.
298 w.WriteHeader(teapot)
299 }))
300
301 r := createRequest("POST", "/", false)
302
303 // Must be used prior to the CSRF handler being invoked.
304 p := skipCheck(Protect(testKey)(s))
305 rr := httptest.NewRecorder()
306 p.ServeHTTP(rr, r)
307
308 if status := rr.Code; status != teapot {
309 t.Fatalf("middleware failed to skip this request: got %v want %v",
310 status, teapot)
311 }
312 }