Skip to main content

umbral_security/
lib.rs

1//! umbral-security — CSRF protection and a configurable security-header bundle.
2//!
3//! CSRF protection plus a security-header bundle,
4//! widened to the modern header set. Plug it into the app and every non-safe
5//! request must carry a matching CSRF token; every response gets the hardening
6//! headers you've enabled.
7//!
8//! ```ignore
9//! App::builder()
10//!     .plugin(AuthPlugin::new())
11//!     .plugin(SecurityPlugin::new())   // secure-but-dev-safe defaults
12//!     .build()
13//!     .await?;
14//! ```
15//!
16//! ## Configuration is a struct, not a builder chain
17//!
18//! Construct a [`SecurityConfig`] (every field has a secure, dev-safe default)
19//! and flip exactly what you need — no long `.with_x().with_y()` chain:
20//!
21//! ```ignore
22//! SecurityPlugin::with_config(SecurityConfig {
23//!     hsts: true,
24//!     content_security_policy: Some("default-src 'self'".into()),
25//!     server_header: Some("umbral".into()),
26//!     request_body_limit: Some(2 * 1024 * 1024),
27//!     ..Default::default()
28//! })
29//! ```
30//!
31//! `SecurityPlugin::new()` keeps the defaults; `SecurityPlugin::with_hsts(true)`
32//! stays as a one-flag convenience.
33//!
34//! ## CSRF
35//!
36//! Signed double-submit cookie pattern, fully automatic (see
37//! `docs/decisions/2026-06-10-automatic-csrf.md`):
38//!
39//! 1. **The middleware is the only mint.** On GET / HEAD / OPTIONS it mints a
40//!    token *before* the handler runs (first visit covered) and appends the
41//!    `umbral_csrf_token` cookie to the response. The cookie is NOT HttpOnly:
42//!    the page's JS reads it and copies it into a header on later writes.
43//! 2. **Templates get the token for free.** The token is scoped into
44//!    `umbral::templates::CURRENT_CSRF` around every non-exempt request, so
45//!    any rendered template can write `{{ csrf_input }}` (the full hidden
46//!    input) or `{{ csrf_token }}` (raw value, for `X-CSRF-Token` headers /
47//!    htmx `hx-headers`). View code never touches CSRF.
48//! 3. Every POST / PUT / PATCH / DELETE must include the cookie AND a matching
49//!    `X-CSRF-Token` header (JS path) or `csrf_token` / `__csrf` form field
50//!    (HTML-form path). A mismatch returns 403. On success the token stays in
51//!    scope so a validation-error re-render still carries it into the form.
52//!
53//! The token is a 32-byte CSPRNG value, hex-encoded. The CSRF cookie gains
54//! `Secure` automatically under `Environment::Prod` (or force it with
55//! [`SecurityConfig::csrf_cookie_secure`]).
56//!
57//! ### Signed / session-bound CSRF ([`SecurityConfig::signed_csrf`])
58//!
59//! Naive double-submit trusts the cookie: an attacker who can plant a cookie on
60//! a sibling subdomain can forge a matching token. `signed_csrf` (**default
61//! on**) makes the token `<random>.<HMAC-SHA256(secret_key, random[.session])>`
62//! — a forged cookie can't carry a valid signature without the app
63//! `secret_key`. Set [`SecurityConfig::session_bind_cookie`] to also fold the
64//! session cookie's value into the signature so a token minted under one
65//! session can't be replayed under another.
66//!
67//! The flip to default-on is deploy-safe because the middleware **rotates**
68//! any cookie token that can't pass signed-mode validation on the next safe
69//! request (browsers holding pre-upgrade unsigned cookies converge instead of
70//! 403ing), and because no other mint exists: the admin prefers the ambient
71//! middleware token and only self-mints when this plugin isn't mounted. With
72//! no resolvable `secret_key` (tests, pre-`App::build()` renders) minting and
73//! validation degrade to plain double-submit instead of locking writes out.
74//! Opt back into plain double-submit with `signed_csrf: false`.
75//!
76//! ## Headers
77//!
78//! Enabled by default: `X-Content-Type-Options: nosniff`, `X-Frame-Options:
79//! DENY`, `Referrer-Policy: strict-origin-when-cross-origin`, `X-XSS-Protection:
80//! 0` (modern guidance disables the legacy auditor), `Cross-Origin-Opener-Policy:
81//! same-origin`, and a `Server: umbral` header. Opt-in
82//! (default off, each a field on [`SecurityConfig`]): `Strict-Transport-Security`,
83//! `Content-Security-Policy`, `Permissions-Policy`, `Cross-Origin-Resource-Policy`,
84//! `Cross-Origin-Embedder-Policy`. CSP and HSTS are off by default because a wrong
85//! value breaks apps (HSTS bricks `http://` dev; a strict CSP breaks the CDN-using
86//! admin).
87//!
88//! ## Server identity & tower-http knobs
89//!
90//! [`SecurityConfig::server_header`] sets the `Server` header (prefer a bare
91//! product name — a version is an information-disclosure tradeoff);
92//! [`SecurityConfig::hide_server_header`] strips whatever the stack added.
93//! [`SecurityConfig::request_body_limit`] caps the request body via tower-http's
94//! `RequestBodyLimitLayer` (DoS hardening); [`SecurityConfig::redact_sensitive_headers`]
95//! (default on) marks `authorization` / `cookie` / `set-cookie` sensitive so
96//! they're redacted in tracing output.
97//!
98//! ## Why this lives in Plugin::wrap_router
99//!
100//! Layering middleware needs a `tower::Layer` value; the Plugin trait's
101//! `wrap_router(Router) -> Router` lets each plugin layer its middleware with
102//! the full axum / tower API. The app builder calls it in topological order so
103//! security wraps everything declared before it.
104
105use std::convert::Infallible;
106
107use axum::body::Body;
108use axum::extract::{Request, State};
109use axum::middleware::{self, Next};
110use axum::response::Response;
111use http::header::{
112    AUTHORIZATION, COOKIE, HeaderName, HeaderValue, PROXY_AUTHORIZATION, SERVER, SET_COOKIE,
113};
114use http::{Method, StatusCode};
115use tower_http::limit::RequestBodyLimitLayer;
116use tower_http::sensitive_headers::SetSensitiveHeadersLayer;
117use tower_http::set_header::SetResponseHeaderLayer;
118use umbral::prelude::*;
119
120const CSRF_COOKIE: &str = "umbral_csrf_token";
121/// The session cookie name. Matches `umbral_sessions::COOKIE_NAME`, mirrored
122/// here rather than depended upon: `umbral-security` sits below `umbral-sessions`
123/// in the plugin graph and must not import it. `umbral-cache`'s `cache_page`
124/// mirrors the same literal for the same reason.
125const SESSION_COOKIE: &str = "umbral_session";
126const CSRF_HEADER: &str = "x-csrf-token";
127/// Form field name that carries the CSRF token for HTML `<form>` submissions.
128/// Two shapes are accepted — `csrf_token` and `__csrf` — so existing form code
129/// on either convention works without migration. The header path stays the
130/// canonical one for JS clients.
131const CSRF_FORM_FIELDS: &[&str] = &["csrf_token", "__csrf"];
132/// Hard cap on the buffered body size when we peek at form data to extract the
133/// CSRF field. 1 MiB is well above any realistic urlencoded form.
134const MAX_FORM_BODY: usize = 1024 * 1024;
135
136/// Declarative security configuration. Build from [`Default`] (secure,
137/// dev-safe) and override the fields you need — see the crate docs for the
138/// rationale behind each default.
139#[derive(Debug, Clone)]
140pub struct SecurityConfig {
141    // ---- CSRF ----
142    /// Run the CSRF middleware. Default `true`.
143    pub csrf: bool,
144    /// Force the `Secure` flag on the CSRF cookie. Default `false`; `Secure` is
145    /// added automatically under `Environment::Prod` regardless, so this only
146    /// matters for forcing it on in a non-prod HTTPS setup.
147    pub csrf_cookie_secure: bool,
148    /// Sign the CSRF token with the app `secret_key` (HMAC-SHA256). Default
149    /// `true` — the middleware is the only mint, so every token carries a
150    /// signature; stale unsigned cookies rotate automatically on the next
151    /// safe request. Set `false` for plain double-submit.
152    pub signed_csrf: bool,
153    /// When `signed_csrf` is on, also bind the token to this cookie's value
154    /// (typically the session cookie). Default `None`.
155    pub session_bind_cookie: Option<String>,
156    /// Request-path prefixes exempt from CSRF (CSRF-exempt paths).
157    /// A token-authenticated REST API carries no session cookie, so a
158    /// bearer-auth `POST /api/...` would otherwise 403; exempt `"/api"` to
159    /// keep it working. Matched as a path prefix. Default empty.
160    pub csrf_exempt_paths: Vec<String>,
161
162    // ---- Response headers (None / false = header omitted) ----
163    /// `X-Content-Type-Options: nosniff`. Default `true`.
164    pub content_type_options: bool,
165    /// `X-Frame-Options`. Default `Some("DENY")`.
166    pub frame_options: Option<String>,
167    /// `Referrer-Policy`. Default `Some("strict-origin-when-cross-origin")`.
168    pub referrer_policy: Option<String>,
169    /// `X-XSS-Protection`. Default `Some("0")` — disables the buggy legacy
170    /// filter rather than enabling it (current OWASP guidance).
171    pub xss_protection: Option<String>,
172    /// Emit `Strict-Transport-Security`. Default `false` (dev-safe). Value is
173    /// built from the `hsts_*` fields.
174    pub hsts: bool,
175    /// HSTS `max-age` in seconds. Default one year.
176    pub hsts_max_age: u64,
177    /// Add `; includeSubDomains` to HSTS. Default `true`.
178    pub hsts_include_subdomains: bool,
179    /// Add `; preload` to HSTS. Default `false`.
180    pub hsts_preload: bool,
181    /// `Content-Security-Policy`. Default `None` — a wrong CSP breaks apps, so
182    /// it's opt-in.
183    pub content_security_policy: Option<String>,
184    /// `Permissions-Policy`. Default `None`.
185    pub permissions_policy: Option<String>,
186    /// `Cross-Origin-Opener-Policy`. Default `Some("same-origin")`.
187    /// Set `None` to omit, e.g. apps relying on cross-origin
188    /// popups (some OAuth flows).
189    pub cross_origin_opener_policy: Option<String>,
190    /// `Cross-Origin-Resource-Policy` (e.g. `"same-origin"`). Default `None`.
191    pub cross_origin_resource_policy: Option<String>,
192    /// `Cross-Origin-Embedder-Policy` (e.g. `"require-corp"`). Default `None`.
193    pub cross_origin_embedder_policy: Option<String>,
194
195    // ---- Server identity ----
196    /// Set the `Server` response header. Default `Some("umbral")` — a bare
197    /// product name (no version, so no info disclosure), the way many app
198    /// servers advertise one. Set `None` to omit. Prefer no version.
199    pub server_header: Option<String>,
200    /// Strip any `Server` header the stack set. Default `false`. Ignored when
201    /// `server_header` is `Some` (the set wins) — to strip, also set
202    /// `server_header: None`.
203    pub hide_server_header: bool,
204
205    // ---- axum / tower-http knobs ----
206    /// Cap request body size in bytes (tower-http `RequestBodyLimitLayer`).
207    /// Default `None` (axum's own default applies).
208    pub request_body_limit: Option<usize>,
209    /// Mark `authorization` / `cookie` / `set-cookie` sensitive so tracing
210    /// redacts them. Default `true`.
211    pub redact_sensitive_headers: bool,
212
213    /// Send `Cache-Control: no-store, private` on responses to *personalised*
214    /// requests — those carrying a session cookie or an `Authorization` /
215    /// `Proxy-Authorization` header. Default `true`.
216    ///
217    /// An authenticated page holds the viewer's data and their CSRF token
218    /// (double-submit, so the token is deliberately readable — see the module
219    /// docs). Without this header nothing tells a CDN, a corporate proxy, or
220    /// the browser's back/forward cache that the page belongs to one person.
221    /// `private` stops shared caches; `no-store` stops the local disk cache
222    /// replaying an admin page after logout.
223    ///
224    /// Anonymous requests are untouched, so public pages stay cacheable, and a
225    /// handler that sets its own `Cache-Control` always wins. Turn this off
226    /// only if a cache you control already keys on the session cookie.
227    pub private_cache: bool,
228}
229
230impl Default for SecurityConfig {
231    fn default() -> Self {
232        Self {
233            csrf: true,
234            csrf_cookie_secure: false,
235            signed_csrf: true,
236            session_bind_cookie: None,
237            csrf_exempt_paths: Vec::new(),
238            content_type_options: true,
239            frame_options: Some("DENY".to_string()),
240            referrer_policy: Some("strict-origin-when-cross-origin".to_string()),
241            xss_protection: Some("0".to_string()),
242            hsts: false,
243            hsts_max_age: 31_536_000,
244            hsts_include_subdomains: true,
245            hsts_preload: false,
246            content_security_policy: None,
247            permissions_policy: None,
248            // On by default (same-origin). Isolates the browsing
249            // context group; only affects apps that rely on cross-origin popups.
250            cross_origin_opener_policy: Some("same-origin".to_string()),
251            cross_origin_resource_policy: None,
252            cross_origin_embedder_policy: None,
253            // Advertise the framework (no version, no info disclosure). Many app
254            // servers emit a `Server` header. Set `None` to omit
255            // or pair `None` + `hide_server_header` to strip an upstream one.
256            server_header: Some("umbral".to_string()),
257            hide_server_header: false,
258            request_body_limit: None,
259            redact_sensitive_headers: true,
260            // Secure by default: an authenticated page is never storable by a
261            // cache umbral doesn't control.
262            private_cache: true,
263        }
264    }
265}
266
267impl SecurityConfig {
268    /// A production-grade preset (audit_2 plugin-authz S1). The defaults are
269    /// deliberately dev-safe — HSTS, CSP, and cross-origin isolation are OFF so
270    /// local HTTP dev works — but that leaves a default deployment without an
271    /// XSS backstop (no CSP) or SSL-stripping protection (no HSTS). Rather than
272    /// have every operator hand-assemble a config and risk forgetting one, this
273    /// turns on the headline prod headers in a single call:
274    ///
275    /// - `hsts` + `hsts_preload` (long max-age, subdomains, preload-eligible),
276    /// - a strict `content_security_policy` baseline (`default-src 'self'` with
277    ///   `frame-ancestors 'none'`, `base-uri 'self'`, `form-action 'self'`) —
278    ///   loosen it per app as needed,
279    /// - `cross_origin_resource_policy: same-origin` (COOP is already same-origin
280    ///   by default),
281    /// - `csrf_cookie_secure` (prod serves over HTTPS, so the CSRF cookie should
282    ///   carry the `Secure` attribute).
283    ///
284    /// Everything else keeps the secure defaults (`csrf`, `signed_csrf`,
285    /// `nosniff`, `X-Frame-Options: DENY`, referrer policy). Note the strict CSP
286    /// has no `'unsafe-inline'`, so inline `<script>`/`<style>` won't run —
287    /// adjust the policy for your asset strategy.
288    pub fn production_hardened() -> Self {
289        Self {
290            hsts: true,
291            hsts_preload: true,
292            content_security_policy: Some(
293                "default-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"
294                    .to_string(),
295            ),
296            cross_origin_resource_policy: Some("same-origin".to_string()),
297            csrf_cookie_secure: true,
298            ..Self::default()
299        }
300    }
301
302    fn hsts_value(&self) -> String {
303        let mut v = format!("max-age={}", self.hsts_max_age);
304        if self.hsts_include_subdomains {
305            v.push_str("; includeSubDomains");
306        }
307        if self.hsts_preload {
308            v.push_str("; preload");
309        }
310        v
311    }
312}
313
314/// CSRF + security-headers plugin. Configure via [`SecurityConfig`].
315#[derive(Debug, Clone, Default)]
316pub struct SecurityPlugin {
317    config: SecurityConfig,
318}
319
320impl SecurityPlugin {
321    /// Secure, dev-safe defaults (see [`SecurityConfig`]).
322    pub fn new() -> Self {
323        Self::default()
324    }
325
326    /// Construct from an explicit config — the preferred entry point.
327    pub fn with_config(config: SecurityConfig) -> Self {
328        Self { config }
329    }
330
331    /// The production-hardening preset — HSTS + a strict CSP + CORP +
332    /// Secure CSRF cookie in one call. See
333    /// [`SecurityConfig::production_hardened`] for exactly what it flips.
334    pub fn production_hardened() -> Self {
335        Self::with_config(SecurityConfig::production_hardened())
336    }
337
338    /// Borrow the active config.
339    pub fn config(&self) -> &SecurityConfig {
340        &self.config
341    }
342
343    /// One-flag convenience for `SecurityConfig::hsts`. Equivalent to
344    /// `with_config(SecurityConfig { hsts, ..Default::default() })`.
345    pub fn with_hsts(mut self, hsts: bool) -> Self {
346        self.config.hsts = hsts;
347        self
348    }
349}
350
351impl Plugin for SecurityPlugin {
352    fn name(&self) -> &'static str {
353        "security"
354    }
355
356    fn wrap_router(&self, router: Router) -> Router {
357        let cfg = &self.config;
358        let mut router = router;
359
360        // CSRF middleware (innermost of our additions).
361        if cfg.csrf {
362            let state = CsrfState::from_config(cfg);
363            router = router.layer(middleware::from_fn_with_state(state, csrf_middleware));
364        }
365
366        // Mark personalised responses uncacheable (gaps3 #44). Sits beside the
367        // CSRF layer because it protects the same thing: the token the CSRF
368        // middleware puts on the page is only safe while that page reaches one
369        // browser.
370        if cfg.private_cache {
371            router = router.layer(middleware::from_fn(private_cache_middleware));
372        }
373
374        // Response-header setters. Order among them is irrelevant.
375        if cfg.content_type_options {
376            router = set_header(
377                router,
378                "x-content-type-options",
379                Some("nosniff".to_string()),
380            );
381        }
382        router = set_header(router, "x-frame-options", cfg.frame_options.clone());
383        router = set_header(router, "referrer-policy", cfg.referrer_policy.clone());
384        router = set_header(router, "x-xss-protection", cfg.xss_protection.clone());
385        if cfg.hsts {
386            router = set_header(router, "strict-transport-security", Some(cfg.hsts_value()));
387        }
388        router = set_header(
389            router,
390            "content-security-policy",
391            cfg.content_security_policy.clone(),
392        );
393        router = set_header(router, "permissions-policy", cfg.permissions_policy.clone());
394        router = set_header(
395            router,
396            "cross-origin-opener-policy",
397            cfg.cross_origin_opener_policy.clone(),
398        );
399        router = set_header(
400            router,
401            "cross-origin-resource-policy",
402            cfg.cross_origin_resource_policy.clone(),
403        );
404        router = set_header(
405            router,
406            "cross-origin-embedder-policy",
407            cfg.cross_origin_embedder_policy.clone(),
408        );
409
410        // Server identity: an explicit value overrides; otherwise optionally strip.
411        if let Some(v) = cfg.server_header.as_deref() {
412            if let Ok(hv) = HeaderValue::from_str(v) {
413                router = router.layer(SetResponseHeaderLayer::overriding(SERVER, hv));
414            }
415        } else if cfg.hide_server_header {
416            router = router.layer(middleware::from_fn(strip_server_header));
417        }
418
419        // tower-http knobs (outermost so they wrap everything above).
420        if cfg.redact_sensitive_headers {
421            router = router.layer(SetSensitiveHeadersLayer::new([
422                AUTHORIZATION,
423                COOKIE,
424                SET_COOKIE,
425            ]));
426        }
427        if let Some(limit) = cfg.request_body_limit {
428            router = router.layer(RequestBodyLimitLayer::new(limit));
429        }
430
431        router
432    }
433
434    fn on_ready(
435        &self,
436        _ctx: &umbral::plugin::AppContext,
437    ) -> Result<(), umbral::plugin::PluginError> {
438        let settings = umbral::settings::get_opt();
439
440        // Boot nudge: HSTS and CSP are opt-in (safe defaults for dev), but
441        // a Prod deployment shipping neither is a real exposure — SSL
442        // stripping with no HSTS, XSS with no CSP backstop. Warn loudly so
443        // the gap is visible at startup rather than discovered in an audit.
444        let is_prod = settings
445            .map(|s| matches!(s.environment, Environment::Prod))
446            .unwrap_or(false);
447        if is_prod {
448            if !self.config.hsts {
449                tracing::warn!(
450                    "SecurityPlugin: HSTS is disabled in Environment::Prod — responses ship \
451                     no Strict-Transport-Security header, leaving clients open to SSL \
452                     stripping. Enable with `.with_hsts(true)`."
453                );
454            }
455            if self.config.content_security_policy.is_none() {
456                tracing::warn!(
457                    "SecurityPlugin: no Content-Security-Policy set in Environment::Prod — \
458                     XSS has no CSP backstop. Set `content_security_policy` in SecurityConfig."
459                );
460            }
461        }
462
463        check_secret_key(settings, &self.config)?;
464
465        Ok(())
466    }
467}
468
469/// Add a `SetResponseHeaderLayer::if_not_present` for `name` when `value` is a
470/// valid header value; otherwise return the router untouched.
471fn set_header(router: Router, name: &'static str, value: Option<String>) -> Router {
472    match value.as_deref().and_then(|v| HeaderValue::from_str(v).ok()) {
473        Some(hv) => router.layer(SetResponseHeaderLayer::if_not_present(
474            HeaderName::from_static(name),
475            hv,
476        )),
477        None => router,
478    }
479}
480
481/// Per-request CSRF state captured at `wrap_router` time. The `secret` is read
482/// once from settings (absent in tests / before `App::build()` — signing then
483/// degrades to plain double-submit rather than panicking).
484#[derive(Clone)]
485struct CsrfState {
486    secure: bool,
487    signed: bool,
488    secret: Option<String>,
489    session_cookie: Option<String>,
490    exempt_paths: Vec<String>,
491}
492
493impl CsrfState {
494    fn from_config(cfg: &SecurityConfig) -> Self {
495        let is_prod = umbral::settings::get_opt()
496            .map(|s| matches!(s.environment, Environment::Prod))
497            .unwrap_or(false);
498        Self {
499            secure: cfg.csrf_cookie_secure || is_prod,
500            signed: cfg.signed_csrf,
501            // audit_2 S3: do NOT capture the signing secret here. `wrap_router`
502            // (where this runs) could execute before `umbral::settings` is in
503            // the OnceLock, which would pin `secret = None` and silently degrade
504            // signed CSRF to plain double-submit for the app's whole life — even
505            // in prod, where `on_ready` later confirms a secret exists. Resolve
506            // it per request in `resolve_secret` instead, so there is no
507            // build-order dependency. The field stays for test injection.
508            secret: None,
509            session_cookie: cfg.session_bind_cookie.clone(),
510            exempt_paths: cfg.csrf_exempt_paths.clone(),
511        }
512    }
513
514    /// Resolve the HMAC signing secret at REQUEST time (audit_2 S3). Prefers a
515    /// secret injected onto the state (tests); otherwise reads the ambient
516    /// `secret_key` from settings — which, by the time a request is served, is
517    /// always populated. Returns `None` in plain (unsigned) mode or when no
518    /// non-empty secret is configured (then CSRF degrades to double-submit).
519    fn resolve_secret(&self) -> Option<String> {
520        if !self.signed {
521            return None;
522        }
523        self.secret.clone().or_else(|| {
524            umbral::settings::get_opt()
525                .map(|s| s.secret_key.trim().to_string())
526                .filter(|s| !s.is_empty())
527        })
528    }
529
530    /// True when `path` falls under a configured CSRF-exempt prefix.
531    fn is_exempt(&self, path: &str) -> bool {
532        self.exempt_paths.iter().any(|prefix| {
533            let prefix = prefix.trim_end_matches('/');
534            path == prefix || path.starts_with(&format!("{prefix}/"))
535        })
536    }
537
538    /// The session value to fold into the signature, or `None` when session
539    /// binding isn't configured.
540    fn session_bind<'a>(&self, session_value: Option<&'a str>) -> Option<&'a str> {
541        if self.session_cookie.is_some() {
542            session_value
543        } else {
544            None
545        }
546    }
547
548    /// True when `token` may keep serving as this browser's CSRF cookie.
549    /// Plain mode accepts any non-empty token. Signed mode (with a
550    /// resolvable secret) requires a structurally valid `<raw>.<sig>` —
551    /// anything else (typically a cookie minted before `signed_csrf`
552    /// was enabled) triggers a rotation re-mint by the caller.
553    fn token_acceptable(&self, token: &str, session_value: Option<&str>) -> bool {
554        if token.is_empty() {
555            return false;
556        }
557        if !self.signed {
558            return true;
559        }
560        let Some(secret) = self.resolve_secret() else {
561            return true; // signing requested but no secret resolved: degrade
562        };
563        let Some((raw, sig)) = token.rsplit_once('.') else {
564            return false;
565        };
566        tokens_match(sig, &sign(&secret, raw, self.session_bind(session_value)))
567    }
568}
569
570/// Generate a fresh 32-byte token, hex-encoded. Public so tests and downstream
571/// code that mints tokens directly (e.g. server-rendered forms) share the same
572/// shape. Raw (unsigned) — the signed wrapper is applied by the middleware.
573pub fn generate_token() -> String {
574    let mut bytes = [0u8; 32];
575    getrandom::getrandom(&mut bytes).expect("getrandom failed");
576    hex::encode(bytes)
577}
578
579/// HMAC-SHA256 over `raw` (and the session value, when bound), keyed by the app
580/// secret, hex-encoded.
581///
582/// `secret` must never be empty in production. Boot (`on_ready`) already
583/// rejects an empty `SECRET_KEY` before this path is reachable in a real
584/// deployment; the assert below catches the bug in debug/test builds if
585/// that guard is somehow bypassed.
586fn sign(secret: &str, raw: &str, session: Option<&str>) -> String {
587    debug_assert!(
588        !secret.is_empty(),
589        "sign() called with an empty secret — CSRF tokens are trivially forgeable; \
590         on_ready should have rejected boot already"
591    );
592    use hmac::{Hmac, Mac};
593    use sha2::Sha256;
594    let mut mac =
595        <Hmac<Sha256>>::new_from_slice(secret.as_bytes()).expect("HMAC accepts any key length");
596    mac.update(raw.as_bytes());
597    if let Some(s) = session {
598        mac.update(b".");
599        mac.update(s.as_bytes());
600    }
601    hex::encode(mac.finalize().into_bytes())
602}
603
604/// Mint a token for the response cookie — signed when configured and a secret
605/// is available, raw otherwise.
606fn mint_token(state: &CsrfState, session_value: Option<&str>) -> String {
607    let raw = generate_token();
608    if state.signed {
609        if let Some(secret) = state.resolve_secret() {
610            let sig = sign(&secret, &raw, state.session_bind(session_value));
611            return format!("{raw}.{sig}");
612        }
613    }
614    raw
615}
616
617/// Validate a submitted token against the cookie token. Always requires the
618/// double-submit equality; additionally verifies the HMAC signature when
619/// `signed` is on and a secret is available.
620fn csrf_valid(
621    state: &CsrfState,
622    cookie_token: &str,
623    submitted: &str,
624    session_value: Option<&str>,
625) -> bool {
626    if !tokens_match(cookie_token, submitted) {
627        return false;
628    }
629    if !state.signed {
630        return true;
631    }
632    let Some(secret) = state.resolve_secret() else {
633        // Signing requested but no secret resolved (e.g. before App::build()):
634        // fall back to plain double-submit rather than locking writes out.
635        return true;
636    };
637    let Some((raw, sig)) = cookie_token.rsplit_once('.') else {
638        // Signed mode requires a signature; an unsigned token can't be trusted.
639        return false;
640    };
641    let expected = sign(&secret, raw, state.session_bind(session_value));
642    tokens_match(sig, &expected)
643}
644
645/// Pull the value of a named cookie out of a `Cookie` header. v0 shape: linear
646/// scan, no quoting.
647fn cookie_value<'a>(header: &'a str, name: &str) -> Option<&'a str> {
648    for part in header.split(';') {
649        let part = part.trim();
650        if let Some((k, v)) = part.split_once('=') {
651            if k == name {
652                return Some(v);
653            }
654        }
655    }
656    None
657}
658
659fn is_safe_method(method: &Method) -> bool {
660    matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS)
661}
662
663/// `Cache-Control` for a response that belongs to exactly one person.
664///
665/// `private` bars shared caches (CDN, corporate proxy) from storing it at all;
666/// `no-store` additionally bars the browser's own disk and back/forward caches,
667/// which is what stops a logged-out user pressing Back into a rendered admin
668/// page. Both, because they address different caches.
669const PRIVATE_CACHE_CONTROL: &str = "no-store, private";
670
671/// Return `true` when the request is tied to one identity, and its response
672/// therefore must not be stored by a cache shared with anyone else.
673///
674/// Three signals, matching the personalisation predicate `umbral-cache`'s
675/// `cache_page` uses to bypass its own store (`request_is_personalised`):
676///
677/// - a `umbral_session` cookie (the canonical `umbral_sessions::COOKIE_NAME`),
678/// - an `Authorization` header (bearer / basic / API token),
679/// - a `Proxy-Authorization` header.
680///
681/// Deliberately NOT a signal: the `umbral_csrf_token` cookie. Every first-time
682/// anonymous visitor is minted one on their first safe request, so keying on it
683/// would mark the entire public site `no-store`.
684fn request_is_personalised(headers: &http::HeaderMap) -> bool {
685    if headers.contains_key(AUTHORIZATION) || headers.contains_key(PROXY_AUTHORIZATION) {
686        return true;
687    }
688    headers
689        .get_all(COOKIE)
690        .iter()
691        .filter_map(|v| v.to_str().ok())
692        .any(|h| cookie_value(h, SESSION_COOKIE).is_some())
693}
694
695/// Attach [`PRIVATE_CACHE_CONTROL`] to responses for personalised requests.
696///
697/// `if_not_present` semantics: a handler that already declared its own caching
698/// policy keeps it, so an authenticated request for a fingerprinted static asset
699/// still serves `public, max-age=…`.
700async fn private_cache_middleware(req: Request, next: Next) -> Response {
701    let personalised = request_is_personalised(req.headers());
702    let mut resp = next.run(req).await;
703    if personalised {
704        resp.headers_mut()
705            .entry(http::header::CACHE_CONTROL)
706            .or_insert_with(|| HeaderValue::from_static(PRIVATE_CACHE_CONTROL));
707    }
708    resp
709}
710
711async fn csrf_middleware(
712    State(state): State<CsrfState>,
713    req: Request,
714    next: Next,
715) -> Result<Response, Infallible> {
716    let method = req.method().clone();
717
718    // Exempt paths (e.g. a token-authenticated `/api`) bypass CSRF entirely —
719    // they carry no session cookie, so the double-submit check doesn't apply.
720    if state.is_exempt(req.uri().path()) {
721        return Ok(next.run(req).await);
722    }
723
724    let cookie_header = req
725        .headers()
726        .get(COOKIE)
727        .and_then(|h| h.to_str().ok())
728        .map(str::to_string);
729    let cookie_token = cookie_header
730        .as_deref()
731        .and_then(|h| cookie_value(h, CSRF_COOKIE).map(str::to_string));
732    let session_value = state.session_cookie.as_deref().and_then(|name| {
733        cookie_header
734            .as_deref()
735            .and_then(|h| cookie_value(h, name).map(str::to_string))
736    });
737
738    if is_safe_method(&method) {
739        // The middleware is the only mint (docs/decisions/
740        // 2026-06-10-automatic-csrf.md): mint BEFORE the handler runs so
741        // first-visit renders already have a token in scope, and rotate a
742        // cookie token that can't pass signed-mode validation so flipping
743        // `signed_csrf` on doesn't 403 browsers holding old cookies.
744        let (token, minted) = match cookie_token {
745            Some(t) if state.token_acceptable(&t, session_value.as_deref()) => (t, false),
746            _ => (mint_token(&state, session_value.as_deref()), true),
747        };
748        let mut response =
749            umbral::templates::with_current_csrf(Some(token.clone()), next.run(req)).await;
750        if minted {
751            let mut cookie = format!("{CSRF_COOKIE}={token}; Path=/; SameSite=Lax");
752            if state.secure {
753                cookie.push_str("; Secure");
754            }
755            if let Ok(v) = HeaderValue::from_str(&cookie) {
756                // `append`, not `insert` — `insert` would wipe any cookie
757                // the handler set on this response (e.g. the session).
758                response.headers_mut().append(SET_COOKIE, v);
759            }
760        }
761        return Ok(response);
762    }
763
764    // Write methods: cookie and (header OR form field) must validate.
765    // On success the token is scoped around the handler so a
766    // validation-error re-render still carries it into the form.
767    let header_token = req
768        .headers()
769        .get(CSRF_HEADER)
770        .and_then(|h| h.to_str().ok())
771        .map(str::to_string);
772
773    if let Some(c) = cookie_token.as_ref() {
774        if let Some(h) = header_token.as_ref() {
775            if csrf_valid(&state, c, h, session_value.as_deref()) {
776                let token = c.clone();
777                return Ok(umbral::templates::with_current_csrf(Some(token), next.run(req)).await);
778            }
779        }
780        // Form-field path: peek the urlencoded body, then rebuild the request.
781        let content_type = req
782            .headers()
783            .get(http::header::CONTENT_TYPE)
784            .and_then(|v| v.to_str().ok())
785            .unwrap_or("")
786            .to_string();
787        if content_type.starts_with("application/x-www-form-urlencoded") {
788            let cookie_owned = c.clone();
789            let (parts, body) = req.into_parts();
790            let bytes = match axum::body::to_bytes(body, MAX_FORM_BODY).await {
791                Ok(b) => b,
792                Err(_) => return Ok(forbidden()),
793            };
794            if let Some(s) = form_field_token(&bytes) {
795                if csrf_valid(&state, &cookie_owned, &s, session_value.as_deref()) {
796                    let req = Request::from_parts(parts, Body::from(bytes));
797                    return Ok(umbral::templates::with_current_csrf(
798                        Some(cookie_owned),
799                        next.run(req),
800                    )
801                    .await);
802                }
803            }
804        }
805    }
806
807    Ok(forbidden())
808}
809
810/// Strip the `Server` response header (used when `hide_server_header` is set
811/// and no explicit value was given).
812async fn strip_server_header(req: Request, next: Next) -> Result<Response, Infallible> {
813    let mut response = next.run(req).await;
814    response.headers_mut().remove(SERVER);
815    Ok(response)
816}
817
818fn forbidden() -> Response {
819    let body = Body::from("CSRF verification failed");
820    Response::builder()
821        .status(StatusCode::FORBIDDEN)
822        .body(body)
823        .expect("static response")
824}
825
826/// Scan a urlencoded form body for any of the accepted CSRF field names.
827fn form_field_token(body: &[u8]) -> Option<String> {
828    let s = std::str::from_utf8(body).ok()?;
829    for part in s.split('&') {
830        let mut iter = part.splitn(2, '=');
831        let key = iter.next()?;
832        let val = iter.next().unwrap_or("");
833        if CSRF_FORM_FIELDS.contains(&key) {
834            // Tokens are hex (signed tokens add a `.` + hex sig — still no
835            // urlencoded-special chars), so `+`→space is the only decode
836            // needed for the common case.
837            return Some(val.replace('+', " "));
838        }
839    }
840    None
841}
842
843/// Read the current CSRF token from the request's cookie header. Public so
844/// handlers that render HTML forms can embed it as a hidden `csrf_token` input.
845pub fn current_csrf_token(headers: &http::HeaderMap) -> Option<String> {
846    headers
847        .get(COOKIE)
848        .and_then(|h| h.to_str().ok())
849        .and_then(|h| cookie_value(h, CSRF_COOKIE).map(str::to_string))
850}
851
852/// Constant-time string equality. Short-circuit `==` on `String` is a timing
853/// side-channel; `ct_eq` closes it. Per OWASP's "Use Constant-Time String
854/// Comparison" rule for security tokens. Public so other token consumers
855/// (e.g. the admin's SecurityPlugin-less login fallback) compare the same way.
856pub fn tokens_match(a: &str, b: &str) -> bool {
857    use subtle::ConstantTimeEq;
858    a.as_bytes().ct_eq(b.as_bytes()).into()
859}
860
861/// Validate that `secret_key` is non-empty when signed CSRF is enabled.
862///
863/// Called from [`SecurityPlugin::on_ready`]. Extracted as a free function so
864/// integration tests can exercise it with an explicit [`umbral::Settings`]
865/// without needing a live `App::build()` to populate the ambient
866/// `SETTINGS` OnceLock (which is `pub(crate)` and unreachable from plugin
867/// tests).
868///
869/// Behaviour when `settings` is `None` (i.e. `get_opt()` returned nothing,
870/// common in tests that bypass `App::build()`): treated as non-prod, no
871/// error.
872fn check_secret_key(
873    settings: Option<&umbral::Settings>,
874    config: &SecurityConfig,
875) -> Result<(), umbral::plugin::PluginError> {
876    // Only relevant when signed CSRF is active; plain double-submit doesn't
877    // use the secret at all.
878    if !config.csrf || !config.signed_csrf {
879        return Ok(());
880    }
881
882    let Some(s) = settings else {
883        // No settings available — running outside App::build() (e.g. tests).
884        // Can't determine environment or secret; skip.
885        return Ok(());
886    };
887
888    if s.secret_key.trim().is_empty() {
889        match s.environment {
890            Environment::Dev | Environment::Test => {
891                tracing::warn!(
892                    "SecurityPlugin: SECRET_KEY is empty — CSRF tokens are signed with an \
893                     empty HMAC key and are trivially forgeable. Set `secret_key` in \
894                     umbral.toml or the UMBRAL_SECRET_KEY environment variable before \
895                     deploying."
896                );
897            }
898            Environment::Prod => {
899                return Err(
900                    "SecurityPlugin: SECRET_KEY must not be empty in production. \
901                     An empty key makes CSRF tokens trivially forgeable. \
902                     Set `secret_key` in umbral.toml or via UMBRAL_SECRET_KEY."
903                        .into(),
904                );
905            }
906        }
907    }
908
909    Ok(())
910}
911
912/// Test-only constructors. `#[doc(hidden)]` — NOT a stable API; integration
913/// tests need a CSRF-wrapped router without `App::build()`-resolved settings.
914#[doc(hidden)]
915pub mod test_support {
916    use super::*;
917
918    /// Wrap `router` with the CSRF middleware using an explicit state,
919    /// bypassing settings resolution.
920    pub fn wrap_with_csrf(
921        router: axum::Router,
922        signed: bool,
923        secret: Option<String>,
924    ) -> axum::Router {
925        let state = CsrfState {
926            secure: false,
927            signed,
928            secret,
929            session_cookie: None,
930            exempt_paths: Vec::new(),
931        };
932        router.layer(middleware::from_fn_with_state(state, csrf_middleware))
933    }
934
935    /// Exercise [`check_secret_key`] directly with an explicit [`umbral::Settings`],
936    /// bypassing the ambient `SETTINGS` OnceLock (which is `pub(crate)` and
937    /// unreachable from plugin tests).
938    pub fn validate_secret_key(
939        settings: &umbral::Settings,
940        config: &SecurityConfig,
941    ) -> Result<(), umbral::plugin::PluginError> {
942        check_secret_key(Some(settings), config)
943    }
944}
945
946#[cfg(test)]
947mod tests {
948    use super::*;
949
950    fn signed_state(secret: &str, session_cookie: Option<&str>) -> CsrfState {
951        CsrfState {
952            secure: false,
953            signed: true,
954            secret: Some(secret.to_string()),
955            session_cookie: session_cookie.map(str::to_string),
956            exempt_paths: Vec::new(),
957        }
958    }
959
960    #[test]
961    fn signing_is_deterministic_and_key_dependent() {
962        assert_eq!(sign("k", "abc", None), sign("k", "abc", None));
963        assert_ne!(sign("k1", "abc", None), sign("k2", "abc", None));
964        assert_ne!(sign("k", "abc", None), sign("k", "abc", Some("sess")));
965    }
966
967    /// audit_2 S3 — `from_config` must NOT capture the secret at build time
968    /// (that pinned plain double-submit if settings weren't ready at
969    /// `wrap_router`); the secret is resolved per request instead.
970    #[test]
971    fn from_config_does_not_capture_the_secret_at_build_time() {
972        let cfg = SecurityConfig {
973            csrf: true,
974            signed_csrf: true,
975            ..Default::default()
976        };
977        let state = CsrfState::from_config(&cfg);
978        assert!(state.signed, "signed mode still requested");
979        assert!(
980            state.secret.is_none(),
981            "the secret must not be captured at build time — it's resolved per request"
982        );
983    }
984
985    /// `resolve_secret` prefers an injected secret, and returns `None` for
986    /// unsigned mode. (The ambient-settings fallback is exercised end-to-end in
987    /// a real request, where settings are always populated.)
988    #[test]
989    fn resolve_secret_precedence() {
990        let injected = signed_state("captured", None);
991        assert_eq!(injected.resolve_secret().as_deref(), Some("captured"));
992
993        let unsigned = CsrfState {
994            secure: false,
995            signed: false,
996            secret: Some("ignored".to_string()),
997            session_cookie: None,
998            exempt_paths: Vec::new(),
999        };
1000        assert_eq!(
1001            unsigned.resolve_secret(),
1002            None,
1003            "unsigned mode never resolves a secret"
1004        );
1005    }
1006
1007    #[test]
1008    fn signed_token_round_trips_and_rejects_forgery() {
1009        let st = signed_state("app-secret", None);
1010        let token = mint_token(&st, None);
1011        // Minted token is `<raw>.<sig>` and validates as a double-submit pair.
1012        assert!(token.contains('.'));
1013        assert!(csrf_valid(&st, &token, &token, None));
1014        // An unsigned token (attacker-planted, no valid signature) is rejected
1015        // even though it double-submits against itself.
1016        let forged = generate_token();
1017        assert!(!csrf_valid(&st, &forged, &forged, None));
1018        // A token signed under a different key is rejected.
1019        let other = signed_state("different-secret", None);
1020        let other_token = mint_token(&other, None);
1021        assert!(!csrf_valid(&st, &other_token, &other_token, None));
1022    }
1023
1024    #[test]
1025    fn session_binding_ties_token_to_session_value() {
1026        let st = signed_state("app-secret", Some("umbral_session"));
1027        let token = mint_token(&st, Some("sess-A"));
1028        assert!(csrf_valid(&st, &token, &token, Some("sess-A")));
1029        // Same token under a different session value no longer validates.
1030        assert!(!csrf_valid(&st, &token, &token, Some("sess-B")));
1031    }
1032
1033    #[test]
1034    fn unsigned_mode_is_plain_double_submit() {
1035        let st = CsrfState {
1036            secure: false,
1037            signed: false,
1038            secret: None,
1039            session_cookie: None,
1040            exempt_paths: Vec::new(),
1041        };
1042        let tok = generate_token();
1043        assert!(csrf_valid(&st, &tok, &tok, None));
1044        assert!(!csrf_valid(&st, &tok, "different", None));
1045    }
1046
1047    #[test]
1048    fn exempt_path_matching_is_prefix_based() {
1049        let st = CsrfState {
1050            secure: false,
1051            signed: false,
1052            secret: None,
1053            session_cookie: None,
1054            exempt_paths: vec!["/api".to_string()],
1055        };
1056        assert!(st.is_exempt("/api"));
1057        assert!(st.is_exempt("/api/customer/1"));
1058        assert!(!st.is_exempt("/admin"));
1059        assert!(!st.is_exempt("/contact"));
1060    }
1061
1062    /// `/api` exempt must NOT bleed into `/api-internal`, `/apixyz`, etc.
1063    /// The boundary check requires the prefix to be followed by `/` (sub-path)
1064    /// or be an exact match — a bare `starts_with("/api")` would incorrectly
1065    /// exempt those sibling routes.
1066    #[test]
1067    fn csrf_exempt_boundary_stops_at_path_segment() {
1068        let st = CsrfState {
1069            secure: false,
1070            signed: false,
1071            secret: None,
1072            session_cookie: None,
1073            exempt_paths: vec!["/api".to_string()],
1074        };
1075        // Exact match and sub-paths ARE exempt.
1076        assert!(st.is_exempt("/api"), "/api exact must be exempt");
1077        assert!(
1078            st.is_exempt("/api/users"),
1079            "/api/users sub-path must be exempt"
1080        );
1081        assert!(
1082            st.is_exempt("/api/v2/resource"),
1083            "/api/v2/resource must be exempt"
1084        );
1085        // Paths that merely START WITH the string but aren't segment-separated
1086        // must NOT be exempt — that would be a CSRF-bypass on unintended routes.
1087        assert!(
1088            !st.is_exempt("/api-internal"),
1089            "/api-internal must NOT be exempt when /api is configured"
1090        );
1091        assert!(
1092            !st.is_exempt("/apixyz"),
1093            "/apixyz must NOT be exempt when /api is configured"
1094        );
1095        assert!(
1096            !st.is_exempt("/api2"),
1097            "/api2 must NOT be exempt when /api is configured"
1098        );
1099    }
1100
1101    #[test]
1102    fn hsts_value_reflects_flags() {
1103        let cfg = SecurityConfig {
1104            hsts_max_age: 100,
1105            hsts_include_subdomains: true,
1106            hsts_preload: true,
1107            ..Default::default()
1108        };
1109        assert_eq!(cfg.hsts_value(), "max-age=100; includeSubDomains; preload");
1110        let bare = SecurityConfig {
1111            hsts_max_age: 100,
1112            hsts_include_subdomains: false,
1113            hsts_preload: false,
1114            ..Default::default()
1115        };
1116        assert_eq!(bare.hsts_value(), "max-age=100");
1117    }
1118}