1use data_encoding::BASE64URL_NOPAD;
8use subtle::ConstantTimeEq;
9use topcoat::{
10 context::{Cx, try_context},
11 cookie::{Cookie, CookieJarCell, Cookies, cookies},
12};
13
14pub const COOKIE_NAME: &str = "__Host-tablo_csrf";
16pub const FIELD_NAME: &str = "csrf_token";
17
18const TOKEN_LEN: usize = 16;
20
21pub 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
44pub 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
56pub 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
64pub 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
83fn 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
97pub 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;