Enhance security headers by adding Content-Security-Policy with environment-based upgrade-insecure-requests directive

This commit is contained in:
Christian Galo 2025-05-04 22:14:13 -05:00
parent 4698361d2f
commit 0c446e244b

View File

@ -2,6 +2,8 @@ package middleware
import ( import (
"net/http" "net/http"
"github.com/spf13/viper"
) )
// SecurityHeaders adds security and cache-control headers to all responses // SecurityHeaders adds security and cache-control headers to all responses
@ -27,16 +29,25 @@ func SecureHeaders() Middleware {
w.Header().Set("Referrer-Policy", "no-referrer") w.Header().Set("Referrer-Policy", "no-referrer")
// CSP controls the resources the user agent is allowed to load for a page // CSP controls the resources the user agent is allowed to load for a page
w.Header().Set("Content-Security-Policy", cspPolicy := "default-src 'self'; " +
"default-src 'self'; "+ // Allow HTMX to load from unpkg.com
// Allow HTMX to load from unpkg.com "script-src 'self' https://unpkg.com/htmx.org@*; " +
"script-src 'self' https://unpkg.com/htmx.org@*; "+ "style-src 'self'; " +
"style-src 'self'; "+ "img-src 'self' data:; " +
"img-src 'self' data:; "+ "font-src 'self'; " +
"connect-src 'self'; "+ "connect-src 'self'; " +
"frame-ancestors 'none'; "+ "object-src 'none'; " +
"form-action 'self'; "+ "frame-ancestors 'none'; " +
"base-uri 'self';") "form-action 'self'; " +
"base-uri 'self';"
// Add upgrade-insecure-requests directive only in production
if viper.GetString("environment") == "production" {
cspPolicy += "upgrade-insecure-requests;"
}
// Set Content-Security-Policy header
w.Header().Set("Content-Security-Policy", cspPolicy)
// Cross-Origin-Embedder-Policy prevents cross-origin resources from being loaded // Cross-Origin-Embedder-Policy prevents cross-origin resources from being loaded
w.Header().Set("Cross-Origin-Embedder-Policy", "require-corp") w.Header().Set("Cross-Origin-Embedder-Policy", "require-corp")