2025-10-20 08:54:21 +01:00
|
|
|
package middleware
|
|
|
|
|
|
2025-10-31 11:06:38 +00:00
|
|
|
import (
|
|
|
|
|
"net/http"
|
|
|
|
|
"os"
|
|
|
|
|
)
|
2025-10-20 08:54:21 +01:00
|
|
|
|
2025-10-31 11:06:38 +00:00
|
|
|
// SecurityHeaders adds production-grade security headers to responses
|
2025-10-20 08:54:21 +01:00
|
|
|
func SecurityHeaders(next http.Handler) http.Handler {
|
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
// Prevent clickjacking
|
|
|
|
|
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
|
|
|
|
|
|
|
|
|
|
// Prevent MIME type sniffing
|
|
|
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
|
|
|
|
2025-10-31 11:06:38 +00:00
|
|
|
// XSS Protection (legacy but still useful for older browsers)
|
2025-10-20 08:54:21 +01:00
|
|
|
w.Header().Set("X-XSS-Protection", "1; mode=block")
|
|
|
|
|
|
2025-10-31 11:06:38 +00:00
|
|
|
// Referrer policy - strict privacy
|
2025-10-20 08:54:21 +01:00
|
|
|
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
|
|
|
|
|
|
2025-10-31 11:06:38 +00:00
|
|
|
// Permissions Policy - disable unnecessary features
|
|
|
|
|
w.Header().Set("Permissions-Policy",
|
|
|
|
|
"geolocation=(), microphone=(), camera=(), payment=(), usb=(), "+
|
|
|
|
|
"magnetometer=(), gyroscope=(), accelerometer=()")
|
|
|
|
|
|
|
|
|
|
// Content Security Policy (comprehensive)
|
|
|
|
|
csp := "default-src 'self'; " +
|
2025-11-07 11:49:47 +00:00
|
|
|
"script-src 'self' 'unsafe-inline' https://unpkg.com https://code.iconify.design; " +
|
2025-10-31 11:06:38 +00:00
|
|
|
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " +
|
|
|
|
|
"font-src 'self' https://fonts.gstatic.com; " +
|
|
|
|
|
"img-src 'self' data: https:; " +
|
2025-11-07 11:49:47 +00:00
|
|
|
"connect-src 'self' https://api.iconify.design; " +
|
2025-10-31 11:06:38 +00:00
|
|
|
"frame-ancestors 'self'; " +
|
|
|
|
|
"base-uri 'self'; " +
|
|
|
|
|
"form-action 'self'"
|
|
|
|
|
w.Header().Set("Content-Security-Policy", csp)
|
|
|
|
|
|
|
|
|
|
// HSTS - only in production with HTTPS
|
|
|
|
|
if os.Getenv("GO_ENV") == "production" {
|
|
|
|
|
// 1 year max-age, include subdomains
|
|
|
|
|
w.Header().Set("Strict-Transport-Security",
|
|
|
|
|
"max-age=31536000; includeSubDomains; preload")
|
|
|
|
|
}
|
2025-10-20 08:54:21 +01:00
|
|
|
|
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
|
})
|
|
|
|
|
}
|