Files
selfpost/internal/web/security.go
T
mixandClaude Opus 5.5 503939c6cf origin-strict: a change with neither Sec-Fetch-Site nor Origin is refused
Agreed with the owner on 2026-10-13 (in place of csrf-tokens), taken up on
2026-10-16 ("Да"). originAllowed (internal/web/security.go) returns false
in the "neither header" branch: such a POST is answered 403 and logged
like a cross-origin one. It was let through until now as an accepted
risk, which left a browser that sends neither open to a request forged by
any site. A browser that follows Fetch § 3.2 never sends a POST without
Origin; one too old to (Firefox before 70) can no longer save anything.

What posts to the panel without a browser: the e2e suite's client, which
now sends Origin on every form (panelClient.postForm); cmd/panel's tests
already did. Nothing else posts to it (the CLI runs in the container).

Tests: security_test's case of no headers is refused; e2e posts with
neither header and gets 403 (testFormPostWithTheBrowsersOrigin). go vet +
go test (26 packages) and make e2e on the test server for this tree.

Docs: security.md - the accepted risk struck, the ADR's decision and
trade-off say refused, the origin-check bullet; architecture § Web,
guide § the proxy; CHANGELOG [Unreleased] § Security; roadmap row done.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 23:16:27 +03:00

171 lines
8.6 KiB
Go

