Skip to main content

tablo_core/
csrf.rs

1//! CSRF protection via double-submit cookie.
2//!
3//! Verifies state-changing POSTs with a double-submit `__Host-` cookie compared in constant time.
4//! A form carries the cookie's token masked with a one-time pad drawn for each render, so no two
5//! compressed pages hold the same bytes for an observer to guess from response sizes (BREACH).
6
7use data_encoding::BASE64URL_NOPAD;
8use subtle::ConstantTimeEq;
9use topcoat::{
10    context::{Cx, try_context},
11    cookie::{Cookie, CookieJarCell, Cookies, cookies},
12};
13
14/// Names the `__Host-`-prefixed CSRF cookie.
15pub const COOKIE_NAME: &str = "__Host-tablo_csrf";
16pub const FIELD_NAME: &str = "csrf_token";
17
18/// The bytes in a token.
19const TOKEN_LEN: usize = 16;
20
21/// Ensures a request token before headers send, returning `""` without a cookie layer.
22pub fn ensure_token(cx: &Cx) -> String {
23    if try_context::<CookieJarCell>(cx).is_none() {
24        return String::new();
25    }
26    let jar = cookies(cx);
27    if let Some(cookie) = jar.get(COOKIE_NAME) {
28        let value = cookie.value().to_string();
29        if is_valid_token(&value) {
30            return value;
31        }
32    }
33    let token = uuid::Uuid::new_v4().to_string();
34    let cookie = Cookie::build((COOKIE_NAME, token.clone()))
35        .path("/")
36        .http_only(true)
37        .secure(true)
38        .same_site(topcoat::cookie::SameSite::Lax)
39        .build();
40    jar.add(cookie);
41    token
42}
43
44/// Reads the current token without setting one, safe inside streamed children.
45pub fn current_token(cx: &Cx) -> String {
46    if try_context::<CookieJarCell>(cx).is_none() {
47        return String::new();
48    }
49    cookies(cx)
50        .get(COOKIE_NAME)
51        .map(|c| c.value().to_string())
52        .filter(|v| is_valid_token(v))
53        .unwrap_or_default()
54}
55
56/// Renders the hidden field carrying the given token, [`mask`]ed afresh.
57pub fn field<'a>(cx: &'a Cx, token: &str) -> topcoat::view::BoxView<'a> {
58    use topcoat::view::ViewExt;
59
60    let value = mask(token);
61    topcoat::view::view! { <input type="hidden" name=(FIELD_NAME) value=(value)> }.boxed()
62}
63
64/// The value a form posts under [`FIELD_NAME`] for `token`: the token XORed with a random pad,
65/// pad first, in unpadded base64url. Each call draws a new pad, so the same token never renders
66/// twice the same; [`verify`] accepts any of them. `""` when `token` is not a token
67/// [`ensure_token`] issued.
68///
69/// [`field`] renders it; call it for a form a page builds without the view.
70pub fn mask(token: &str) -> String {
71    let Ok(token) = token.parse::<uuid::Uuid>() else {
72        return String::new();
73    };
74    let mut masked = [0u8; 2 * TOKEN_LEN];
75    let (pad, sealed) = masked.split_at_mut(TOKEN_LEN);
76    getrandom::fill(pad).expect("the CSRF pad randomness source failed");
77    for ((sealed, pad), byte) in sealed.iter_mut().zip(&*pad).zip(token.as_bytes()) {
78        *sealed = pad ^ byte;
79    }
80    BASE64URL_NOPAD.encode(&masked)
81}
82
83/// The token a [`mask`]ed value carries, or `None` when `value` is not one.
84fn unmask(value: &str) -> Option<[u8; TOKEN_LEN]> {
85    let masked = BASE64URL_NOPAD.decode(value.as_bytes()).ok()?;
86    let (pad, sealed) = masked.split_at_checked(TOKEN_LEN)?;
87    if sealed.len() != TOKEN_LEN {
88        return None;
89    }
90    let mut token = [0u8; TOKEN_LEN];
91    for ((byte, pad), sealed) in token.iter_mut().zip(pad).zip(sealed) {
92        *byte = pad ^ sealed;
93    }
94    Some(token)
95}
96
97/// Verifies the value a POST `submitted` under [`FIELD_NAME`] is a [`mask`] of the cookie's
98/// token with a constant-time compare, failing closed with 403. The cookie's token itself,
99/// unmasked, is refused: no page renders it.
100pub fn verify(cx: &Cx, submitted: Option<&str>) -> Result<(), topcoat::Error> {
101    let expected = try_context::<CookieJarCell>(cx)
102        .and_then(|_| cookies(cx).get(COOKIE_NAME).map(|c| c.value().to_string()))
103        .and_then(|value| value.parse::<uuid::Uuid>().ok());
104    let submitted = submitted.and_then(unmask);
105    let (Some(expected), Some(submitted)) = (expected, submitted) else {
106        return Err(topcoat::router::error::forbidden().into());
107    };
108    if submitted.as_slice().ct_ne(expected.as_bytes()).into() {
109        return Err(topcoat::router::error::forbidden().into());
110    }
111    Ok(())
112}
113
114fn is_valid_token(value: &str) -> bool {
115    value.parse::<uuid::Uuid>().is_ok()
116}
117
118#[cfg(test)]
119mod tests;