serenade_security/
csrf.rs1use hmac::{Hmac, KeyInit, Mac};
7use sha2::Sha256;
8use subtle::ConstantTimeEq;
9
10use crate::SecurityError;
11
12type HmacSha256 = Hmac<Sha256>;
13
14pub const CSRF_FIELD_NAME: &str = "_token";
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct CsrfToken {
20 id: String,
21 value: String,
22}
23
24impl CsrfToken {
25 #[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 #[must_use]
36 pub fn id(&self) -> &str {
37 &self.id
38 }
39
40 #[must_use]
42 pub fn value(&self) -> &str {
43 &self.value
44 }
45}
46
47pub trait CsrfTokenManager: Send + Sync {
49 fn get_token(&self, token_id: &str) -> Result<CsrfToken, SecurityError>;
55
56 fn is_token_valid(&self, token: &CsrfToken) -> bool;
58}
59
60#[derive(Debug, Clone)]
62pub struct HmacCsrfTokenManager {
63 secret: Vec<u8>,
64}
65
66impl HmacCsrfTokenManager {
67 #[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 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}