- web.SecurityHeaders middleware wired into the chi router - Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' (page scripts are inline); frame-ancestors 'none' - Referrer-Policy: no-referrer, X-Content-Type-Options: nosniff - Applied only to text/html responses; JSON API and /raw pass through unchanged - Regression test internal/web/securityheaders_test.go
57 lines
2.2 KiB
Go
57 lines
2.2 KiB
Go
package web
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
// #59: SecurityHeaders must add the CSP and hardening headers to rendered
|
|
// HTML responses only; JSON and /raw responses pass through untouched.
|
|
func TestSecurityHeaders(t *testing.T) {
|
|
pages := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
w.Write([]byte("<html><body>ok</body></html>"))
|
|
})
|
|
h := SecurityHeaders(pages)
|
|
rec := httptest.NewRecorder()
|
|
h.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
|
|
wantCSP := "default-src 'self'; script-src 'self' 'unsafe-inline'; frame-ancestors 'none'"
|
|
if got := rec.Header().Get("Content-Security-Policy"); got != wantCSP {
|
|
t.Errorf("CSP = %q, want %q", got, wantCSP)
|
|
}
|
|
if got := rec.Header().Get("Referrer-Policy"); got != "no-referrer" {
|
|
t.Errorf("Referrer-Policy = %q, want no-referrer", got)
|
|
}
|
|
if got := rec.Header().Get("X-Content-Type-Options"); got != "nosniff" {
|
|
t.Errorf("X-Content-Type-Options = %q, want nosniff", got)
|
|
}
|
|
|
|
// JSON response: no security headers.
|
|
jsonh := SecurityHeaders(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.Write([]byte(`{"ok":true}`))
|
|
}))
|
|
rec = httptest.NewRecorder()
|
|
jsonh.ServeHTTP(rec, httptest.NewRequest("GET", "/api/x", nil))
|
|
if got := rec.Header().Get("Content-Security-Policy"); got != "" {
|
|
t.Errorf("unexpected CSP %q on JSON response", got)
|
|
}
|
|
if got := rec.Header().Get("Referrer-Policy"); got != "" {
|
|
t.Errorf("unexpected Referrer-Policy %q on JSON response", got)
|
|
}
|
|
|
|
// Content type set after the first Write (as the inline can page does) is
|
|
// still picked up because headers are inspected post-handler.
|
|
lateh := SecurityHeaders(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Write([]byte("<html></html>"))
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
}))
|
|
rec = httptest.NewRecorder()
|
|
lateh.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
|
|
if got := rec.Header().Get("Content-Security-Policy"); !strings.Contains(got, "frame-ancestors 'none'") {
|
|
t.Errorf("CSP = %q, want frame-ancestors 'none'", got)
|
|
}
|
|
}
|