package web
import (
"net/http"
"net/url"
)
// contentSecurityPolicy is the panel's CSP. Everything the pages load —
// stylesheet, HTMX, the panel's own script, the favicon — is served from
// /static by this same origin, and no template carries an inline <script>,
// an inline event handler or a style="..." attribute (the
// template guard test enforces that), so 'self' needs no exemptions:
//
// - default-src 'self' covers scripts, styles, images and the XHR that
// HTMX's polling fragments use;
// - object-src/frame-ancestors 'none' remove plugin embedding and framing
// (clickjacking) outright;
// - base-uri 'none' stops an injected <base> from re-pointing every
// relative URL on the page, including the form actions;
// - form-action 'self' keeps a form from being retargeted at another host.
//
// CSP Level 3, https://www.w3.org/TR/CSP3/ § 6.8.3 "Get fetch directive
// fallback list": script, style, img, font, connect and object fall back to
// default-src; base-uri (§ 6.3.1), form-action (§ 6.4.1) and frame-ancestors
// (§ 6.4.2) are not in any list, so each is set here.
//
// This is a second line of defence: XSS is already prevented by
// html/template's contextual auto-escaping (security.md). Go 1.26,
// html/template doc.go "Security Model": template authors are trusted, the
// data is not. An attribute it does not know (hx-get, hx-swap, popovertarget)
// is escaped as plain text (attr.go attrType()), so the hx-get paths are built
// by the server, never taken from input.
const contentSecurityPolicy = "default-src 'self'; " +
"object-src 'none'; " +
"base-uri 'none'; " +
"form-action 'self'; " +
"frame-ancestors 'none'"
// strictTransportSecurity is sent only when the deployment is HTTPS-only
// (CookieSecure, the same condition that gates the cookie's Secure attribute):
// on the plain-HTTP development setup it would be meaningless at best and
// would pin the browser to a scheme the dev instance does not speak at worst.
// RFC 6797 § 8.1: a header received over insecure transport is ignored.
//
// Deliberately without includeSubDomains (RFC 6797 § 6.1.2: only with it does
// the policy reach the host's subdomains). The panel commonly lives on a
// subdomain of a domain used for other things, but it may also sit at the
// apex — and there the directive would force HTTPS on every unrelated
// subdomain of that domain for a year, which is not SelfPost's call to make.
const strictTransportSecurity = "max-age=31536000"
// secure wraps the whole router with the panel's two transport-level
// defences: the security response headers, and an origin check on every
// state-changing request.
//
// It sits outside the authentication middleware on purpose, so that POST
// /login and POST /setup/{token} are covered too.
func (s *Server) secure(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("Content-Security-Policy", contentSecurityPolicy)
h.Set("X-Content-Type-Options", "nosniff")
// Equivalent to the CSP's frame-ancestors directive, kept for browsers
// that predate it. The two never disagree: both mean "never framed".
// CSP3 § 6.4.2.2: 'none' is DENY, and where frame-ancestors is
// enforced X-Frame-Options is ignored.
h.Set("X-Frame-Options", "DENY")
// Panel URLs carry domain names and record identifiers that need not
// leak to anything the administrator clicks through to: same-origin
// sends no referrer to another site. Not no-referrer, which the
// origin check below depends on: under it a browser sends a form
// POST - a navigation - with Origin: null, refused whenever
// Sec-Fetch-Site is absent (Safari before 16.4, any browser over
// plain HTTP at a name). Fetch Standard § 3.2 "append a request
// `Origin` header": "no-referrer" sets the serialised origin to null;
// "same-origin" does so only when the request is not same origin
// with its URL (assumptions D-B3).
h.Set("Referrer-Policy", "same-origin")
if s.cfg.CookieSecure {
h.Set("Strict-Transport-Security", strictTransportSecurity)
}
if !originAllowed(r) {
// Log both sides of the comparison. The check depends on r.Host
// being the name the browser actually used, which every reverse
// proxy fragment this project ships preserves (Apache
// ProxyPreserveHost On, nginx proxy_set_header Host $host, Caddy
// and Traefik by default: httpd.apache.org/docs/2.4/mod/mod_proxy.html
// #proxypreservehost; nginx.org ngx_http_proxy_module
// #proxy_set_header, whose default is $proxy_host; Caddy 2
// reverse_proxy § Headers > Defaults, "passes through incoming
// headers - including Host"; Traefik service load balancer,
// passHostHeader true by default) — but a proxy that rewrites Host turns
// every form submission into a 403, and without these two values
// side by side the symptom just looks like "the panel stopped
// saving anything".
logf("panel: rejected %s %s: cross-origin request (Sec-Fetch-Site=%q Origin=%q Host=%q); "+
"if this was a legitimate request, check that the reverse proxy passes the original Host header through",
r.Method, r.URL.Path, r.Header.Get("Sec-Fetch-Site"), r.Header.Get("Origin"), r.Host)
http.Error(w, "cross-origin request rejected", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
// originAllowed reports whether a state-changing request came from the panel's
// own origin. This is what the session cookie's
// SameSite=Lax attribute cannot do on its own: SameSite is judged per *site*
// (registrable domain), so a neighbouring subdomain — a CMS on the same
// domain, a forgotten staging host — counts as same-site and its forged POST
// would arrive with the session cookie attached. Sec-Fetch-Site and Origin are
// judged per *origin*, so they tell that neighbour apart from the panel.
// draft-ietf-httpbis-rfc6265bis § 5.2 (same-site is the [SAMESITE] "same
// site" of the two origins); W3C Fetch Metadata § 2.3 (Sec-Fetch-Site:
// same-origin only if every URL of the request is same origin).
//
// Read-only methods are exempt: every GET route in the panel is a read (the
// delete confirmation at GET /outbound/domains/{id}/delete only renders a form), so
// there is nothing for a cross-origin GET to change.
func originAllowed(r *http.Request) bool {
switch r.Method {
case http.MethodGet, http.MethodHead, http.MethodOptions:
return true
}
// The browser's own account of where the request came from. It cannot be
// set by page script (a forbidden header name), so when it is present it
// is the answer: anything but same-origin — including "none", a
// navigation with no initiator — is refused. Fetch Standard § 2.2.2: a
// header name starting with `Sec-` is a forbidden request-header; Fetch
// Metadata § 2.3: "none" is a navigation the user started directly.
if site := r.Header.Get("Sec-Fetch-Site"); site != "" {
return site == "same-origin"
}
// Older browsers send only Origin, and so does a current one over plain
// HTTP at a name other than localhost: Fetch Metadata § 3 appends its
// headers only for a potentially trustworthy URL. Fetch Standard § 3.2: a
// request that is neither GET nor HEAD carries Origin, and under this
// panel's Referrer-Policy, same-origin, it is the page's own origin for a
// form of the panel (§ 3.2; assumptions-2026-10-14, D-B3).
// Compare hosts, not full origins: the panel speaks plain HTTP behind the
// proxy and does not know its own external scheme, while Origin will say
// https.
origin := r.Header.Get("Origin")
if origin == "" {
// Neither header: nothing says where the request came from, so it is
// refused (origin-strict, owner 2026-10-13; until 2.10.4 it was let
// through as an accepted risk). By Fetch § 3.2 a browser that follows
// it never sends a POST without Origin; Firefox did for a same-origin
// form before 70 (MDN browser-compat-data 6.0.0, http.headers.Origin),
// and such a browser can no longer save anything here. A script that
// posts to the panel sends Origin itself (test/e2e, panelClient).
return false
}
u, err := url.Parse(origin)
if err != nil || u.Host == "" {
// Unparseable, or the opaque "null" origin (sandboxed iframe,
// redirected cross-origin POST) — not this panel either way.
// Fetch Standard § 2.2.5 "serializing a request origin": "null" for a
// redirect-tainted request; HTML § 7.1.1: an opaque origin serialises
// to "null"; url.Parse("null") has no Host. (Fetch § 3.2 also sends
// "null" under Referrer-Policy no-referrer, which this panel therefore
// does not set: D-B3 of the same register.)
return false
}
return u.Host == r.Host
}