This commit is contained in:
juanatsap
2025-10-31 11:06:38 +00:00
parent 5d2f763d2e
commit a5804936ba
16 changed files with 3096 additions and 283 deletions
+30 -11
View File
@@ -1,8 +1,11 @@
package middleware
import "net/http"
import (
"net/http"
"os"
)
// SecurityHeaders adds common security headers to responses
// SecurityHeaders adds production-grade security headers to responses
func SecurityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Prevent clickjacking
@@ -11,19 +14,35 @@ func SecurityHeaders(next http.Handler) http.Handler {
// Prevent MIME type sniffing
w.Header().Set("X-Content-Type-Options", "nosniff")
// XSS Protection (legacy but still useful)
// XSS Protection (legacy but still useful for older browsers)
w.Header().Set("X-XSS-Protection", "1; mode=block")
// Referrer policy
// Referrer policy - strict privacy
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
// Content Security Policy (adjust as needed)
w.Header().Set("Content-Security-Policy",
"default-src 'self'; "+
"script-src 'self' 'unsafe-inline' https://unpkg.com; "+
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "+
"font-src 'self' https://fonts.gstatic.com; "+
"connect-src 'self'")
// 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'; " +
"script-src 'self' 'unsafe-inline' https://unpkg.com; " +
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " +
"font-src 'self' https://fonts.gstatic.com; " +
"img-src 'self' data: https:; " +
"connect-src 'self'; " +
"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")
}
next.ServeHTTP(w, r)
})