Debian Codegraph @

csp_test.go

raw symbols SCIP
1 package secure
2
3 import (
4 "encoding/base64"
5 "fmt"
6 "net/http"
7 "net/http/httptest"
8 "strings"
9 "testing"
10 )
11
12 // cspHandler writes the nonce out as the response body.
13 var cspHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
14 w.Write([]byte(CSPNonce(r.Context())))
15 })
16
17 func TestCSPNonce(t *testing.T) {
18 csp := "default-src 'self' $NONCE; script-src 'strict-dynamic' $NONCE"
19 cases := []struct {
20 options Options
21 headers []string
22 }{
23 {Options{ContentSecurityPolicy: csp}, []string{"Content-Security-Policy"}},
24 {Options{ContentSecurityPolicyReportOnly: csp}, []string{"Content-Security-Policy-Report-Only"}},
25 {Options{ContentSecurityPolicy: csp, ContentSecurityPolicyReportOnly: csp},
26 []string{"Content-Security-Policy", "Content-Security-Policy-Report-Only"}},
27 }
28
29 for _, c := range cases {
30 s := New(c.options)
31
32 res := httptest.NewRecorder()
33 req, _ := http.NewRequest("GET", "/foo", nil)
34
35 s.Handler(cspHandler).ServeHTTP(res, req)
36
37 expect(t, res.Code, http.StatusOK)
38
39 for _, header := range c.headers {
40 csp := res.Header().Get(header)
41 expect(t, strings.Count(csp, "'nonce-"), 2)
42
43 nonce := strings.Split(strings.Split(csp, "'")[3], "-")[1]
44 // Test that the context has the CSP nonce, but only during the request.
45 expect(t, res.Body.String(), nonce)
46 expect(t, CSPNonce(req.Context()), "")
47
48 _, err := base64.RawStdEncoding.DecodeString(nonce)
49 expect(t, err, nil)
50
51 expect(t, csp, fmt.Sprintf("default-src 'self' 'nonce-%[1]s'; script-src 'strict-dynamic' 'nonce-%[1]s'", nonce))
52 }
53 }
54 }
55
56 func TestWithCSPNonce(t *testing.T) {
57 req, _ := http.NewRequest("GET", "/foo", nil)
58
59 nonce := "jdgKGHkbnd+/"
60
61 expect(t, CSPNonce(withCSPNonce(req, nonce).Context()), nonce)
62 }