gohorsejobs/backend/internal/middleware/security_headers.go
Tiago Yamamoto 15fe5db50e fix(backend): relax CSP for Swagger UI docs
- Allow 'unsafe-inline' and 'unsafe-eval' scripts on /docs routes
- Swagger UI requires inline scripts to function properly
- Keep strict CSP for all other API routes
2025-12-14 09:04:19 -03:00

44 lines
1.6 KiB
Go

package middleware
import (
"net/http"
"strings"
)
// SecurityHeadersMiddleware adds essential security headers to all responses
// Based on OWASP guidelines
func SecurityHeadersMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Prevent clickjacking (allow framing for Swagger UI)
if strings.HasPrefix(r.URL.Path, "/docs") {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
} else {
w.Header().Set("X-Frame-Options", "DENY")
}
// Prevent MIME sniffing
w.Header().Set("X-Content-Type-Options", "nosniff")
// Enable XSS filter
w.Header().Set("X-XSS-Protection", "1; mode=block")
// Only send referrer for same-origin
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
// Permissions policy (disable potentially dangerous features)
w.Header().Set("Permissions-Policy", "geolocation=(), microphone=(), camera=()")
// Content Security Policy - relaxed for Swagger UI docs
if strings.HasPrefix(r.URL.Path, "/docs") {
// Swagger UI needs unsafe-inline and unsafe-eval for its scripts
w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:")
} else {
w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'")
}
// HSTS - uncomment in production with HTTPS
// w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
next.ServeHTTP(w, r)
})
}