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 (
"net/http"
"github.com/spf13/viper"
)
// SecurityHeaders adds security and cache-control headers to all responses
@ -27,16 +29,25 @@ func SecureHeaders() Middleware {
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'; "+
// 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'; "+
"base-uri 'self';")
cspPolicy := "default-src 'self'; " +
// Allow HTMX to load from unpkg.com
"script-src 'self' https://unpkg.com/htmx.org@*; " +
"style-src 'self'; " +
"img-src 'self' data:; " +
"font-src 'self'; " +
"connect-src 'self'; " +
"object-src 'none'; " +
"frame-ancestors 'none'; " +
"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
w.Header().Set("Cross-Origin-Embedder-Policy", "require-corp")