use hmac::{Hmac, KeyInit, Mac};
use sha2::Sha256;
use subtle::ConstantTimeEq;
type HmacSha256 = Hmac<Sha256>;
pub fn csrf_hash(token: &str, secret: &str) -> String {
let mut mac = <HmacSha256 as KeyInit>::new_from_slice(secret.as_bytes())
.expect("HMAC accepts keys of any length");
mac.update(token.as_bytes());
mac.update(secret.as_bytes());
hex::encode(mac.finalize().into_bytes())
}
pub fn verify_csrf(cookie_value: &str, body_token: &str, secret: &str) -> (String, bool) {
let Some((token, signature)) = cookie_value.split_once('|') else {
return (String::new(), false);
};
let expected = csrf_hash(token, secret);
if !bool::from(signature.as_bytes().ct_eq(expected.as_bytes())) {
return (token.to_string(), false);
}
if body_token.is_empty() {
return (token.to_string(), false);
}
if !bool::from(body_token.as_bytes().ct_eq(token.as_bytes())) {
return (token.to_string(), false);
}
(token.to_string(), true)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn verify_csrf_accepts_only_matching_signed_pairs() {
const SECRET: &str = "test-secret";
const TOKEN: &str = "random-token";
let cookie = format!("{TOKEN}|{}", csrf_hash(TOKEN, SECRET));
let cases: &[(&str, &str, &str, bool)] = &[
("valid cookie and body", &cookie, TOKEN, true),
("body token mismatch", &cookie, "other-token", false),
("missing body token", &cookie, "", false),
("tampered signature", "random-token|deadbeef", TOKEN, false),
("malformed cookie", "no-separator", TOKEN, false),
("empty cookie", "", TOKEN, false),
];
for (name, cookie, body, want_valid) in cases {
let (_, valid) = verify_csrf(cookie, body, SECRET);
assert_eq!(valid, *want_valid, "{name}");
}
}
}