secureheaders

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2026 License: MIT Imports: 6 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'
  • X-Content-Type-Options: nosniff
  • X-Frame-Options: DENY
  • X-Xss-Protection: 0
  • 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).

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 strict baseline: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-ancestors 'none'; object-src 'none'; base-uri 'self'; form-action 'self'.
  • Adds external source expressions from resourceURLs by resource type:
    • .js -> script-src
    • .css -> style-src
    • image MIME types -> img-src
    • font MIME types -> font-src
    • ws:///wss:// URLs -> connect-src

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, err := secureheaders.BuildContentSecurityPolicy(
	[]*url.URL{u1, u2},
)
if err != nil {
	panic(err)
}
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

View Source
var DefaultHeaders = http.Header{
	"Referrer-Policy":           {"strict-origin-when-cross-origin"},
	"Content-Security-Policy":   {"default-src 'self'; frame-ancestors 'none'"},
	"X-Content-Type-Options":    {"nosniff"},
	"X-Frame-Options":           {"DENY"},
	"X-Xss-Protection":          {"0"},
	"Permissions-Policy":        {"camera=(), microphone=(), geolocation=(), payment=()"},
	"Strict-Transport-Security": {"max-age=31536000; includeSubDomains"},
}

DefaultHeaders contains the default security header values used by SetHeaders.

These are not protected by a mutex, so modifying the map while serving requests is racy.

Functions

func BuildContentSecurityPolicy

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

BuildContentSecurityPolicy returns a CSP header value based on resource URLs.

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

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, DefaultHeaders is 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.
	http.Header  // The headers to set. If nil, uses DefaultHeaders
	// 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)

Jump to

Keyboard shortcuts

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