Skip to main content

serenade_security/
csrf.rs

1//! CSRF token manager (Symfony `CsrfTokenManager` analogue).
2//!
3//! Tokens are HMAC-signed and **stateless**: validation recomputes the MAC.
4//! Forms embed the value in `_token`; no server session store is required for v0.
5
6use hmac::{Hmac, KeyInit, Mac};
7use sha2::Sha256;
8use subtle::ConstantTimeEq;
9
10use crate::SecurityError;
11
12type HmacSha256 = Hmac<Sha256>;
13
14/// Default HTML form field name for the CSRF token (Symfony `_token`).
15pub const CSRF_FIELD_NAME: &str = "_token";
16
17/// Issued CSRF token: intention id + opaque value for the form field.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct CsrfToken {
20    id: String,
21    value: String,
22}
23
24impl CsrfToken {
25    /// Builds a token from an intention id and opaque value.
26    #[must_use]
27    pub fn new(id: impl Into<String>, value: impl Into<String>) -> Self {
28        Self {
29            id: id.into(),
30            value: value.into(),
31        }
32    }
33
34    /// Intention / form id (Symfony token id).
35    #[must_use]
36    pub fn id(&self) -> &str {
37        &self.id
38    }
39
40    /// Opaque value placed in the CSRF form field.
41    #[must_use]
42    pub fn value(&self) -> &str {
43        &self.value
44    }
45}
46
47/// Issues and validates CSRF tokens.
48pub trait CsrfTokenManager: Send + Sync {
49    /// Creates a new token for `token_id` (usually the form name).
50    ///
51    /// # Errors
52    ///
53    /// Returns [`SecurityError::CsrfGeneration`] when the RNG fails.
54    fn get_token(&self, token_id: &str) -> Result<CsrfToken, SecurityError>;
55
56    /// Returns whether `token` matches a previously issued value for its id.
57    fn is_token_valid(&self, token: &CsrfToken) -> bool;
58}
59
60/// HMAC-SHA256 CSRF manager. Secret must be app-owned and stable across requests.
61#[derive(Debug, Clone)]
62pub struct HmacCsrfTokenManager {
63    secret: Vec<u8>,
64}
65
66impl HmacCsrfTokenManager {
67    /// Creates a manager keyed by `secret` (use a long random app secret).
68    #[must_use]
69    pub fn new(secret: impl AsRef<[u8]>) -> Self {
70        Self {
71            secret: secret.as_ref().to_vec(),
72        }
73    }
74
75    fn sign(&self, token_id: &str, nonce_hex: &str) -> String {
76        // HMAC-SHA256 accepts any key length (including empty).
77        let mut mac = Hmac::<Sha256>::new_from_slice(&self.secret)
78            .unwrap_or_else(|_| HmacSha256::new_from_slice(&[0_u8; 32]).expect("fallback key"));
79        mac.update(token_id.as_bytes());
80        mac.update(b":");
81        mac.update(nonce_hex.as_bytes());
82        hex_encode(&mac.finalize().into_bytes())
83    }
84}
85
86impl CsrfTokenManager for HmacCsrfTokenManager {
87    fn get_token(&self, token_id: &str) -> Result<CsrfToken, SecurityError> {
88        let mut nonce = [0_u8; 16];
89        getrandom::fill(&mut nonce).map_err(|_| SecurityError::CsrfGeneration)?;
90        let nonce_hex = hex_encode(&nonce);
91        let mac_hex = self.sign(token_id, &nonce_hex);
92        Ok(CsrfToken::new(token_id, format!("{nonce_hex}.{mac_hex}")))
93    }
94
95    fn is_token_valid(&self, token: &CsrfToken) -> bool {
96        let Some((nonce_hex, mac_hex)) = token.value().split_once('.') else {
97            return false;
98        };
99        if nonce_hex.is_empty() || mac_hex.is_empty() {
100            return false;
101        }
102        let expected = self.sign(token.id(), nonce_hex);
103        expected.as_bytes().ct_eq(mac_hex.as_bytes()).into()
104    }
105}
106
107fn hex_encode(bytes: &[u8]) -> String {
108    const HEX: &[u8; 16] = b"0123456789abcdef";
109    let mut out = String::with_capacity(bytes.len() * 2);
110    for byte in bytes {
111        out.push(HEX[(byte >> 4) as usize] as char);
112        out.push(HEX[(byte & 0x0f) as usize] as char);
113    }
114    out
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    #[test]
122    fn hmac_roundtrip() {
123        let mgr = HmacCsrfTokenManager::new(b"test-secret-key-32bytes-minimum!!");
124        let token = mgr.get_token("comment").expect("token");
125        assert_eq!(token.id(), "comment");
126        assert!(token.value().contains('.'));
127        assert!(mgr.is_token_valid(&token));
128        let forged = CsrfToken::new("comment", "deadbeef.badmac");
129        assert!(!mgr.is_token_valid(&forged));
130        let wrong_id = CsrfToken::new("other", token.value());
131        assert!(!mgr.is_token_valid(&wrong_id));
132    }
133
134    #[test]
135    fn rejects_malformed_token_values() {
136        let mgr = HmacCsrfTokenManager::new(b"test-secret-key-32bytes-minimum!!");
137        assert!(!mgr.is_token_valid(&CsrfToken::new("id", "nodot")));
138        assert!(!mgr.is_token_valid(&CsrfToken::new("id", ".mac")));
139        assert!(!mgr.is_token_valid(&CsrfToken::new("id", "nonce.")));
140        assert!(!mgr.is_token_valid(&CsrfToken::new("id", ".")));
141    }
142}