veylant/internal/middleware/securityheaders.go
2026-02-23 13:35:04 +01:00

36 lines
1.6 KiB
Go

package middleware
import "net/http"
// SecurityHeaders returns a middleware that injects security hardening headers
// into every HTTP response. HSTS is only added in production to avoid breaking
// local HTTP development.
//
// Headers applied:
// - X-Content-Type-Options: nosniff — prevents MIME-type sniffing
// - X-Frame-Options: DENY — blocks clickjacking
// - X-XSS-Protection: 1; mode=block — legacy XSS filter for older browsers
// - Referrer-Policy — limits referrer leakage
// - Permissions-Policy — disables dangerous browser features
// - Content-Security-Policy — restricts resource loading for API routes
// - Cross-Origin-Opener-Policy: same-origin — isolates browsing context
// - Strict-Transport-Security — production only (requires HTTPS)
func SecurityHeaders(env string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("X-Content-Type-Options", "nosniff")
h.Set("X-Frame-Options", "DENY")
h.Set("X-XSS-Protection", "1; mode=block")
h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
h.Set("Permissions-Policy", "geolocation=(), microphone=(), camera=()")
h.Set("Content-Security-Policy", "default-src 'none'; base-uri 'self'; connect-src 'self'; frame-ancestors 'none'")
h.Set("Cross-Origin-Opener-Policy", "same-origin")
if env == "production" {
h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
}
next.ServeHTTP(w, r)
})
}
}