policy_test.go
46 lines1
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
package security
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestNew_NoOptions(t *testing.T) {
mw := New()
handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("expected 200, got %d", rec.Code)
}
// No nonce, no headers — should pass through cleanly
if rec.Header().Get("X-Frame-Options") != "" {
t.Error("expected no security headers without WithHeaders")
}
}
func TestNew_ComposesNonceAndHeaders(t *testing.T) {
mw := New(WithNonce(), WithHeaders())
var gotNonce string
handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotNonce = NonceFrom(r.Context())
w.WriteHeader(http.StatusOK)
}))
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/", nil)
handler.ServeHTTP(rec, req)
if gotNonce == "" {
t.Error("expected nonce in context")
}
if rec.Header().Get("X-Frame-Options") != "DENY" {
t.Error("expected security headers")
}
}