1package middleware
2
3import (
4 "net/http"
5 "net/http/httptest"
6 "testing"
7
8 "github.com/stretchr/testify/assert"
9)
10
11func TestSecurityHeaders(t *testing.T) {
12 handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
13 w.WriteHeader(http.StatusOK)
14 })
15
16 wrapped := SecurityHeaders(handler)
17
18 req := httptest.NewRequest(http.MethodGet, "/", nil)
19 rec := httptest.NewRecorder()
20 wrapped.ServeHTTP(rec, req)
21
22 assert.Equal(t, http.StatusOK, rec.Code)
23
24 // Verify all security headers are set
25 assert.Equal(t, "nosniff", rec.Header().Get("X-Content-Type-Options"))
26 assert.Equal(t, "DENY", rec.Header().Get("X-Frame-Options"))
27 assert.Equal(t, "1; mode=block", rec.Header().Get("X-XSS-Protection"))
28 assert.Equal(t, "strict-origin-when-cross-origin", rec.Header().Get("Referrer-Policy"))
29 assert.Equal(t, "geolocation=(), microphone=(), camera=()", rec.Header().Get("Permissions-Policy"))
30}
31
32func TestSecurityHeaders_PreservesExistingHeaders(t *testing.T) {
33 handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
34 w.Header().Set("Content-Type", "application/json")
35 w.Header().Set("X-Custom-Header", "custom-value")
36 w.WriteHeader(http.StatusOK)
37 })
38
39 wrapped := SecurityHeaders(handler)
40
41 req := httptest.NewRequest(http.MethodGet, "/", nil)
42 rec := httptest.NewRecorder()
43 wrapped.ServeHTTP(rec, req)
44
45 // Security headers should be set
46 assert.Equal(t, "nosniff", rec.Header().Get("X-Content-Type-Options"))
47
48 // Handler's headers should also be present
49 assert.Equal(t, "application/json", rec.Header().Get("Content-Type"))
50 assert.Equal(t, "custom-value", rec.Header().Get("X-Custom-Header"))
51}
52
53func TestSecurityHeaders_CallsNextHandler(t *testing.T) {
54 called := false
55 handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
56 called = true
57 w.WriteHeader(http.StatusOK)
58 })
59
60 wrapped := SecurityHeaders(handler)
61
62 req := httptest.NewRequest(http.MethodGet, "/", nil)
63 rec := httptest.NewRecorder()
64 wrapped.ServeHTTP(rec, req)
65
66 assert.True(t, called, "next handler should have been called")
67}