1use std::sync::Arc;
4
5use adk_core::subject::VisitorId;
6use chrono::{Duration, Utc};
7use hmac::{Hmac, Mac};
8use sha2::Sha256;
9
10pub const VISITOR_COOKIE: &str = "__Host-adk_visitor";
13
14#[derive(Clone)]
40pub struct VisitorTokens {
41 keys: Vec<Arc<[u8]>>,
42 ttl: Duration,
43}
44
45impl std::fmt::Debug for VisitorTokens {
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 f.debug_struct("VisitorTokens")
48 .field("keys", &self.keys.len())
49 .field("ttl", &self.ttl)
50 .finish()
51 }
52}
53
54impl VisitorTokens {
55 pub fn new(key: impl Into<Arc<[u8]>>) -> Self {
57 Self { keys: vec![key.into()], ttl: Duration::days(30) }
58 }
59
60 #[must_use]
62 pub fn with_previous_key(mut self, key: impl Into<Arc<[u8]>>) -> Self {
63 self.keys.push(key.into());
64 self
65 }
66
67 #[must_use]
69 pub fn with_ttl(mut self, ttl: Duration) -> Self {
70 self.ttl = ttl;
71 self
72 }
73
74 pub fn ttl(&self) -> Duration {
76 self.ttl
77 }
78
79 fn mac(key: &[u8], payload: &str) -> String {
80 let mut mac = Hmac::<Sha256>::new_from_slice(key).expect("HMAC takes any key length");
81 mac.update(payload.as_bytes());
82 mac.finalize().into_bytes().iter().map(|byte| format!("{byte:02x}")).collect()
83 }
84
85 pub fn issue(&self, visitor: &VisitorId) -> String {
87 let expiry = (Utc::now() + self.ttl).timestamp();
88 let payload = format!("v1.{visitor}.{expiry}");
89 let mac = Self::mac(&self.keys[0], &payload);
90 format!("{payload}.{mac}")
91 }
92
93 pub fn verify(&self, token: &str) -> Option<VisitorId> {
95 let (payload, mac) = token.trim().rsplit_once('.')?;
96 let signed = self.keys.iter().any(|key| {
97 let expected = Self::mac(key, payload);
98 expected.len() == mac.len()
99 && expected.bytes().zip(mac.bytes()).fold(0_u8, |acc, (a, b)| acc | (a ^ b)) == 0
100 });
101 if !signed {
102 return None;
103 }
104 let mut parts = payload.split('.');
105 let (Some("v1"), Some(visitor), Some(expiry), None) =
106 (parts.next(), parts.next(), parts.next(), parts.next())
107 else {
108 return None;
109 };
110 if expiry.parse::<i64>().ok()? < Utc::now().timestamp() {
111 return None;
112 }
113 visitor.parse().ok()
114 }
115
116 pub fn set_cookie(&self, token: &str) -> String {
120 format!(
121 "{VISITOR_COOKIE}={token}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age={}",
122 self.ttl.num_seconds()
123 )
124 }
125
126 pub fn from_cookie_header(header: &str) -> Option<&str> {
128 header.split(';').find_map(|pair| {
129 let (name, value) = pair.trim().split_once('=')?;
130 (name == VISITOR_COOKIE).then_some(value)
131 })
132 }
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 #[test]
140 fn tokens_verify_until_they_expire_and_never_across_keys() {
141 let tokens = VisitorTokens::new(vec![7_u8; 32]);
142 let visitor = VisitorId::generate();
143 let token = tokens.issue(&visitor);
144 assert_eq!(tokens.verify(&token), Some(visitor.clone()));
145 assert_eq!(VisitorTokens::new(vec![8_u8; 32]).verify(&token), None);
146 let expired = VisitorTokens::new(vec![7_u8; 32]).with_ttl(Duration::seconds(-60));
147 assert_eq!(tokens.verify(&expired.issue(&visitor)), None);
148 assert_eq!(tokens.verify("v1.subj_1.99999999999.00"), None);
149
150 let cookie = tokens.set_cookie(&token);
151 assert!(cookie.starts_with("__Host-adk_visitor=v1.v:"));
152 assert!(cookie.contains("Secure; HttpOnly; SameSite=Lax"));
153 let header = format!("theme=dark; {VISITOR_COOKIE}={token}; lang=sw");
154 assert_eq!(VisitorTokens::from_cookie_header(&header), Some(token.as_str()));
155 }
156}