Skip to main content

adk_auth/
visitor.rs

1//! Tokens that carry a visitor id between a site and its visitors.
2
3use std::sync::Arc;
4
5use adk_core::subject::VisitorId;
6use chrono::{Duration, Utc};
7use hmac::{Hmac, Mac};
8use sha2::Sha256;
9
10/// The name of the cookie a site may keep a visitor token in. The `__Host-` prefix makes a
11/// browser accept it only when it is `Secure`, has no `Domain`, and has `Path=/`.
12pub const VISITOR_COOKIE: &str = "__Host-adk_visitor";
13
14/// Issues and verifies visitor tokens: `v1.{visitor id}.{expiry}.{HMAC-SHA256}`.
15///
16/// A token proves the bearer was given the visitor id; it authenticates no one. Tokens are
17/// signed with the first key and verified with every key, so a deployment rotates by adding
18/// a new first key and keeping the old one until its tokens expire. A site hands the token
19/// to the visitor in a response header or, once the visitor consents to being remembered, in
20/// the [`VISITOR_COOKIE`] cookie ([`set_cookie`](Self::set_cookie)); nothing sets a cookie by
21/// default.
22///
23/// # Example
24///
25/// ```rust
26/// use adk_auth::VisitorTokens;
27/// use adk_core::subject::VisitorId;
28///
29/// let tokens = VisitorTokens::new(b"a key of at least thirty-two bytes!!".to_vec());
30/// let visitor = VisitorId::generate();
31/// let token = tokens.issue(&visitor);
32/// assert_eq!(tokens.verify(&token), Some(visitor));
33/// assert_eq!(tokens.verify(&token.replace("v1.", "v2.")), None);
34///
35/// let rotated = VisitorTokens::new(b"the next key, also thirty-two bytes".to_vec())
36///     .with_previous_key(b"a key of at least thirty-two bytes!!".to_vec());
37/// assert!(rotated.verify(&token).is_some(), "old tokens verify during rotation");
38/// ```
39#[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    /// Tokens signed with `key`, at least 32 bytes kept by the site, lasting 30 days.
56    pub fn new(key: impl Into<Arc<[u8]>>) -> Self {
57        Self { keys: vec![key.into()], ttl: Duration::days(30) }
58    }
59
60    /// Also verifies tokens signed with `key`, an earlier key being rotated out.
61    #[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    /// Sets how long a token lasts.
68    #[must_use]
69    pub fn with_ttl(mut self, ttl: Duration) -> Self {
70        self.ttl = ttl;
71        self
72    }
73
74    /// How long a token lasts.
75    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    /// A token for `visitor`, signed with the first key.
86    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    /// The visitor id `token` carries, when a key signed it and it has not expired.
94    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    /// The `Set-Cookie` value that keeps `token` in the [`VISITOR_COOKIE`] cookie: `Secure`,
117    /// `HttpOnly`, `SameSite=Lax`, `Path=/`, expiring with the token. Set it only once the
118    /// visitor has consented to being remembered.
119    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    /// The visitor token in a `Cookie` header value, if the [`VISITOR_COOKIE`] cookie is set.
127    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}