secureheaders

package module
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 27, 2026 License: MIT Imports: 7 Imported by: 2

README

build coverage goreport Docs

secureheaders

secureheaders is an http.Handler middleware that writes a secure baseline of HTTP response headers.

Default headers

SetHeaders sets:

  • Referrer-Policy: strict-origin-when-cross-origin
  • Content-Security-Policy: default-src 'self'; frame-ancestors 'none'; object-src 'none'; base-uri 'self'; form-action 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'
  • X-Content-Type-Options: nosniff
  • X-Frame-Options: DENY
  • X-Xss-Protection: 0
  • Cross-Origin-Opener-Policy: same-origin-allow-popups
  • Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=()

If the request is considered HTTPS, it also sets:

  • Strict-Transport-Security: max-age=31536000; includeSubDomains

Usage

mux := http.NewServeMux()
mux.Handle("GET /", secureheaders.Middleware{
	Handler:               myHandler,
	TrustForwardedHeaders: true,
})

TrustForwardedHeaders controls whether forwarded headers are trusted when checking if a request is secure.

Set it to true only when forwarding headers are set and sanitized by trusted infrastructure (for example, your reverse proxy).

To customize the baseline, start from a copy of the defaults and pass it to the middleware:

headers := secureheaders.DefaultHeaders()
headers.Set("Content-Security-Policy", "default-src 'self'; object-src 'none'")

mux.Handle("GET /", secureheaders.Middleware{
	Handler: myHandler,
	Header:  headers,
})

Security detection

RequestIsSecure(r, trustForwardedHeaders) always trusts r.TLS != nil.

When trustForwardedHeaders is true, it also checks:

  • X-Forwarded-Ssl: on
  • Front-End-Https: on
  • X-Forwarded-Proto
  • Forwarded (proto=https)

For list-valued forwarding headers, the first hop is used.

CSP builder

BuildContentSecurityPolicy(resourceURLs) builds a Content-Security-Policy header value from known external resources.

Behavior:

  • Starts with a baseline policy: default-src 'self'; frame-ancestors 'none'; object-src 'none'; base-uri 'self'; form-action 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'.
  • Includes style-src 'unsafe-inline' by default.
  • Expects resourceURLs to come from trusted application configuration; this helper classifies known resources and does not sanitize arbitrary user input.
  • Adds external source expressions from resourceURLs by resource type:
    • ws:///wss:// URLs -> connect-src
    • all other URLs are classified by their file extension:
      • an explicit list of common script, style, image and font extensions (including web fonts such as .woff2, .otf and .eot) is consulted first;
      • extensions not on that list fall back to the host's MIME database (mime.TypeByExtension), mapping text/javascript, application/javascript and application/ecmascript -> script-src, text/css -> style-src, image/* -> img-src and font/* -> font-src;
      • stylesheet sources are also added to font-src, since stylesheets commonly reference webfonts via relative URLs;
      • URLs whose extension matches neither are ignored.

Example:

u1, _ := url.Parse("https://cdn.jsdelivr.net/npm/bootstrap@5/dist/css/bootstrap.min.css")
u2, _ := url.Parse("https://cdn.jsdelivr.net/npm/bootstrap@5/dist/js/bootstrap.min.js")

csp := secureheaders.BuildContentSecurityPolicy(
	[]*url.URL{u1, u2},
)
w.Header().Set("Content-Security-Policy", csp)

Extra headers

To add additional response headers, wrap your handler around the middleware or set them in the wrapped handler itself after middleware processing.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildContentSecurityPolicy

func BuildContentSecurityPolicy(resourceURLs []*url.URL) (value string)

BuildContentSecurityPolicy returns a CSP header value based on resource URLs.

The default policy includes style-src 'unsafe-inline'.

Resource URLs contribute external source expressions to script, style, image, font and connect directives according to their type.

The resource URLs are expected to come from trusted application configuration, not from arbitrary user input. This function classifies known resources; it is not a URL sanitizer.

func DefaultHeaders

func DefaultHeaders() http.Header

DefaultHeaders returns a copy of the default security headers used by SetHeaders.

func RequestIsSecure

func RequestIsSecure(hr *http.Request, trustForwardedHeaders bool) (yes bool)

RequestIsSecure reports if a request should be considered HTTPS.

It always treats requests with non-nil TLS as secure.

If trustForwardedHeaders is true, it also honors the forwarding headers X-Forwarded-Ssl, Front-End-Https, X-Forwarded-Proto and Forwarded.

For list-valued forwarding headers, only the first hop is used.

func SetHeaders

func SetHeaders(src http.Header, hw http.ResponseWriter, ishttps bool)

SetHeaders sets the response headers to the values in src. If src is nil, the default security headers are used.

If ishttps is false, Strict-Transport-Security is not set.

Types

type Middleware

type Middleware struct {
	http.Handler             // Handler receives the request after security headers are set.
	Header       http.Header // The headers to set. If nil, uses the default security headers.
	// TrustForwardedHeaders enables forwarded-header HTTPS detection
	// (X-Forwarded-Ssl, Front-End-Https, X-Forwarded-Proto and Forwarded).
	// Enable only when these headers are set and sanitized by trusted
	// infrastructure.
	TrustForwardedHeaders bool
}

Middleware wraps an HTTP handler and sets secure default response headers before delegating to the wrapped handler.

The embedded Handler must be non-nil.

func (Middleware) ServeHTTP

func (m Middleware) ServeHTTP(hw http.ResponseWriter, hr *http.Request)

ServeHTTP sets the security headers on the response and then delegates to the wrapped Handler. Strict-Transport-Security is included only when the request is considered secure (see RequestIsSecure and TrustForwardedHeaders).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL