steid

@jamesgill /

1//! Cross-site request forgery protection for every form.
2//!
3//! **This is defence in depth, not the only defence.** Two things already stand in
4//! front of it. The session cookie is `SameSite=Lax`, which stops a cross-site POST in
5//! every current browser; and Topcoat's `sessions()` installs an
6//! [`OriginLayer`](topcoat::session::OriginLayer) that refuses any state-changing
7//! request whose `Sec-Fetch-Site` is not `same-origin`/`none`, falling back to
8//! comparing `Origin`'s host against the request's own. What that layer deliberately
9//! lets through is a request carrying **neither** header — a non-browser client, which
10//! has no ambient cookies to forge with. A browser old enough to send neither, or a
11//! proxy that strips `Origin`, lands in the same gap, and this is what covers it. It
12//! also covers `SameSite` being loosened later, which is a one-line change somebody
13//! could make for an unrelated reason.
14//!
15//! **The pattern is double-submit bound to the session.** The token is
16//! `HMAC-SHA-256(secret, session token hash)`, rendered hex. Nothing new is stored:
17//! the session already exists on both sides, and the HMAC is what stops a visitor
18//! minting a token for a session that is not theirs. A token is therefore useless
19//! anywhere but in the session it was rendered for, which is the property a plain
20//! random hidden field does not have.
21//!
22//! **The secret is random per boot** ([`CsrfSecret::generate`]), not derived from
23//! anything durable — Steid configures no session secret to derive from
24//! (`SessionConfig::default()` in `main`), so there is nothing else to use. The cost
25//! is that a restart invalidates every form that is already open on someone's screen:
26//! submitting it answers 403 and they reload and retype. That is acceptable for a
27//! form and would not be for a session, which is why the session cookie is not
28//! treated the same way.
29//!
30//! **A request with no session is refused**, uniformly, for every guarded route. Every
31//! guarded route is an owner's, so an anonymous POST to one was going to be refused a
32//! moment later anyway; refusing it here answers the same 403 whether or not the target
33//! exists, so nothing leaks by status code.
34//!
35//! ## What is exempt, and why
36//!
37//! Enumerated in [`EXEMPT`] and asserted by the test at the bottom of this file. Two
38//! kinds:
39//!
40//! - **No cookie and no form.** The git transport (`git-upload-pack`,
41//! `git-receive-pack`) authenticates with HTTP Basic per request, and `/api/setup` is
42//! JSON a provisioner POSTs. Neither is reached from a browser carrying a session, so
43//! there is no ambient authority to forge with and nowhere to put a hidden field.
44//! - **No session to bind to.** `/auth/setup`, `/auth/forgot` and `/auth/reset/{token}`
45//! are submitted by someone who is not signed in. A double-submit token there would be
46//! one an attacker can simply fetch, so it would protect nothing.
47//!
48//! ## Signing in
49//!
50//! `/auth/login` is submitted signed out too, but it is not exempt: login CSRF — a
51//! forged form that signs the victim's browser in *as the attacker* — is real, and it is
52//! closed by [`csrf_verified_signed_out`] rather than by a token. See its doc and
53//! 0008's note of 2026-10-07 for why not a pre-session cookie.
54
55use hmac::{Hmac, Mac};
56use serde::Deserialize;
57use sha2::Sha256;
58use subtle::ConstantTimeEq;
59use topcoat::{
60 Result,
61 context::{Cx, app_context},
62 router::{Body, Response, StatusCode, header::ORIGIN, headers},
63 session,
64 view::{component, view},
65};
66
67type HmacSha256 = Hmac<Sha256>;
68
69/// The name of the hidden input, and of the field on every guarded form struct.
70pub const CSRF_FIELD: &str = "csrf_token";
71
72/// What a refused submission is told. One sentence, because there is nothing the
73/// person can usefully do beyond going back — and because saying more would describe
74/// the check to whoever is probing it.
75pub const REFUSED: &str = "This form was submitted from somewhere else. Go back and try again.";
76
77/// The routes that deliberately do not carry a token, with the reason.
78///
79/// Read by the scan test in `csrf_scan.rs`, which fails when a POST route neither calls
80/// the check nor appears here — so a new form cannot forget, and an exemption has to be
81/// written down before it counts.
82pub const EXEMPT: &[(&str, &str)] = &[
83 (
84 "/{handle}/repos/{repo}/git-upload-pack",
85 "git transport: HTTP Basic per request, no cookie and no form",
86 ),
87 (
88 "/{handle}/repos/{repo}/git-receive-pack",
89 "git transport: HTTP Basic per request, no cookie and no form",
90 ),
91 (
92 "/api/setup",
93 "JSON a provisioner POSTs, never a browser carrying a session",
94 ),
95 (
96 "/auth/setup",
97 "submitted signed out: no session to bind a token to",
98 ),
99 (
100 "/auth/forgot",
101 "submitted signed out: no session to bind a token to",
102 ),
103 (
104 "/auth/reset/{token}",
105 "submitted signed out, and the URL's own token is the unguessable part",
106 ),
107];
108
109/// The process-wide secret the tokens are derived from.
110///
111/// Lives in app context, built once in `main`. Built per request it would mint a
112/// different token on every page and verify nothing.
113pub struct CsrfSecret([u8; 32]);
114
115impl CsrfSecret {
116 /// A fresh secret. See the module header for why this is per boot.
117 #[must_use]
118 pub fn generate() -> Self {
119 use rand::Rng;
120
121 let mut bytes = [0u8; 32];
122 rand::rng().fill_bytes(&mut bytes);
123
124 Self(bytes)
125 }
126}
127
128impl std::fmt::Debug for CsrfSecret {
129 /// Redacted, like every other secret in the codebase: a `Debug` of the app context
130 /// must not be a way to read it out of a log.
131 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132 f.write_str("CsrfSecret(redacted)")
133 }
134}
135
136/// The token for one session under one secret.
137///
138/// Separated from the request so it can be tested without a `Cx`.
139fn derive(secret: &CsrfSecret, session: &[u8]) -> String {
140 // Infallible for HMAC: the construction accepts a key of any length.
141 let mut mac = HmacSha256::new_from_slice(&secret.0).expect("hmac takes any key");
142 mac.update(session);
143
144 mac.finalize()
145 .into_bytes()
146 .iter()
147 .map(|byte| format!("{byte:02x}"))
148 .collect()
149}
150
151/// Whether a presented token is the expected one, without leaking where they differ.
152///
153/// Length is compared by `ct_eq` too, so two values of different length are unequal
154/// without an early return that depends on the first differing byte.
155fn matches(expected: &str, presented: &str) -> bool {
156 expected.as_bytes().ct_eq(presented.as_bytes()).unwrap_u8() == 1
157}
158
159/// This request's token, or `None` when there is no session to bind one to.
160async fn token(cx: &Cx) -> Result<Option<String>> {
161 let Some(hash) = session::token_hash(cx).await? else {
162 return Ok(None);
163 };
164
165 Ok(Some(derive(app_context::<CsrfSecret>(cx), &*hash)))
166}
167
168/// The hidden input every guarded form carries.
169///
170/// A component rather than a helper function because `view!` needs `__cx` in scope. It
171/// declares `cx` and so is invoked bare — `csrf_field()` — with no argument.
172///
173/// Renders an empty value when there is no session. Every guarded route is an owner's,
174/// so the only visitor who sees that is one whose submission is refused either way.
175#[component]
176pub async fn csrf_field(cx: &Cx) -> Result {
177 let token = token(cx).await?.unwrap_or_default();
178
179 view! { <input type="hidden" name=(CSRF_FIELD) value=(token.as_str()) /> }
180}
181
182/// Refuses the submission unless it carries this session's token.
183///
184/// Called by every `#[page(POST …)]` handler **before its use case**, so that nothing
185/// with a side effect runs on a submission that may not be the visitor's own. The
186/// refusal is a **403, not a 404**: the visitor is signed in and the page they were
187/// looking at exists, so the honest answer is that this particular request is not
188/// allowed — and unlike the ownership guards there is nothing to hide, because the
189/// answer does not depend on the target.
190///
191/// # Errors
192///
193/// [`CsrfRefused`] when the token is absent, wrong, or there is no session.
194pub async fn csrf_verified(cx: &Cx, presented: &str) -> Result<()> {
195 match token(cx).await? {
196 Some(expected) if matches(&expected, presented) => Ok(()),
197 _ => {
198 eprintln!("steid: refused a form submission with no valid CSRF token");
199 Err(CsrfRefused.into())
200 }
201 }
202}
203
204/// [`csrf_verified`] for the `#[route(POST …)]` handlers, which return a `Response`
205/// rather than a view.
206///
207/// Layouts wrap views, so a route handler cannot reach the 403 page the layout renders
208/// for [`CsrfRefused`] — it would fall through to a 500. It gets the same sentence as a
209/// plain response instead, in the shape `throttled` already established:
210///
211/// ```ignore
212/// if let Some(response) = csrf_verified_response(cx, &form.csrf_token).await? {
213/// return Ok(response);
214/// }
215/// ```
216///
217/// # Errors
218///
219/// Propagates a session-store failure. A refusal is the `Some` arm, not an error.
220pub async fn csrf_verified_response(cx: &Cx, presented: &str) -> Result<Option<Response>> {
221 match csrf_verified(cx, presented).await {
222 Ok(()) => Ok(None),
223 Err(error) => {
224 if error.downcast_ref::<CsrfRefused>().is_some() {
225 Ok(Some(refused()))
226 } else {
227 Err(error)
228 }
229 }
230 }
231}
232
233/// The CSRF check for a form submitted signed out: `POST /auth/login`.
234///
235/// Signed out there is no session to bind a token to, so [`csrf_verified`] cannot
236/// apply. What a browser does send is its own account of where the request came from.
237/// Topcoat's `OriginLayer` refuses a POST whose `Sec-Fetch-Site` is `same-site` or
238/// `cross-site`, or whose `Origin` names another host, and lets one carrying
239/// **neither** header through: a non-browser client has no ambient cookies to forge
240/// with. Login CSRF needs none, though. The forged form carries the attacker's own
241/// credentials, and what it steals is the victim's browser, which ends up signed in as
242/// the attacker. A browser too old for both headers, or a proxy that strips `Origin`,
243/// sends exactly that gap, so here it is refused.
244///
245/// Every browser that can use this form sends at least one of the two on a POST. The
246/// cost lands on a script signing in with a bare HTTP client, which must now send
247/// `Origin` or `Sec-Fetch-Site`.
248///
249/// It also runs the layer's own [`verify_origin`](session::verify_origin), so that this
250/// check does not depend on the layer being installed. While it is, that changes
251/// nothing: the layer has already refused what it would refuse.
252///
253/// Call it first, after `throttled`, in the `if let Some(response)` shape. The refusal
254/// is the same 403 sentence as [`csrf_verified_response`]'s.
255pub fn csrf_verified_signed_out(cx: &Cx) -> Option<Response> {
256 let headers = headers(cx);
257 let says_where = headers.contains_key("sec-fetch-site") || headers.contains_key(ORIGIN);
258
259 if says_where && session::verify_origin(cx).is_ok() {
260 return None;
261 }
262
263 eprintln!("steid: refused a signed-out form submission that did not say where it came from");
264 Some(refused())
265}
266
267/// The 403 a `#[route]` handler answers a refused submission with: [`REFUSED`], and
268/// nothing else.
269fn refused() -> Response {
270 let mut response = Response::new(Body::from(format!("{REFUSED}\n")));
271 *response.status_mut() = StatusCode::FORBIDDEN;
272 response
273}
274
275/// A submission that did not carry this session's token.
276///
277/// Not one of Topcoat's error types, so the router would render it as a 500 — the root
278/// layout catches it by downcast and renders [`REFUSED`] with a 403 instead. That is
279/// the only way a `#[page]` handler can answer with both a status and a view.
280#[derive(Debug)]
281pub struct CsrfRefused;
282
283impl std::fmt::Display for CsrfRefused {
284 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
285 f.write_str("the form did not carry this session's CSRF token")
286 }
287}
288
289impl std::error::Error for CsrfRefused {}
290
291/// The `csrf_token` field on its own, for a POST that otherwise submits nothing —
292/// a delete button, a toggle, signing out.
293///
294/// Without this those handlers took no `Form` at all, and adding a one-field struct to
295/// each of them would be eight copies of the same three lines.
296#[derive(Debug, Deserialize)]
297pub struct CsrfGuard {
298 /// `default` for the reason every guarded form's own field is: a body with no token
299 /// must reach [`csrf_verified`] and be refused with a sentence, rather than failing
300 /// deserialization into a bare 400.
301 #[serde(default)]
302 pub csrf_token: String,
303}
304
305#[cfg(test)]
306mod tests {
307 use super::*;
308
309 /// A fixed secret, so a derivation can be asserted rather than merely compared to
310 /// itself.
311 fn secret(byte: u8) -> CsrfSecret {
312 CsrfSecret([byte; 32])
313 }
314
315 #[test]
316 fn a_token_is_the_hmac_of_the_session_under_the_secret() {
317 // Cross-checked against `openssl dgst -sha256 -mac HMAC -macopt hexkey:<32 * 01>`
318 // over the four bytes `sess`.
319 assert_eq!(
320 derive(&secret(0x01), b"sess"),
321 "8a705977f42fbbc2a31942039d841760ec5de4c812f88e983674c0a5b44f61f7"
322 );
323 }
324
325 #[test]
326 fn two_sessions_get_different_tokens_under_one_secret() {
327 // The whole point of binding: a token minted for one session must not verify
328 // for another, or a signed-in attacker could hand out their own.
329 assert_ne!(derive(&secret(0x01), b"one"), derive(&secret(0x01), b"two"));
330 }
331
332 #[test]
333 fn two_boots_get_different_tokens_for_one_session() {
334 // Why a restart invalidates open forms, stated as a test rather than only in
335 // the header.
336 assert_ne!(derive(&secret(0x01), b"one"), derive(&secret(0x02), b"one"));
337 }
338
339 #[test]
340 fn a_token_verifies_against_itself_and_nothing_else() {
341 let token = derive(&secret(0x01), b"sess");
342
343 assert!(matches(&token, &token));
344 assert!(!matches(&token, ""));
345 assert!(!matches(&token, &token[..token.len() - 1]));
346 assert!(!matches(&token, &format!("{token}0")));
347 assert!(!matches(&token, &derive(&secret(0x01), b"other")));
348 }
349
350 #[test]
351 fn the_secret_does_not_print_itself() {
352 // A secret that shows up in a `Debug` of the app context is a secret in a log.
353 assert_eq!(format!("{:?}", secret(0x01)), "CsrfSecret(redacted)");
354 }
355
356 #[test]
357 fn every_exemption_says_why() {
358 for (route, reason) in EXEMPT {
359 assert!(route.starts_with('/'), "{route} is not a route");
360 assert!(!reason.is_empty(), "{route} is exempt for no stated reason");
361 }
362 }
363}