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::{AUTHORIZATION, COOKIE, HeaderName, HeaderValue, SERVER, SET_COOKIE};
112use http::{Method, StatusCode};
113use tower_http::limit::RequestBodyLimitLayer;
114use tower_http::sensitive_headers::SetSensitiveHeadersLayer;
115use tower_http::set_header::SetResponseHeaderLayer;
116use umbral::prelude::*;
117
118const CSRF_COOKIE: &str = "umbral_csrf_token";
119const CSRF_HEADER: &str = "x-csrf-token";
120/// Form field name that carries the CSRF token for HTML `<form>` submissions.
121/// Two shapes are accepted — `csrf_token` and `__csrf` — so existing form code
122/// on either convention works without migration. The header path stays the
123/// canonical one for JS clients.
124const CSRF_FORM_FIELDS: &[&str] = &["csrf_token", "__csrf"];
125/// Hard cap on the buffered body size when we peek at form data to extract the
126/// CSRF field. 1 MiB is well above any realistic urlencoded form.
127const MAX_FORM_BODY: usize = 1024 * 1024;
128
129/// Declarative security configuration. Build from [`Default`] (secure,
130/// dev-safe) and override the fields you need — see the crate docs for the
131/// rationale behind each default.
132#[derive(Debug, Clone)]
133pub struct SecurityConfig {
134 // ---- CSRF ----
135 /// Run the CSRF middleware. Default `true`.
136 pub csrf: bool,
137 /// Force the `Secure` flag on the CSRF cookie. Default `false`; `Secure` is
138 /// added automatically under `Environment::Prod` regardless, so this only
139 /// matters for forcing it on in a non-prod HTTPS setup.
140 pub csrf_cookie_secure: bool,
141 /// Sign the CSRF token with the app `secret_key` (HMAC-SHA256). Default
142 /// `true` — the middleware is the only mint, so every token carries a
143 /// signature; stale unsigned cookies rotate automatically on the next
144 /// safe request. Set `false` for plain double-submit.
145 pub signed_csrf: bool,
146 /// When `signed_csrf` is on, also bind the token to this cookie's value
147 /// (typically the session cookie). Default `None`.
148 pub session_bind_cookie: Option<String>,
149 /// Request-path prefixes exempt from CSRF (CSRF-exempt paths).
150 /// A token-authenticated REST API carries no session cookie, so a
151 /// bearer-auth `POST /api/...` would otherwise 403; exempt `"/api"` to
152 /// keep it working. Matched as a path prefix. Default empty.
153 pub csrf_exempt_paths: Vec<String>,
154
155 // ---- Response headers (None / false = header omitted) ----
156 /// `X-Content-Type-Options: nosniff`. Default `true`.
157 pub content_type_options: bool,
158 /// `X-Frame-Options`. Default `Some("DENY")`.
159 pub frame_options: Option<String>,
160 /// `Referrer-Policy`. Default `Some("strict-origin-when-cross-origin")`.
161 pub referrer_policy: Option<String>,
162 /// `X-XSS-Protection`. Default `Some("0")` — disables the buggy legacy
163 /// filter rather than enabling it (current OWASP guidance).
164 pub xss_protection: Option<String>,
165 /// Emit `Strict-Transport-Security`. Default `false` (dev-safe). Value is
166 /// built from the `hsts_*` fields.
167 pub hsts: bool,
168 /// HSTS `max-age` in seconds. Default one year.
169 pub hsts_max_age: u64,
170 /// Add `; includeSubDomains` to HSTS. Default `true`.
171 pub hsts_include_subdomains: bool,
172 /// Add `; preload` to HSTS. Default `false`.
173 pub hsts_preload: bool,
174 /// `Content-Security-Policy`. Default `None` — a wrong CSP breaks apps, so
175 /// it's opt-in.
176 pub content_security_policy: Option<String>,
177 /// `Permissions-Policy`. Default `None`.
178 pub permissions_policy: Option<String>,
179 /// `Cross-Origin-Opener-Policy`. Default `Some("same-origin")`.
180 /// Set `None` to omit, e.g. apps relying on cross-origin
181 /// popups (some OAuth flows).
182 pub cross_origin_opener_policy: Option<String>,
183 /// `Cross-Origin-Resource-Policy` (e.g. `"same-origin"`). Default `None`.
184 pub cross_origin_resource_policy: Option<String>,
185 /// `Cross-Origin-Embedder-Policy` (e.g. `"require-corp"`). Default `None`.
186 pub cross_origin_embedder_policy: Option<String>,
187
188 // ---- Server identity ----
189 /// Set the `Server` response header. Default `Some("umbral")` — a bare
190 /// product name (no version, so no info disclosure), the way many app
191 /// servers advertise one. Set `None` to omit. Prefer no version.
192 pub server_header: Option<String>,
193 /// Strip any `Server` header the stack set. Default `false`. Ignored when
194 /// `server_header` is `Some` (the set wins) — to strip, also set
195 /// `server_header: None`.
196 pub hide_server_header: bool,
197
198 // ---- axum / tower-http knobs ----
199 /// Cap request body size in bytes (tower-http `RequestBodyLimitLayer`).
200 /// Default `None` (axum's own default applies).
201 pub request_body_limit: Option<usize>,
202 /// Mark `authorization` / `cookie` / `set-cookie` sensitive so tracing
203 /// redacts them. Default `true`.
204 pub redact_sensitive_headers: bool,
205}
206
207impl Default for SecurityConfig {
208 fn default() -> Self {
209 Self {
210 csrf: true,
211 csrf_cookie_secure: false,
212 signed_csrf: true,
213 session_bind_cookie: None,
214 csrf_exempt_paths: Vec::new(),
215 content_type_options: true,
216 frame_options: Some("DENY".to_string()),
217 referrer_policy: Some("strict-origin-when-cross-origin".to_string()),
218 xss_protection: Some("0".to_string()),
219 hsts: false,
220 hsts_max_age: 31_536_000,
221 hsts_include_subdomains: true,
222 hsts_preload: false,
223 content_security_policy: None,
224 permissions_policy: None,
225 // On by default (same-origin). Isolates the browsing
226 // context group; only affects apps that rely on cross-origin popups.
227 cross_origin_opener_policy: Some("same-origin".to_string()),
228 cross_origin_resource_policy: None,
229 cross_origin_embedder_policy: None,
230 // Advertise the framework (no version, no info disclosure). Many app
231 // servers emit a `Server` header. Set `None` to omit
232 // or pair `None` + `hide_server_header` to strip an upstream one.
233 server_header: Some("umbral".to_string()),
234 hide_server_header: false,
235 request_body_limit: None,
236 redact_sensitive_headers: true,
237 }
238 }
239}
240
241impl SecurityConfig {
242 fn hsts_value(&self) -> String {
243 let mut v = format!("max-age={}", self.hsts_max_age);
244 if self.hsts_include_subdomains {
245 v.push_str("; includeSubDomains");
246 }
247 if self.hsts_preload {
248 v.push_str("; preload");
249 }
250 v
251 }
252}
253
254/// CSRF + security-headers plugin. Configure via [`SecurityConfig`].
255#[derive(Debug, Clone, Default)]
256pub struct SecurityPlugin {
257 config: SecurityConfig,
258}
259
260impl SecurityPlugin {
261 /// Secure, dev-safe defaults (see [`SecurityConfig`]).
262 pub fn new() -> Self {
263 Self::default()
264 }
265
266 /// Construct from an explicit config — the preferred entry point.
267 pub fn with_config(config: SecurityConfig) -> Self {
268 Self { config }
269 }
270
271 /// Borrow the active config.
272 pub fn config(&self) -> &SecurityConfig {
273 &self.config
274 }
275
276 /// One-flag convenience for `SecurityConfig::hsts`. Equivalent to
277 /// `with_config(SecurityConfig { hsts, ..Default::default() })`.
278 pub fn with_hsts(mut self, hsts: bool) -> Self {
279 self.config.hsts = hsts;
280 self
281 }
282}
283
284impl Plugin for SecurityPlugin {
285 fn name(&self) -> &'static str {
286 "security"
287 }
288
289 fn wrap_router(&self, router: Router) -> Router {
290 let cfg = &self.config;
291 let mut router = router;
292
293 // CSRF middleware (innermost of our additions).
294 if cfg.csrf {
295 let state = CsrfState::from_config(cfg);
296 router = router.layer(middleware::from_fn_with_state(state, csrf_middleware));
297 }
298
299 // Response-header setters. Order among them is irrelevant.
300 if cfg.content_type_options {
301 router = set_header(
302 router,
303 "x-content-type-options",
304 Some("nosniff".to_string()),
305 );
306 }
307 router = set_header(router, "x-frame-options", cfg.frame_options.clone());
308 router = set_header(router, "referrer-policy", cfg.referrer_policy.clone());
309 router = set_header(router, "x-xss-protection", cfg.xss_protection.clone());
310 if cfg.hsts {
311 router = set_header(router, "strict-transport-security", Some(cfg.hsts_value()));
312 }
313 router = set_header(
314 router,
315 "content-security-policy",
316 cfg.content_security_policy.clone(),
317 );
318 router = set_header(router, "permissions-policy", cfg.permissions_policy.clone());
319 router = set_header(
320 router,
321 "cross-origin-opener-policy",
322 cfg.cross_origin_opener_policy.clone(),
323 );
324 router = set_header(
325 router,
326 "cross-origin-resource-policy",
327 cfg.cross_origin_resource_policy.clone(),
328 );
329 router = set_header(
330 router,
331 "cross-origin-embedder-policy",
332 cfg.cross_origin_embedder_policy.clone(),
333 );
334
335 // Server identity: an explicit value overrides; otherwise optionally strip.
336 if let Some(v) = cfg.server_header.as_deref() {
337 if let Ok(hv) = HeaderValue::from_str(v) {
338 router = router.layer(SetResponseHeaderLayer::overriding(SERVER, hv));
339 }
340 } else if cfg.hide_server_header {
341 router = router.layer(middleware::from_fn(strip_server_header));
342 }
343
344 // tower-http knobs (outermost so they wrap everything above).
345 if cfg.redact_sensitive_headers {
346 router = router.layer(SetSensitiveHeadersLayer::new([
347 AUTHORIZATION,
348 COOKIE,
349 SET_COOKIE,
350 ]));
351 }
352 if let Some(limit) = cfg.request_body_limit {
353 router = router.layer(RequestBodyLimitLayer::new(limit));
354 }
355
356 router
357 }
358
359 fn on_ready(&self, _ctx: &umbral::plugin::AppContext) -> Result<(), umbral::plugin::PluginError> {
360 let settings = umbral::settings::get_opt();
361
362 // Boot nudge: HSTS and CSP are opt-in (safe defaults for dev), but
363 // a Prod deployment shipping neither is a real exposure — SSL
364 // stripping with no HSTS, XSS with no CSP backstop. Warn loudly so
365 // the gap is visible at startup rather than discovered in an audit.
366 let is_prod = settings
367 .map(|s| matches!(s.environment, Environment::Prod))
368 .unwrap_or(false);
369 if is_prod {
370 if !self.config.hsts {
371 tracing::warn!(
372 "SecurityPlugin: HSTS is disabled in Environment::Prod — responses ship \
373 no Strict-Transport-Security header, leaving clients open to SSL \
374 stripping. Enable with `.with_hsts(true)`."
375 );
376 }
377 if self.config.content_security_policy.is_none() {
378 tracing::warn!(
379 "SecurityPlugin: no Content-Security-Policy set in Environment::Prod — \
380 XSS has no CSP backstop. Set `content_security_policy` in SecurityConfig."
381 );
382 }
383 }
384
385 check_secret_key(settings, &self.config)?;
386
387 Ok(())
388 }
389}
390
391/// Add a `SetResponseHeaderLayer::if_not_present` for `name` when `value` is a
392/// valid header value; otherwise return the router untouched.
393fn set_header(router: Router, name: &'static str, value: Option<String>) -> Router {
394 match value.as_deref().and_then(|v| HeaderValue::from_str(v).ok()) {
395 Some(hv) => router.layer(SetResponseHeaderLayer::if_not_present(
396 HeaderName::from_static(name),
397 hv,
398 )),
399 None => router,
400 }
401}
402
403/// Per-request CSRF state captured at `wrap_router` time. The `secret` is read
404/// once from settings (absent in tests / before `App::build()` — signing then
405/// degrades to plain double-submit rather than panicking).
406#[derive(Clone)]
407struct CsrfState {
408 secure: bool,
409 signed: bool,
410 secret: Option<String>,
411 session_cookie: Option<String>,
412 exempt_paths: Vec<String>,
413}
414
415impl CsrfState {
416 fn from_config(cfg: &SecurityConfig) -> Self {
417 let settings = umbral::settings::get_opt();
418 let is_prod = settings
419 .map(|s| matches!(s.environment, Environment::Prod))
420 .unwrap_or(false);
421 let secret = if cfg.signed_csrf {
422 settings
423 .map(|s| s.secret_key.trim().to_string())
424 .filter(|s| !s.is_empty())
425 } else {
426 None
427 };
428 Self {
429 secure: cfg.csrf_cookie_secure || is_prod,
430 signed: cfg.signed_csrf,
431 secret,
432 session_cookie: cfg.session_bind_cookie.clone(),
433 exempt_paths: cfg.csrf_exempt_paths.clone(),
434 }
435 }
436
437 /// True when `path` falls under a configured CSRF-exempt prefix.
438 fn is_exempt(&self, path: &str) -> bool {
439 self.exempt_paths.iter().any(|prefix| {
440 let prefix = prefix.trim_end_matches('/');
441 path == prefix || path.starts_with(&format!("{prefix}/"))
442 })
443 }
444
445 /// The session value to fold into the signature, or `None` when session
446 /// binding isn't configured.
447 fn session_bind<'a>(&self, session_value: Option<&'a str>) -> Option<&'a str> {
448 if self.session_cookie.is_some() {
449 session_value
450 } else {
451 None
452 }
453 }
454
455 /// True when `token` may keep serving as this browser's CSRF cookie.
456 /// Plain mode accepts any non-empty token. Signed mode (with a
457 /// resolvable secret) requires a structurally valid `<raw>.<sig>` —
458 /// anything else (typically a cookie minted before `signed_csrf`
459 /// was enabled) triggers a rotation re-mint by the caller.
460 fn token_acceptable(&self, token: &str, session_value: Option<&str>) -> bool {
461 if token.is_empty() {
462 return false;
463 }
464 if !self.signed {
465 return true;
466 }
467 let Some(secret) = self.secret.as_deref() else {
468 return true; // signing requested but no secret resolved: degrade
469 };
470 let Some((raw, sig)) = token.rsplit_once('.') else {
471 return false;
472 };
473 tokens_match(sig, &sign(secret, raw, self.session_bind(session_value)))
474 }
475}
476
477/// Generate a fresh 32-byte token, hex-encoded. Public so tests and downstream
478/// code that mints tokens directly (e.g. server-rendered forms) share the same
479/// shape. Raw (unsigned) — the signed wrapper is applied by the middleware.
480pub fn generate_token() -> String {
481 let mut bytes = [0u8; 32];
482 getrandom::getrandom(&mut bytes).expect("getrandom failed");
483 hex::encode(bytes)
484}
485
486/// HMAC-SHA256 over `raw` (and the session value, when bound), keyed by the app
487/// secret, hex-encoded.
488///
489/// `secret` must never be empty in production. Boot (`on_ready`) already
490/// rejects an empty `SECRET_KEY` before this path is reachable in a real
491/// deployment; the assert below catches the bug in debug/test builds if
492/// that guard is somehow bypassed.
493fn sign(secret: &str, raw: &str, session: Option<&str>) -> String {
494 debug_assert!(
495 !secret.is_empty(),
496 "sign() called with an empty secret — CSRF tokens are trivially forgeable; \
497 on_ready should have rejected boot already"
498 );
499 use hmac::{Hmac, Mac};
500 use sha2::Sha256;
501 let mut mac =
502 <Hmac<Sha256>>::new_from_slice(secret.as_bytes()).expect("HMAC accepts any key length");
503 mac.update(raw.as_bytes());
504 if let Some(s) = session {
505 mac.update(b".");
506 mac.update(s.as_bytes());
507 }
508 hex::encode(mac.finalize().into_bytes())
509}
510
511/// Mint a token for the response cookie — signed when configured and a secret
512/// is available, raw otherwise.
513fn mint_token(state: &CsrfState, session_value: Option<&str>) -> String {
514 let raw = generate_token();
515 if state.signed {
516 if let Some(secret) = state.secret.as_deref() {
517 let sig = sign(secret, &raw, state.session_bind(session_value));
518 return format!("{raw}.{sig}");
519 }
520 }
521 raw
522}
523
524/// Validate a submitted token against the cookie token. Always requires the
525/// double-submit equality; additionally verifies the HMAC signature when
526/// `signed` is on and a secret is available.
527fn csrf_valid(
528 state: &CsrfState,
529 cookie_token: &str,
530 submitted: &str,
531 session_value: Option<&str>,
532) -> bool {
533 if !tokens_match(cookie_token, submitted) {
534 return false;
535 }
536 if !state.signed {
537 return true;
538 }
539 let Some(secret) = state.secret.as_deref() else {
540 // Signing requested but no secret resolved (e.g. before App::build()):
541 // fall back to plain double-submit rather than locking writes out.
542 return true;
543 };
544 let Some((raw, sig)) = cookie_token.rsplit_once('.') else {
545 // Signed mode requires a signature; an unsigned token can't be trusted.
546 return false;
547 };
548 let expected = sign(secret, raw, state.session_bind(session_value));
549 tokens_match(sig, &expected)
550}
551
552/// Pull the value of a named cookie out of a `Cookie` header. v0 shape: linear
553/// scan, no quoting.
554fn cookie_value<'a>(header: &'a str, name: &str) -> Option<&'a str> {
555 for part in header.split(';') {
556 let part = part.trim();
557 if let Some((k, v)) = part.split_once('=') {
558 if k == name {
559 return Some(v);
560 }
561 }
562 }
563 None
564}
565
566fn is_safe_method(method: &Method) -> bool {
567 matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS)
568}
569
570async fn csrf_middleware(
571 State(state): State<CsrfState>,
572 req: Request,
573 next: Next,
574) -> Result<Response, Infallible> {
575 let method = req.method().clone();
576
577 // Exempt paths (e.g. a token-authenticated `/api`) bypass CSRF entirely —
578 // they carry no session cookie, so the double-submit check doesn't apply.
579 if state.is_exempt(req.uri().path()) {
580 return Ok(next.run(req).await);
581 }
582
583 let cookie_header = req
584 .headers()
585 .get(COOKIE)
586 .and_then(|h| h.to_str().ok())
587 .map(str::to_string);
588 let cookie_token = cookie_header
589 .as_deref()
590 .and_then(|h| cookie_value(h, CSRF_COOKIE).map(str::to_string));
591 let session_value = state.session_cookie.as_deref().and_then(|name| {
592 cookie_header
593 .as_deref()
594 .and_then(|h| cookie_value(h, name).map(str::to_string))
595 });
596
597 if is_safe_method(&method) {
598 // The middleware is the only mint (docs/decisions/
599 // 2026-06-10-automatic-csrf.md): mint BEFORE the handler runs so
600 // first-visit renders already have a token in scope, and rotate a
601 // cookie token that can't pass signed-mode validation so flipping
602 // `signed_csrf` on doesn't 403 browsers holding old cookies.
603 let (token, minted) = match cookie_token {
604 Some(t) if state.token_acceptable(&t, session_value.as_deref()) => (t, false),
605 _ => (mint_token(&state, session_value.as_deref()), true),
606 };
607 let mut response =
608 umbral::templates::with_current_csrf(Some(token.clone()), next.run(req)).await;
609 if minted {
610 let mut cookie = format!("{CSRF_COOKIE}={token}; Path=/; SameSite=Lax");
611 if state.secure {
612 cookie.push_str("; Secure");
613 }
614 if let Ok(v) = HeaderValue::from_str(&cookie) {
615 // `append`, not `insert` — `insert` would wipe any cookie
616 // the handler set on this response (e.g. the session).
617 response.headers_mut().append(SET_COOKIE, v);
618 }
619 }
620 return Ok(response);
621 }
622
623 // Write methods: cookie and (header OR form field) must validate.
624 // On success the token is scoped around the handler so a
625 // validation-error re-render still carries it into the form.
626 let header_token = req
627 .headers()
628 .get(CSRF_HEADER)
629 .and_then(|h| h.to_str().ok())
630 .map(str::to_string);
631
632 if let Some(c) = cookie_token.as_ref() {
633 if let Some(h) = header_token.as_ref() {
634 if csrf_valid(&state, c, h, session_value.as_deref()) {
635 let token = c.clone();
636 return Ok(umbral::templates::with_current_csrf(Some(token), next.run(req)).await);
637 }
638 }
639 // Form-field path: peek the urlencoded body, then rebuild the request.
640 let content_type = req
641 .headers()
642 .get(http::header::CONTENT_TYPE)
643 .and_then(|v| v.to_str().ok())
644 .unwrap_or("")
645 .to_string();
646 if content_type.starts_with("application/x-www-form-urlencoded") {
647 let cookie_owned = c.clone();
648 let (parts, body) = req.into_parts();
649 let bytes = match axum::body::to_bytes(body, MAX_FORM_BODY).await {
650 Ok(b) => b,
651 Err(_) => return Ok(forbidden()),
652 };
653 if let Some(s) = form_field_token(&bytes) {
654 if csrf_valid(&state, &cookie_owned, &s, session_value.as_deref()) {
655 let req = Request::from_parts(parts, Body::from(bytes));
656 return Ok(umbral::templates::with_current_csrf(
657 Some(cookie_owned),
658 next.run(req),
659 )
660 .await);
661 }
662 }
663 }
664 }
665
666 Ok(forbidden())
667}
668
669/// Strip the `Server` response header (used when `hide_server_header` is set
670/// and no explicit value was given).
671async fn strip_server_header(req: Request, next: Next) -> Result<Response, Infallible> {
672 let mut response = next.run(req).await;
673 response.headers_mut().remove(SERVER);
674 Ok(response)
675}
676
677fn forbidden() -> Response {
678 let body = Body::from("CSRF verification failed");
679 Response::builder()
680 .status(StatusCode::FORBIDDEN)
681 .body(body)
682 .expect("static response")
683}
684
685/// Scan a urlencoded form body for any of the accepted CSRF field names.
686fn form_field_token(body: &[u8]) -> Option<String> {
687 let s = std::str::from_utf8(body).ok()?;
688 for part in s.split('&') {
689 let mut iter = part.splitn(2, '=');
690 let key = iter.next()?;
691 let val = iter.next().unwrap_or("");
692 if CSRF_FORM_FIELDS.contains(&key) {
693 // Tokens are hex (signed tokens add a `.` + hex sig — still no
694 // urlencoded-special chars), so `+`→space is the only decode
695 // needed for the common case.
696 return Some(val.replace('+', " "));
697 }
698 }
699 None
700}
701
702/// Read the current CSRF token from the request's cookie header. Public so
703/// handlers that render HTML forms can embed it as a hidden `csrf_token` input.
704pub fn current_csrf_token(headers: &http::HeaderMap) -> Option<String> {
705 headers
706 .get(COOKIE)
707 .and_then(|h| h.to_str().ok())
708 .and_then(|h| cookie_value(h, CSRF_COOKIE).map(str::to_string))
709}
710
711/// Constant-time string equality. Short-circuit `==` on `String` is a timing
712/// side-channel; `ct_eq` closes it. Per OWASP's "Use Constant-Time String
713/// Comparison" rule for security tokens. Public so other token consumers
714/// (e.g. the admin's SecurityPlugin-less login fallback) compare the same way.
715pub fn tokens_match(a: &str, b: &str) -> bool {
716 use subtle::ConstantTimeEq;
717 a.as_bytes().ct_eq(b.as_bytes()).into()
718}
719
720/// Validate that `secret_key` is non-empty when signed CSRF is enabled.
721///
722/// Called from [`SecurityPlugin::on_ready`]. Extracted as a free function so
723/// integration tests can exercise it with an explicit [`umbral::Settings`]
724/// without needing a live `App::build()` to populate the ambient
725/// `SETTINGS` OnceLock (which is `pub(crate)` and unreachable from plugin
726/// tests).
727///
728/// Behaviour when `settings` is `None` (i.e. `get_opt()` returned nothing,
729/// common in tests that bypass `App::build()`): treated as non-prod, no
730/// error.
731fn check_secret_key(
732 settings: Option<&umbral::Settings>,
733 config: &SecurityConfig,
734) -> Result<(), umbral::plugin::PluginError> {
735 // Only relevant when signed CSRF is active; plain double-submit doesn't
736 // use the secret at all.
737 if !config.csrf || !config.signed_csrf {
738 return Ok(());
739 }
740
741 let Some(s) = settings else {
742 // No settings available — running outside App::build() (e.g. tests).
743 // Can't determine environment or secret; skip.
744 return Ok(());
745 };
746
747 if s.secret_key.trim().is_empty() {
748 match s.environment {
749 Environment::Dev | Environment::Test => {
750 tracing::warn!(
751 "SecurityPlugin: SECRET_KEY is empty — CSRF tokens are signed with an \
752 empty HMAC key and are trivially forgeable. Set `secret_key` in \
753 umbral.toml or the UMBRAL_SECRET_KEY environment variable before \
754 deploying."
755 );
756 }
757 Environment::Prod => {
758 return Err(
759 "SecurityPlugin: SECRET_KEY must not be empty in production. \
760 An empty key makes CSRF tokens trivially forgeable. \
761 Set `secret_key` in umbral.toml or via UMBRAL_SECRET_KEY."
762 .into(),
763 );
764 }
765 }
766 }
767
768 Ok(())
769}
770
771/// Test-only constructors. `#[doc(hidden)]` — NOT a stable API; integration
772/// tests need a CSRF-wrapped router without `App::build()`-resolved settings.
773#[doc(hidden)]
774pub mod test_support {
775 use super::*;
776
777 /// Wrap `router` with the CSRF middleware using an explicit state,
778 /// bypassing settings resolution.
779 pub fn wrap_with_csrf(
780 router: axum::Router,
781 signed: bool,
782 secret: Option<String>,
783 ) -> axum::Router {
784 let state = CsrfState {
785 secure: false,
786 signed,
787 secret,
788 session_cookie: None,
789 exempt_paths: Vec::new(),
790 };
791 router.layer(middleware::from_fn_with_state(state, csrf_middleware))
792 }
793
794 /// Exercise [`check_secret_key`] directly with an explicit [`umbral::Settings`],
795 /// bypassing the ambient `SETTINGS` OnceLock (which is `pub(crate)` and
796 /// unreachable from plugin tests).
797 pub fn validate_secret_key(
798 settings: &umbral::Settings,
799 config: &SecurityConfig,
800 ) -> Result<(), umbral::plugin::PluginError> {
801 check_secret_key(Some(settings), config)
802 }
803}
804
805#[cfg(test)]
806mod tests {
807 use super::*;
808
809 fn signed_state(secret: &str, session_cookie: Option<&str>) -> CsrfState {
810 CsrfState {
811 secure: false,
812 signed: true,
813 secret: Some(secret.to_string()),
814 session_cookie: session_cookie.map(str::to_string),
815 exempt_paths: Vec::new(),
816 }
817 }
818
819 #[test]
820 fn signing_is_deterministic_and_key_dependent() {
821 assert_eq!(sign("k", "abc", None), sign("k", "abc", None));
822 assert_ne!(sign("k1", "abc", None), sign("k2", "abc", None));
823 assert_ne!(sign("k", "abc", None), sign("k", "abc", Some("sess")));
824 }
825
826 #[test]
827 fn signed_token_round_trips_and_rejects_forgery() {
828 let st = signed_state("app-secret", None);
829 let token = mint_token(&st, None);
830 // Minted token is `<raw>.<sig>` and validates as a double-submit pair.
831 assert!(token.contains('.'));
832 assert!(csrf_valid(&st, &token, &token, None));
833 // An unsigned token (attacker-planted, no valid signature) is rejected
834 // even though it double-submits against itself.
835 let forged = generate_token();
836 assert!(!csrf_valid(&st, &forged, &forged, None));
837 // A token signed under a different key is rejected.
838 let other = signed_state("different-secret", None);
839 let other_token = mint_token(&other, None);
840 assert!(!csrf_valid(&st, &other_token, &other_token, None));
841 }
842
843 #[test]
844 fn session_binding_ties_token_to_session_value() {
845 let st = signed_state("app-secret", Some("umbral_session"));
846 let token = mint_token(&st, Some("sess-A"));
847 assert!(csrf_valid(&st, &token, &token, Some("sess-A")));
848 // Same token under a different session value no longer validates.
849 assert!(!csrf_valid(&st, &token, &token, Some("sess-B")));
850 }
851
852 #[test]
853 fn unsigned_mode_is_plain_double_submit() {
854 let st = CsrfState {
855 secure: false,
856 signed: false,
857 secret: None,
858 session_cookie: None,
859 exempt_paths: Vec::new(),
860 };
861 let tok = generate_token();
862 assert!(csrf_valid(&st, &tok, &tok, None));
863 assert!(!csrf_valid(&st, &tok, "different", None));
864 }
865
866 #[test]
867 fn exempt_path_matching_is_prefix_based() {
868 let st = CsrfState {
869 secure: false,
870 signed: false,
871 secret: None,
872 session_cookie: None,
873 exempt_paths: vec!["/api".to_string()],
874 };
875 assert!(st.is_exempt("/api"));
876 assert!(st.is_exempt("/api/customer/1"));
877 assert!(!st.is_exempt("/admin"));
878 assert!(!st.is_exempt("/contact"));
879 }
880
881 /// `/api` exempt must NOT bleed into `/api-internal`, `/apixyz`, etc.
882 /// The boundary check requires the prefix to be followed by `/` (sub-path)
883 /// or be an exact match — a bare `starts_with("/api")` would incorrectly
884 /// exempt those sibling routes.
885 #[test]
886 fn csrf_exempt_boundary_stops_at_path_segment() {
887 let st = CsrfState {
888 secure: false,
889 signed: false,
890 secret: None,
891 session_cookie: None,
892 exempt_paths: vec!["/api".to_string()],
893 };
894 // Exact match and sub-paths ARE exempt.
895 assert!(st.is_exempt("/api"), "/api exact must be exempt");
896 assert!(
897 st.is_exempt("/api/users"),
898 "/api/users sub-path must be exempt"
899 );
900 assert!(
901 st.is_exempt("/api/v2/resource"),
902 "/api/v2/resource must be exempt"
903 );
904 // Paths that merely START WITH the string but aren't segment-separated
905 // must NOT be exempt — that would be a CSRF-bypass on unintended routes.
906 assert!(
907 !st.is_exempt("/api-internal"),
908 "/api-internal must NOT be exempt when /api is configured"
909 );
910 assert!(
911 !st.is_exempt("/apixyz"),
912 "/apixyz must NOT be exempt when /api is configured"
913 );
914 assert!(
915 !st.is_exempt("/api2"),
916 "/api2 must NOT be exempt when /api is configured"
917 );
918 }
919
920 #[test]
921 fn hsts_value_reflects_flags() {
922 let cfg = SecurityConfig {
923 hsts_max_age: 100,
924 hsts_include_subdomains: true,
925 hsts_preload: true,
926 ..Default::default()
927 };
928 assert_eq!(cfg.hsts_value(), "max-age=100; includeSubDomains; preload");
929 let bare = SecurityConfig {
930 hsts_max_age: 100,
931 hsts_include_subdomains: false,
932 hsts_preload: false,
933 ..Default::default()
934 };
935 assert_eq!(bare.hsts_value(), "max-age=100");
936 }
937}