diff --git a/README.md b/README.md index a915af1..ddd2078 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,37 @@ webtools.DisableCacheControl(w) webtools.SetBasicAuth(w, "admin", "passw0rd") ``` +- Content Security Policy + - `Content-Security-Policy` + - `Strict-Transport-Security` + - `X-Content-Type-Options` + - `X-Frame-Options` + - `Referrer-Policy` + - `Permissions-Policy` + - `Cross-Origin-Opener-Policy` + - `Cross-Origin-Resource-Policy` + +```go +webtools.SetSecurity(w, secure, webtools.DefaultCSP) +``` + +Passing an empty `csp` uses `webtools.DefaultCSP`, a strict self-only policy. +The `secure` argument controls `Strict-Transport-Security`, which must not be +set for plain HTTP responses. + +Build a custom policy from `DefaultCSP` without copying it using `BuildCSP`, +which applies each option in order: + +```go +csp := webtools.BuildCSP( + webtools.WithScriptSrc("https://cdn.example.com"), + webtools.WithConnectSrc("https://api.example.com"), +) +``` + +The `With*` options append to their source-list directive, retaining the +default `'self'` source. Use `WithCSP` to replace the policy outright. + ##### sanitize a url Use `Sanitize` to remove known trackers from URL parameters. @@ -222,6 +253,17 @@ type Sessions[I identity.UserIdentity] interface { } ``` +The `SecurityHTTP` middleware applies a baseline of security response headers +to every response it serves. + +```go +handler := &middles.SecurityHTTP{ + Environment: environment, // gates Strict-Transport-Security on non-local + CSP: "", // empty uses webtools.DefaultCSP + H: router, +} +``` + #### package webtools/httpclient Provides a sharable `http.Client` that sets sensible values for maintaining a diff --git a/csp.go b/csp.go new file mode 100644 index 0000000..1958720 --- /dev/null +++ b/csp.go @@ -0,0 +1,113 @@ +package webtools + +import "strings" + +// CSPOption customizes a Content-Security-Policy built from DefaultCSP. +// +// Construct options using the With* functions in this package. The zero +// options (a nil slice) reproduce DefaultCSP exactly. +type CSPOption func(*csp) + +// csp is the internal representation of a Content-Security-Policy, holding +// each directive in declaration order. +type csp struct { + directives []directive +} + +// directive is a single Content-Security-Policy directive: a name and its +// whitespace separated value. +type directive struct { + name string + value string +} + +// BuildCSP returns a Content-Security-Policy string built from DefaultCSP, +// applying each option in order. Passing no options returns DefaultCSP +// verbatim. +func BuildCSP(opts ...CSPOption) string { + c := parseCSP(DefaultCSP) + for _, opt := range opts { + if opt != nil { + opt(c) + } + } + return c.String() +} + +// WithScriptSrc appends the given origins to the script-src directive, +// retaining the default 'self' source. +func WithScriptSrc(origins ...string) CSPOption { + return func(c *csp) { c.append("script-src", origins...) } +} + +// WithStyleSrc appends the given origins to the style-src directive, +// retaining the default 'self' source. +func WithStyleSrc(origins ...string) CSPOption { + return func(c *csp) { c.append("style-src", origins...) } +} + +// WithImgSrc appends the given origins to the img-src directive, retaining +// the default 'self' source. +func WithImgSrc(origins ...string) CSPOption { + return func(c *csp) { c.append("img-src", origins...) } +} + +// WithFontSrc appends the given origins to the font-src directive, retaining +// the default 'self' source. +func WithFontSrc(origins ...string) CSPOption { + return func(c *csp) { c.append("font-src", origins...) } +} + +// WithConnectSrc appends the given origins to the connect-src directive, +// retaining the default 'self' source. +func WithConnectSrc(origins ...string) CSPOption { + return func(c *csp) { c.append("connect-src", origins...) } +} + +// WithFrameSrc appends the given origins to the frame-src directive. Note that +// DefaultCSP does not declare frame-src; this option adds the directive with +// the given origins. +func WithFrameSrc(origins ...string) CSPOption { + return func(c *csp) { c.append("frame-src", origins...) } +} + +// WithCSP replaces the entire policy with the given string. Use it when a +// fully custom Content-Security-Policy is required instead of DefaultCSP with +// overrides. +func WithCSP(s string) CSPOption { + return func(c *csp) { + c.directives = parseCSP(s).directives + } +} + +// parseCSP splits a serialized Content-Security-Policy into its directives. +func parseCSP(s string) *csp { + c := &csp{} + for _, part := range strings.Split(s, "; ") { + name, value, _ := strings.Cut(part, " ") + c.directives = append(c.directives, directive{name: name, value: value}) + } + return c +} + +// String serializes the policy back into a single header value. +func (c *csp) String() string { + parts := make([]string, 0, len(c.directives)) + for _, d := range c.directives { + parts = append(parts, d.name+" "+d.value) + } + return strings.Join(parts, "; ") +} + +// append adds origins to the named directive, retaining any existing value. +func (c *csp) append(name string, origins ...string) { + for i := range c.directives { + if c.directives[i].name == name { + c.directives[i].value += " " + strings.Join(origins, " ") + return + } + } + + // directive not present; add a new one + c.directives = append(c.directives, directive{name: name, value: strings.Join(origins, " ")}) +} diff --git a/csp_test.go b/csp_test.go new file mode 100644 index 0000000..b0940f3 --- /dev/null +++ b/csp_test.go @@ -0,0 +1,69 @@ +package webtools + +import ( + "testing" + + "github.com/shoenig/test/must" +) + +func Test_BuildCSP_default(t *testing.T) { + t.Parallel() + + must.Eq(t, DefaultCSP, BuildCSP()) + must.Eq(t, DefaultCSP, BuildCSP(nil)) +} + +func Test_BuildCSP_scriptSrc(t *testing.T) { + t.Parallel() + + got := BuildCSP(WithScriptSrc("https://cdn.jsdelivr.net")) + want := "default-src 'self'; " + + "script-src 'self' https://cdn.jsdelivr.net; " + + "style-src 'self'; " + + "style-src-attr 'unsafe-inline'; " + + "img-src 'self'; " + + "font-src 'self'; " + + "connect-src 'self'; " + + "form-action 'self'; " + + "frame-ancestors 'none'; " + + "base-uri 'none'; " + + "object-src 'none'" + must.Eq(t, want, got) +} + +func Test_BuildCSP_multiple_origins(t *testing.T) { + t.Parallel() + + got := BuildCSP(WithScriptSrc("https://cdn.example.com", "https://cdn2.example.com")) + must.StrContains(t, got, "script-src 'self' https://cdn.example.com https://cdn2.example.com") +} + +func Test_BuildCSP_multiple_directives(t *testing.T) { + t.Parallel() + + got := BuildCSP( + WithScriptSrc("https://cdn.example.com"), + WithConnectSrc("https://api.example.com"), + ) + + must.StrContains(t, got, "script-src 'self' https://cdn.example.com") + must.StrContains(t, got, "connect-src 'self' https://api.example.com") +} + +func Test_BuildCSP_frameSrc(t *testing.T) { + t.Parallel() + + got := BuildCSP(WithFrameSrc("https://example.com")) + + must.StrContains(t, got, "frame-src https://example.com") + must.StrHasSuffix(t, "frame-src https://example.com", got) +} + +func Test_BuildCSP_withCSP(t *testing.T) { + t.Parallel() + + const custom = "default-src 'self'; script-src 'self' https://cdn.example.com" + + got := BuildCSP(WithCSP(custom)) + must.Eq(t, custom, got) +} diff --git a/middles/security.go b/middles/security.go new file mode 100644 index 0000000..c6ed9e2 --- /dev/null +++ b/middles/security.go @@ -0,0 +1,31 @@ +package middles + +import ( + "net/http" + + "cattlecloud.net/go/webtools" + "cattlecloud.net/go/webtools/runtime" +) + +// SecurityHTTP is a middleware that applies a baseline of security response +// headers to every response it serves, including Content-Security-Policy, +// X-Content-Type-Options, X-Frame-Options, Referrer-Policy, +// Permissions-Policy, Cross-Origin-Opener-Policy, and +// Cross-Origin-Resource-Policy. +// +// Strict-Transport-Security is only applied when the environment is not local, +// since it must never be set for plain HTTP responses. +// +// When CSP is empty, webtools.DefaultCSP is used. Applications that need to +// allow additional origins (for example a CDN-hosted script) should set CSP to +// their own policy. +type SecurityHTTP struct { + Environment runtime.Environment + CSP string + H http.Handler +} + +func (s *SecurityHTTP) ServeHTTP(w http.ResponseWriter, r *http.Request) { + webtools.SetSecurity(w, s.Environment.NonLocal(), s.CSP) + s.H.ServeHTTP(w, r) +} diff --git a/middles/security_test.go b/middles/security_test.go new file mode 100644 index 0000000..174946e --- /dev/null +++ b/middles/security_test.go @@ -0,0 +1,79 @@ +package middles + +import ( + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + + "cattlecloud.net/go/webtools" + "cattlecloud.net/go/webtools/runtime" + "github.com/shoenig/test/must" +) + +func TestSecurityHTTP_ServeHTTP_local(t *testing.T) { + t.Parallel() + + run := new(atomic.Bool) + s := &SecurityHTTP{ + Environment: runtime.Setup(&runtime.Config{ + Environment: "local", + Domain: "example.com", + }), + H: http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { + run.Store(true) + }), + } + + w := httptest.NewRecorder() + r, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil) + s.ServeHTTP(w, r) + + must.True(t, run.Load()) + must.Eq(t, "", w.Header().Get("Strict-Transport-Security")) + must.Eq(t, webtools.DefaultCSP, w.Header().Get("Content-Security-Policy")) + must.Eq(t, "nosniff", w.Header().Get("X-Content-Type-Options")) +} + +func TestSecurityHTTP_ServeHTTP_production(t *testing.T) { + t.Parallel() + + s := &SecurityHTTP{ + Environment: runtime.Setup(&runtime.Config{ + Environment: "production", + Domain: "example.com", + }), + H: http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {}), + } + + w := httptest.NewRecorder() + r, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil) + s.ServeHTTP(w, r) + + must.Eq(t, "max-age=31536000; includeSubDomains", w.Header().Get("Strict-Transport-Security")) + must.Eq(t, "DENY", w.Header().Get("X-Frame-Options")) + must.Eq(t, "no-referrer", w.Header().Get("Referrer-Policy")) + must.Eq(t, "same-origin", w.Header().Get("Cross-Origin-Opener-Policy")) + must.Eq(t, "same-origin", w.Header().Get("Cross-Origin-Resource-Policy")) +} + +func TestSecurityHTTP_ServeHTTP_customCSP(t *testing.T) { + t.Parallel() + + const csp = "default-src 'self'; script-src 'self' https://cdn.example.com" + + s := &SecurityHTTP{ + Environment: runtime.Setup(&runtime.Config{ + Environment: "production", + Domain: "example.com", + }), + CSP: csp, + H: http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {}), + } + + w := httptest.NewRecorder() + r, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil) + s.ServeHTTP(w, r) + + must.Eq(t, csp, w.Header().Get("Content-Security-Policy")) +} diff --git a/security.go b/security.go new file mode 100644 index 0000000..39cc2e3 --- /dev/null +++ b/security.go @@ -0,0 +1,55 @@ +package webtools + +import ( + "net/http" + + "github.com/shoenig/lang" +) + +// DefaultCSP is a strict, self-only Content-Security-Policy suitable for most +// applications. It permits nothing from any origin other than the application +// itself, and explicitly forbids inline script execution. +// +// Applications that need to load resources from additional origins (for +// example a CDN-hosted script) should construct their own policy and pass it +// to SetSecurityHeaders or middles.SecurityHTTP. The directive values below +// are safe to copy as a starting point. +const DefaultCSP = "default-src 'self'; " + + "script-src 'self'; " + + "style-src 'self'; " + + "style-src-attr 'unsafe-inline'; " + + "img-src 'self'; " + + "font-src 'self'; " + + "connect-src 'self'; " + + "form-action 'self'; " + + "frame-ancestors 'none'; " + + "base-uri 'none'; " + + "object-src 'none'" + +// SetSecurity applies a baseline of security response headers to w. +// +// The headers set are Content-Security-Policy, X-Content-Type-Options, +// X-Frame-Options, Referrer-Policy, Permissions-Policy, +// Cross-Origin-Opener-Policy, and Cross-Origin-Resource-Policy. +// +// Strict-Transport-Security is only set when secure is true, which should +// reflect whether the response is being served over HTTPS. It must not be +// set for plain HTTP responses (e.g. local development), where browsers will +// ignore it anyway and it risks pinning the wrong origin. +// +// When csp is empty, DefaultCSP is used. +func SetSecurity(w http.ResponseWriter, secure bool, csp string) { + h := w.Header() + + if secure { + h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains") + } + + h.Set("Content-Security-Policy", lang.Maybe(csp == "", DefaultCSP, csp)) + h.Set("X-Content-Type-Options", "nosniff") + h.Set("X-Frame-Options", "DENY") + h.Set("Referrer-Policy", "no-referrer") + h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=(), usb=()") + h.Set("Cross-Origin-Opener-Policy", "same-origin") + h.Set("Cross-Origin-Resource-Policy", "same-origin") +} diff --git a/security_test.go b/security_test.go new file mode 100644 index 0000000..c7c53b6 --- /dev/null +++ b/security_test.go @@ -0,0 +1,46 @@ +package webtools + +import ( + "net/http/httptest" + "testing" + + "github.com/shoenig/test/must" +) + +func Test_SetSecurityHeaders_secure_defaultCSP(t *testing.T) { + t.Parallel() + + w := httptest.NewRecorder() + SetSecurity(w, true, "") + + h := w.Header() + must.Eq(t, "max-age=31536000; includeSubDomains", h.Get("Strict-Transport-Security")) + must.Eq(t, DefaultCSP, h.Get("Content-Security-Policy")) + must.Eq(t, "nosniff", h.Get("X-Content-Type-Options")) + must.Eq(t, "DENY", h.Get("X-Frame-Options")) + must.Eq(t, "no-referrer", h.Get("Referrer-Policy")) + must.Eq(t, "camera=(), microphone=(), geolocation=(), payment=(), usb=()", h.Get("Permissions-Policy")) + must.Eq(t, "same-origin", h.Get("Cross-Origin-Opener-Policy")) + must.Eq(t, "same-origin", h.Get("Cross-Origin-Resource-Policy")) +} + +func Test_SetSecurityHeaders_insecure_omitsHSTS(t *testing.T) { + t.Parallel() + + w := httptest.NewRecorder() + SetSecurity(w, false, "") + + must.Eq(t, "", w.Header().Get("Strict-Transport-Security")) + must.Eq(t, DefaultCSP, w.Header().Get("Content-Security-Policy")) +} + +func Test_SetSecurityHeaders_customCSP(t *testing.T) { + t.Parallel() + + const csp = "default-src 'self'; script-src 'self' https://cdn.example.com" + + w := httptest.NewRecorder() + SetSecurity(w, true, csp) + + must.Eq(t, csp, w.Header().Get("Content-Security-Policy")) +}