secureheaders

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: MIT Imports: 8 Imported by: 2

README

build coverage 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(resources...) builds a Content-Security-Policy header value. Each Resource separates where a resource is located (URL) from how the browser requests it (Destination). The URL's scheme, host and port supply the CSP source expression; the destination selects the directive that permits it. Paths, queries and fragments do not restrict the permission.

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'.
  • Callers must parse and validate resource URLs from trusted application configuration; the builder does not sanitize them.
  • ResourceDestinationAuto, the zero value, infers conventional resources:
    • ws:///wss:// URLs select 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 local 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;
      • inferred stylesheet sources are also added to font-src;
      • URLs whose extension matches neither are ignored.
  • An explicit destination bypasses inference and selects only its named CSP directive: script, style, image, font or connect. Connect permits fetches, XMLHttpRequest, EventSource, navigator.sendBeacon and WebSocket. ResourceDestinationStyle does not also select font-src; list a URL once per required destination.
  • HTTP, HTTPS, WebSocket and scheme-relative URLs with hosts are supported. Nil URLs, URLs without hosts, unsupported schemes and unknown destinations are ignored.
  • Hosts must match the CSP host-source grammar. IPv6 literals and hostnames containing underscores are ignored; internationalized hostnames must use their ASCII A-label (Punycode) form.
  • A scheme-relative URL produces a schemeless source. For an HTTP protected resource it permits HTTP and HTTPS; for HTTPS it permits HTTPS only. It does not permit WebSocket connections; use an explicit ws:// or wss:// URL for those. A scheme-relative * host without a port is ignored.

Example:

stylesheet := &url.URL{Scheme: "https", Host: "cdn.example.com", Path: "/site.css"}
module := &url.URL{Scheme: "https", Host: "modules.example.com", Path: "/module.wasm"}

csp := secureheaders.BuildContentSecurityPolicy(
	secureheaders.Resource{URL: stylesheet},
	secureheaders.Resource{URL: module, Destination: secureheaders.ResourceDestinationConnect},
)
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

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildContentSecurityPolicy

func BuildContentSecurityPolicy(resources ...Resource) (value string)

BuildContentSecurityPolicy returns a Content-Security-Policy header value.

Each resource contributes a host source expression according to its destination. ResourceDestinationAuto infers a destination from the URL; inferred stylesheet sources are also permitted for fonts. The same URL may be listed more than once with different explicit destinations.

With no resources, the function returns the default policy, which includes style-src 'unsafe-inline'. HTTP, HTTPS, WebSocket and scheme-relative URLs with hosts are supported. A scheme-relative URL produces a schemeless source. For an HTTP protected resource it permits HTTP and HTTPS; for HTTPS it permits HTTPS only. It does not permit WebSocket connections; use an explicit ws:// or wss:// URL for those. A scheme-relative * host without a port is ignored. Internationalized hostnames must use their ASCII A-label (Punycode) form. Resources with nil URLs, hosts outside the CSP host-source grammar, unsupported schemes or unknown destinations do not contribute a source.

Resources must come from trusted application configuration. Callers are responsible for parsing and validating URLs; this function does not sanitize them.

Example
package main

import (
	"fmt"
	"net/url"
	"strings"

	"github.com/linkdata/secureheaders"
)

func main() {
	stylesheet := &url.URL{Scheme: "https", Host: "cdn.example.com", Path: "/site.css"}
	module := &url.URL{Scheme: "https", Host: "modules.example.com", Path: "/module.wasm"}

	policy := secureheaders.BuildContentSecurityPolicy(
		secureheaders.Resource{URL: stylesheet},
		secureheaders.Resource{URL: module, Destination: secureheaders.ResourceDestinationConnect},
	)
	for directive := range strings.SplitSeq(policy, "; ") {
		if strings.HasPrefix(directive, "style-src ") ||
			strings.HasPrefix(directive, "font-src ") ||
			strings.HasPrefix(directive, "connect-src ") {
			fmt.Println(directive)
		}
	}

}
Output:
style-src 'self' 'unsafe-inline' https://cdn.example.com
font-src 'self' https://cdn.example.com
connect-src 'self' https://modules.example.com

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).

type Resource added in v1.2.0

type Resource struct {
	// URL identifies the resource.
	//
	// Its scheme, host and port form the CSP source expression. Its path, query
	// and fragment do not restrict that expression. A nil URL causes the
	// resource to be ignored.
	URL *url.URL

	// Destination selects the directive that permits the resource.
	//
	// Its zero value, [ResourceDestinationAuto], infers the destination from URL.
	Destination ResourceDestination
}

Resource describes a URL used by a generated Content-Security-Policy.

URL supplies the CSP source expression. Destination selects the directive that permits the resource.

type ResourceDestination added in v1.2.0

type ResourceDestination uint8

ResourceDestination selects the CSP directive for a Resource.

const (
	// ResourceDestinationAuto infers the destination from the resource URL.
	//
	// WebSocket URLs select [ResourceDestinationConnect]. Other conventional
	// script, stylesheet, image and font resources are inferred from the URL's
	// path extension and registered MIME type. An inferred stylesheet source is
	// also permitted for fonts. Unclassified resources are ignored.
	ResourceDestinationAuto ResourceDestination = iota

	// ResourceDestinationScript selects script-src.
	ResourceDestinationScript

	// ResourceDestinationStyle selects style-src.
	//
	// It does not also select font-src. List the resource with
	// [ResourceDestinationFont] to permit both directives.
	ResourceDestinationStyle

	// ResourceDestinationImage selects img-src.
	ResourceDestinationImage

	// ResourceDestinationFont selects font-src.
	ResourceDestinationFont

	// ResourceDestinationConnect selects connect-src.
	//
	// It permits fetch, XMLHttpRequest, EventSource, navigator.sendBeacon and
	// WebSocket requests to the URL's source.
	ResourceDestinationConnect
)

Jump to

Keyboard shortcuts

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