security.go

43 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
package application

import (
	"fmt"
	"net/http"
)

// SecurityHeaders returns a middleware that sets security response headers
// on every response. CSP uses a per-request nonce from NonceMiddleware.
//
// The CSP policy:
//   - script-src uses nonce + strict-dynamic (CDN scripts loaded by nonce'd scripts inherit trust)
//   - 'unsafe-inline' is a CSP2 fallback, ignored by CSP3 browsers when a nonce is present
//   - style-src allows 'unsafe-inline' because Tailwind CSS Browser runtime needs it
//   - frame-ancestors 'none' replaces X-Frame-Options in CSP-aware browsers
func SecurityHeaders() Middleware {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			nonce := NonceFromContext(r.Context())

			w.Header().Set("X-Content-Type-Options", "nosniff")
			w.Header().Set("X-Frame-Options", "DENY")
			w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
			w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")

			if nonce != "" {
				csp := fmt.Sprintf(
					"default-src 'self'; "+
						"script-src 'nonce-%s' 'strict-dynamic' 'unsafe-inline' https:; "+
						"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com https://fonts.gstatic.com; "+
						"img-src 'self' data: https:; "+
						"font-src 'self' https://fonts.gstatic.com; "+
						"connect-src 'self'; "+
						"frame-ancestors 'none'; object-src 'none'; base-uri 'self'",
					nonce,
				)
				w.Header().Set("Content-Security-Policy", csp)
			}

			next.ServeHTTP(w, r)
		})
	}
}