Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
113 changes: 113 additions & 0 deletions csp.go
Original file line number Diff line number Diff line change
@@ -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, " ")})
}
69 changes: 69 additions & 0 deletions csp_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
31 changes: 31 additions & 0 deletions middles/security.go
Original file line number Diff line number Diff line change
@@ -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)
}
79 changes: 79 additions & 0 deletions middles/security_test.go
Original file line number Diff line number Diff line change
@@ -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"))
}
Loading