forked from unrolled/secure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
csp_test.go
65 lines (51 loc) · 1.77 KB
/
csp_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
package secure
import (
"context"
"encoding/base64"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
//nolint:gochecknoglobals
var cspHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(CSPNonce(r.Context())))
})
func TestCSPNonce(t *testing.T) {
csp := "default-src 'self' $NONCE; script-src 'strict-dynamic' $NONCE"
cases := []struct {
options Options
headers []string
}{
{Options{ContentSecurityPolicy: csp}, []string{"Content-Security-Policy"}},
{Options{ContentSecurityPolicyReportOnly: csp}, []string{"Content-Security-Policy-Report-Only"}},
{
Options{ContentSecurityPolicy: csp, ContentSecurityPolicyReportOnly: csp},
[]string{"Content-Security-Policy", "Content-Security-Policy-Report-Only"},
},
}
for _, c := range cases {
s := New(c.options)
res := httptest.NewRecorder()
req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil)
s.Handler(cspHandler).ServeHTTP(res, req)
expect(t, res.Code, http.StatusOK)
for _, header := range c.headers {
csp := res.Header().Get(header)
expect(t, strings.Count(csp, "'nonce-"), 2)
nonce := strings.Split(strings.Split(csp, "'")[3], "-")[1]
// Test that the context has the CSP nonce, but only during the request.
expect(t, res.Body.String(), nonce)
expect(t, CSPNonce(req.Context()), "")
_, err := base64.RawStdEncoding.DecodeString(nonce)
expect(t, err, nil)
expect(t, csp, fmt.Sprintf("default-src 'self' 'nonce-%[1]s'; script-src 'strict-dynamic' 'nonce-%[1]s'", nonce))
}
}
}
func TestWithCSPNonce(t *testing.T) {
req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil)
nonce := "jdgKGHkbnd+/"
expect(t, CSPNonce(withCSPNonce(req, nonce).Context()), nonce)
}