Refactor security headers in SecureHeaders middleware for improved caching and CSP

This commit is contained in:
Christian Galo 2025-04-27 23:44:34 -05:00
parent 78caaa1053
commit c83b0c50a0

View File

@ -9,23 +9,44 @@ import (
// SecurityHeaders adds security and cache-control headers to all responses
func SecureHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Set strict cache control headers
w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
// Caching headers
w.Header().Set("Cache-Control", "no-store")
// Add security headers with updated CSP
// XSSProtection provides protection against cross-site scripting attack (XSS)
w.Header().Set("X-XSS-Protection", "1; mode=block")
// ContentTypeNosniff provides protection against overriding Content-Type
w.Header().Set("X-Content-Type-Options", "nosniff")
// XFrameOptions prevents the page from being displayed in a frame
w.Header().Set("X-Frame-Options", "DENY")
// HSTS (HTTP Strict Transport Security) forces the browser to use HTTPS
w.Header().Set("Strict-Transport-Security", "max-age=3600; includeSubDomains")
// ReferrerPolicy sets the referrer information passed during navigation
w.Header().Set("Referrer-Policy", "no-referrer")
// CSP controls the resources the user agent is allowed to load for a page
w.Header().Set("Content-Security-Policy",
"default-src 'self'; "+
"script-src 'self' https://unpkg.com/htmx.org@* 'unsafe-inline'; "+
"style-src 'self' 'unsafe-inline'; "+
// Allow HTMX to load from unpkg.com
"script-src 'self' https://unpkg.com/htmx.org@*; "+
"style-src 'self'; "+
"img-src 'self' data:; "+
"connect-src 'self'; "+
"frame-ancestors 'none'; "+
"form-action 'self'")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("X-XSS-Protection", "1; mode=block")
"form-action 'self'; "+
"base-uri 'self';")
// Cross-Origin-Embedder-Policy prevents cross-origin resources from being loaded
w.Header().Set("Cross-Origin-Embedder-Policy", "require-corp")
// Cross-Origin-Opener-Policy prevents cross-origin documents from being loaded
w.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
// Cross-Origin-Resource-Policy prevents cross-origin resources from being loaded
w.Header().Set("Cross-Origin-Resource-Policy", "same-origin")
next.ServeHTTP(w, r)
})