Documentation
¶
Index ¶
- func BuildContentSecurityPolicy(resources ...Resource) (value string)
- func BuildContentSecurityPolicyForURLs(urls ...*url.URL) (value string)
- func DefaultHeaders() http.Header
- func RequestIsSecure(hr *http.Request, trustForwardedHeaders bool) (yes bool)
- func SetHeaders(src http.Header, hw http.ResponseWriter, ishttps bool)
- type Middleware
- type Resource
- type ResourceDestination
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BuildContentSecurityPolicy ¶
BuildContentSecurityPolicy returns a Content-Security-Policy header value.
Each resource contributes a host source expression to its selected destinations. ResourceDestinationAuto applies its documented URL inference. Other destination values may be combined with bitwise OR. Use BuildContentSecurityPolicyForURLs when every URL uses automatic inference.
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. HTTP, HTTPS and scheme-relative sources do 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, URLs with hosts outside the CSP host-source grammar, unsupported schemes or destination bitmasks containing unknown bits 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"}
api := &url.URL{Scheme: "https", Host: "api.example.com", Path: "/data"}
policy := secureheaders.BuildContentSecurityPolicy(
secureheaders.Resource{
URL: stylesheet,
Destination: secureheaders.ResourceDestinationStyle |
secureheaders.ResourceDestinationFont,
},
secureheaders.Resource{URL: api, 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://api.example.com
func BuildContentSecurityPolicyForURLs ¶ added in v1.4.0
BuildContentSecurityPolicyForURLs returns a Content-Security-Policy header value using automatic destination inference.
Each non-nil URL uses ResourceDestinationAuto, including its ResourceDestinationConnect fallback for otherwise-unclassified hosted HTTP, HTTPS and scheme-relative URLs. Use BuildContentSecurityPolicy with explicit destinations when URL conventions do not match the request context. With no URLs, it returns the default policy. Source validation matches BuildContentSecurityPolicy.
URLs must come from trusted application configuration because permissions apply to origins, not paths.
Example ¶
package main
import (
"fmt"
"net/url"
"strings"
"github.com/linkdata/secureheaders"
)
func main() {
script := &url.URL{Scheme: "https", Host: "cdn.example.com", Path: "/app.js"}
api := &url.URL{Scheme: "https", Host: "api.example.com", Path: "/data"}
policy := secureheaders.BuildContentSecurityPolicyForURLs(script, api)
for directive := range strings.SplitSeq(policy, "; ") {
if strings.HasPrefix(directive, "script-src ") ||
strings.HasPrefix(directive, "connect-src ") {
fmt.Println(directive)
}
}
}
Output: script-src 'self' https://cdn.example.com connect-src 'self' https://api.example.com
func DefaultHeaders ¶
DefaultHeaders returns a copy of the default security headers used by SetHeaders.
func RequestIsSecure ¶
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 directives that permit the resource.
//
// Its zero value, [ResourceDestinationAuto], infers destinations from URL.
// Other values may be combined with bitwise OR.
Destination ResourceDestination
}
Resource describes a URL used by a generated Content-Security-Policy.
URL supplies the CSP source expression. Destination selects the directives that permit the resource.
type ResourceDestination ¶ added in v1.2.0
type ResourceDestination uint32
ResourceDestination is a bitmask selecting CSP directives for a Resource.
Combine explicit destinations with bitwise OR. A resource whose destination contains an unknown bit does not contribute a source.
const ( // ResourceDestinationScript selects script-src. ResourceDestinationScript ResourceDestination = 1 << iota // ResourceDestinationStyle selects style-src. ResourceDestinationStyle // ResourceDestinationImage selects img-src. ResourceDestinationImage // ResourceDestinationFont selects font-src. ResourceDestinationFont // ResourceDestinationConnect selects connect-src. // // Use an HTTP, HTTPS or scheme-relative URL for fetch, XMLHttpRequest, // EventSource and navigator.sendBeacon. WebSocket connections require a ws // or wss URL. ResourceDestinationConnect )
const ResourceDestinationAuto ResourceDestination = 0
ResourceDestinationAuto infers destinations from the resource URL.
As the zero value, it applies when no explicit destination bits are set and has no effect when combined with explicit bits. To extend inference, combine a recognized result from InferResourceDestinations with explicit bits. WebSocket URLs select ResourceDestinationConnect. Conventional scripts, stylesheets, images and fonts are inferred from the path extension and registered MIME type; MIME matching is case-insensitive. When ordinary extension inference fails, a trailing @version suffix in the final path segment is ignored, so app.js@4.4.1 is inferred as JavaScript. An inferred stylesheet selects ResourceDestinationStyle, ResourceDestinationImage and ResourceDestinationFont. An otherwise-unclassified HTTP, HTTPS or scheme-relative URL with a hostname selects ResourceDestinationConnect.
Inference uses URL conventions, not the actual request context. Hosted script and stylesheet URLs without a recognized asset extension fall back to ResourceDestinationConnect and need explicit destinations. A fetched URL with a recognized asset extension also needs ResourceDestinationConnect. The builder does not generate worker-src, media-src, frame-src or manifest-src directives.
func InferResourceDestinations ¶ added in v1.3.0
func InferResourceDestinations(u *url.URL) (destinations ResourceDestination, recognized bool)
InferResourceDestinations reports the destinations ResourceDestinationAuto infers for u.
The result is (ResourceDestinationAuto, false) for a nil URL or when no automatic rule matches. Inference does not otherwise validate CSP source support or determine the application's request context.