Skip to main content

strata_web_api/
cookie.rs

1//! RFC 6265 HTTP State Management Mechanism (Cookie Jar & Attributes).
2//!
3//! Provides:
4//! - Full parsing of `Set-Cookie` headers with attributes:
5//!   `Expires`, `Max-Age`, `Domain`, `Path`, `Secure`, `HttpOnly`, `SameSite`.
6//! - Pure-Rust HTTP date parser (RFC 1123, RFC 850, asctime) with leap-year handling.
7//! - RFC 6265 domain matching, path matching, and security domain boundaries.
8//! - Thread-safe, serializable `CookieJar` with automatic cookie injection into requests
9//!   and response extraction.
10
11use crate::fetch::{Headers, ParsedUrl};
12use serde::{Deserialize, Serialize};
13use std::path::Path;
14
15/// Cookie SameSite policy attribute.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
17pub enum SameSite {
18    Strict,
19    #[default]
20    Lax,
21    None,
22}
23
24/// An authentic RFC 6265 HTTP Cookie.
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26pub struct Cookie {
27    pub name: String,
28    pub value: String,
29    pub domain: String,
30    pub path: String,
31    pub expires: Option<u64>,
32    pub max_age: Option<i64>,
33    pub secure: bool,
34    pub http_only: bool,
35    pub same_site: SameSite,
36    pub host_only: bool,
37    pub created_at: u64,
38    pub last_accessed: u64,
39}
40
41impl Cookie {
42    /// Constructs a basic cookie with default path "/" and current timestamp.
43    pub fn new(
44        name: impl Into<String>,
45        value: impl Into<String>,
46        domain: impl Into<String>,
47    ) -> Self {
48        let now = current_time_secs();
49        Self {
50            name: name.into(),
51            value: value.into(),
52            domain: domain.into().to_ascii_lowercase(),
53            path: "/".to_string(),
54            expires: None,
55            max_age: None,
56            secure: false,
57            http_only: false,
58            same_site: SameSite::Lax,
59            host_only: true,
60            created_at: now,
61            last_accessed: now,
62        }
63    }
64
65    /// Parses a `Set-Cookie` response header string in the context of an HTTP request URL.
66    pub fn parse(header_value: &str, request_url: &str) -> Option<Self> {
67        let parsed_url = ParsedUrl::parse(request_url).ok()?;
68        Self::parse_with_context(header_value, &parsed_url, current_time_secs())
69    }
70
71    /// Parses a `Set-Cookie` string with an explicit timestamp and parsed request URL.
72    pub fn parse_with_context(
73        header_value: &str,
74        parsed_url: &ParsedUrl,
75        now: u64,
76    ) -> Option<Self> {
77        let mut parts = header_value.split(';');
78        let name_value = parts.next()?.trim();
79        let (name, value) = name_value.split_once('=')?;
80        let name = name.trim().to_string();
81        let value = value.trim().to_string();
82        if name.is_empty() {
83            return None;
84        }
85
86        let mut domain: Option<String> = None;
87        let mut path: Option<String> = None;
88        let mut expires: Option<u64> = None;
89        let mut max_age: Option<i64> = None;
90        let mut secure = false;
91        let mut http_only = false;
92        let mut same_site = SameSite::Lax;
93
94        for part in parts {
95            let part = part.trim();
96            if part.is_empty() {
97                continue;
98            }
99            if let Some((attr_name, attr_val)) = part.split_once('=') {
100                let attr_name = attr_name.trim().to_ascii_lowercase();
101                let attr_val = attr_val.trim();
102                match attr_name.as_str() {
103                    "domain" => {
104                        let d = attr_val.trim_start_matches('.').to_ascii_lowercase();
105                        if !d.is_empty() && can_set_cookie_domain(&parsed_url.host, &d) {
106                            domain = Some(d);
107                        }
108                    }
109                    "path" => {
110                        if attr_val.starts_with('/') {
111                            path = Some(attr_val.to_string());
112                        }
113                    }
114                    "expires" => {
115                        if let Some(exp_secs) = parse_http_date(attr_val) {
116                            // Max-Age takes precedence over Expires if both specified (RFC 6265 §5.3)
117                            if max_age.is_none() {
118                                expires = Some(exp_secs);
119                            }
120                        }
121                    }
122                    "max-age" => {
123                        if let Ok(delta) = attr_val.parse::<i64>() {
124                            max_age = Some(delta);
125                            let exp = if delta <= 0 {
126                                0
127                            } else {
128                                now.saturating_add(delta as u64)
129                            };
130                            expires = Some(exp);
131                        }
132                    }
133                    "samesite" => {
134                        let lower = attr_val.to_ascii_lowercase();
135                        if lower == "strict" {
136                            same_site = SameSite::Strict;
137                        } else if lower == "none" {
138                            same_site = SameSite::None;
139                        } else {
140                            same_site = SameSite::Lax;
141                        }
142                    }
143                    _ => {}
144                }
145            } else {
146                let flag = part.to_ascii_lowercase();
147                match flag.as_str() {
148                    "secure" => secure = true,
149                    "httponly" => http_only = true,
150                    _ => {}
151                }
152            }
153        }
154
155        let (final_domain, host_only) = match domain {
156            Some(d) => (d, false),
157            None => (parsed_url.host.to_ascii_lowercase(), true),
158        };
159
160        let final_path = match path {
161            Some(p) => p,
162            None => default_path_for_request(&parsed_url.path_and_query),
163        };
164
165        Some(Self {
166            name,
167            value,
168            domain: final_domain,
169            path: final_path,
170            expires,
171            max_age,
172            secure,
173            http_only,
174            same_site,
175            host_only,
176            created_at: now,
177            last_accessed: now,
178        })
179    }
180
181    /// Evaluates whether this cookie has expired relative to `now` timestamp in seconds.
182    pub fn is_expired(&self, now: u64) -> bool {
183        if let Some(exp) = self.expires {
184            exp <= now
185        } else {
186            false
187        }
188    }
189
190    /// Evaluates whether this cookie matches an outgoing request URL per RFC 6265 §5.4.
191    pub fn matches_request(&self, parsed_url: &ParsedUrl, now: u64) -> bool {
192        if self.is_expired(now) {
193            return false;
194        }
195        if self.secure && parsed_url.scheme != "https" {
196            return false;
197        }
198        if !domain_matches(&parsed_url.host, &self.domain, self.host_only) {
199            return false;
200        }
201        if !path_matches(&parsed_url.path_and_query, &self.path) {
202            return false;
203        }
204        true
205    }
206}
207
208/// In-memory and persistent cookie storage conforming to RFC 6265.
209#[derive(Debug, Clone, Default, Serialize, Deserialize)]
210pub struct CookieJar {
211    cookies: Vec<Cookie>,
212}
213
214impl CookieJar {
215    /// Creates a new empty `CookieJar`.
216    pub fn new() -> Self {
217        Self {
218            cookies: Vec::new(),
219        }
220    }
221
222    /// Stores a cookie in the jar according to RFC 6265 §5.3 storage model.
223    pub fn store(&mut self, cookie: Cookie) {
224        let now = current_time_secs();
225        if cookie.is_expired(now) {
226            self.remove(&cookie.name, &cookie.domain, &cookie.path);
227            return;
228        }
229
230        if let Some(pos) = self.cookies.iter().position(|c| {
231            c.name.eq_ignore_ascii_case(&cookie.name)
232                && c.domain.eq_ignore_ascii_case(&cookie.domain)
233                && c.path == cookie.path
234        }) {
235            let mut updated = cookie;
236            // Preserve original creation timestamp (RFC 6265 §5.3 step 11)
237            updated.created_at = self.cookies[pos].created_at;
238            self.cookies[pos] = updated;
239        } else {
240            self.cookies.push(cookie);
241        }
242    }
243
244    /// Parses and stores a `Set-Cookie` header value in the context of an HTTP request URL.
245    pub fn process_set_cookie(&mut self, set_cookie_str: &str, request_url: &str) {
246        if let Some(cookie) = Cookie::parse(set_cookie_str, request_url) {
247            self.store(cookie);
248        }
249    }
250
251    /// Processes all `Set-Cookie` headers from an HTTP response.
252    pub fn process_response_headers(&mut self, headers: &Headers, request_url: &str) {
253        for set_cookie in headers.get_all("set-cookie") {
254            self.process_set_cookie(set_cookie, request_url);
255        }
256    }
257
258    /// Generates the `Cookie` request header string for an outgoing request URL.
259    ///
260    /// Cookies are ordered per RFC 6265 §5.4: longer paths first, then earlier creation timestamps.
261    pub fn get_cookie_header_value(&mut self, request_url: &str) -> Option<String> {
262        let parsed = ParsedUrl::parse(request_url).ok()?;
263        let now = current_time_secs();
264
265        // Evict expired cookies
266        self.cookies.retain(|c| !c.is_expired(now));
267
268        // Find matching cookies
269        let mut matching: Vec<(usize, &mut Cookie)> = self
270            .cookies
271            .iter_mut()
272            .enumerate()
273            .filter(|(_, c)| c.matches_request(&parsed, now))
274            .collect();
275
276        if matching.is_empty() {
277            return None;
278        }
279
280        // Sort by path length descending, then created_at ascending
281        matching.sort_by(|(_, a), (_, b)| {
282            b.path
283                .len()
284                .cmp(&a.path.len())
285                .then_with(|| a.created_at.cmp(&b.created_at))
286        });
287
288        let mut pairs = Vec::with_capacity(matching.len());
289        for (_, cookie) in matching {
290            cookie.last_accessed = now;
291            pairs.push(format!("{}={}", cookie.name, cookie.value));
292        }
293
294        Some(pairs.join("; "))
295    }
296
297    /// Retrieves a specific cookie by exact name, domain, and path.
298    pub fn get(&self, name: &str, domain: &str, path: &str) -> Option<&Cookie> {
299        self.cookies.iter().find(|c| {
300            c.name.eq_ignore_ascii_case(name)
301                && c.domain.eq_ignore_ascii_case(domain)
302                && c.path == path
303        })
304    }
305
306    /// Removes a specific cookie matching name, domain, and path.
307    pub fn remove(&mut self, name: &str, domain: &str, path: &str) {
308        self.cookies.retain(|c| {
309            !(c.name.eq_ignore_ascii_case(name)
310                && c.domain.eq_ignore_ascii_case(domain)
311                && c.path == path)
312        });
313    }
314
315    /// Clears all cookies from the jar.
316    pub fn clear(&mut self) {
317        self.cookies.clear();
318    }
319
320    /// Evicts all expired cookies from the jar.
321    pub fn clear_expired(&mut self) {
322        let now = current_time_secs();
323        self.cookies.retain(|c| !c.is_expired(now));
324    }
325
326    /// Returns the number of cookies currently in the jar.
327    pub fn len(&self) -> usize {
328        self.cookies.len()
329    }
330
331    /// Returns `true` if the jar contains no cookies.
332    pub fn is_empty(&self) -> bool {
333        self.cookies.is_empty()
334    }
335
336    /// Returns an iterator over all cookies currently stored in the jar.
337    pub fn all_cookies(&self) -> &[Cookie] {
338        &self.cookies
339    }
340
341    /// Serializes the cookie jar into a JSON string.
342    pub fn to_json(&self) -> Result<String, serde_json::Error> {
343        serde_json::to_string_pretty(self)
344    }
345
346    /// Deserializes a cookie jar from a JSON string.
347    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
348        serde_json::from_str(json)
349    }
350
351    /// Persists all stored cookies to disk as a JSON file.
352    pub fn save_to_file(&self, path: &Path) -> Result<(), std::io::Error> {
353        if let Some(parent) = path.parent() {
354            std::fs::create_dir_all(parent)?;
355        }
356        let json = serde_json::to_string_pretty(self).map_err(std::io::Error::other)?;
357        std::fs::write(path, json)
358    }
359
360    /// Loads persisted cookies from a JSON file on disk.
361    pub fn load_from_file(path: &Path) -> Result<Self, std::io::Error> {
362        let data = std::fs::read_to_string(path)?;
363        serde_json::from_str(&data)
364            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
365    }
366}
367
368/// Computes the default path for a cookie given a request URI path per RFC 6265 §5.1.4.
369pub fn default_path_for_request(request_path: &str) -> String {
370    let path = if request_path.is_empty() {
371        "/"
372    } else {
373        request_path
374    };
375    if !path.starts_with('/') {
376        return "/".to_string();
377    }
378    match path.rfind('/') {
379        Some(0) => "/".to_string(),
380        Some(idx) => path[..idx].to_string(),
381        None => "/".to_string(),
382    }
383}
384
385/// Verifies whether `request_host` domain-matches `cookie_domain` per RFC 6265 §5.1.3.
386pub fn domain_matches(request_host: &str, cookie_domain: &str, host_only: bool) -> bool {
387    let req = request_host.trim().to_ascii_lowercase();
388    let cookie = cookie_domain
389        .trim()
390        .trim_start_matches('.')
391        .to_ascii_lowercase();
392
393    if host_only {
394        return req == cookie;
395    }
396
397    if req == cookie {
398        return true;
399    }
400
401    if req.ends_with(&format!(".{cookie}")) {
402        return true;
403    }
404
405    false
406}
407
408/// Checks whether an origin host is authorized to set a cookie for `cookie_domain`.
409pub fn can_set_cookie_domain(request_host: &str, cookie_domain: &str) -> bool {
410    let req = request_host.trim().to_ascii_lowercase();
411    let domain = cookie_domain
412        .trim()
413        .trim_start_matches('.')
414        .to_ascii_lowercase();
415    if domain.is_empty() {
416        return false;
417    }
418    // Prevent setting cookies on public suffixes or top-level domains without internal dots
419    if !domain.contains('.') {
420        return false;
421    }
422    req == domain || req.ends_with(&format!(".{domain}"))
423}
424
425/// Evaluates path matching between request path and cookie path per RFC 6265 §5.1.4.
426pub fn path_matches(request_path: &str, cookie_path: &str) -> bool {
427    let req = if request_path.is_empty() {
428        "/"
429    } else {
430        request_path
431    };
432    let c_path = if cookie_path.is_empty() {
433        "/"
434    } else {
435        cookie_path
436    };
437
438    if req == c_path {
439        return true;
440    }
441
442    if req.starts_with(c_path) {
443        if c_path.ends_with('/') {
444            return true;
445        }
446        if req.as_bytes().get(c_path.len()) == Some(&b'/') {
447            return true;
448        }
449    }
450
451    false
452}
453
454/// Parses an HTTP date string (RFC 1123, RFC 850, or asctime) into seconds since the UNIX epoch.
455pub fn parse_http_date(date_str: &str) -> Option<u64> {
456    let trimmed = date_str.trim();
457    if trimmed.is_empty() {
458        return None;
459    }
460
461    let s = if let Some((_, rest)) = trimmed.split_once(',') {
462        rest.trim()
463    } else {
464        trimmed
465    };
466
467    let mut tokens: Vec<&str> = s.split_whitespace().collect();
468    if tokens.is_empty() {
469        return None;
470    }
471
472    // Strip leading day-of-week if present without comma (e.g. asctime "Wed Jun  9 10:18:14 2021")
473    if tokens.len() >= 5
474        && parse_month_name(tokens[0]).is_none()
475        && tokens[0].parse::<u32>().is_err()
476    {
477        tokens.remove(0);
478    }
479
480    let (day, month, year, time_str) = if tokens.len() >= 2 && tokens[0].contains('-') {
481        // RFC 850: "06-Nov-94 08:49:37 GMT"
482        let mut dash_parts = tokens[0].split('-');
483        let d = dash_parts.next()?.parse::<u32>().ok()?;
484        let m = parse_month_name(dash_parts.next()?)?;
485        let y_raw = dash_parts.next()?.parse::<i32>().ok()?;
486        let y = if y_raw < 70 {
487            2000 + y_raw
488        } else {
489            1900 + y_raw
490        };
491        (d, m, y, tokens[1])
492    } else if tokens.len() >= 4 && parse_month_name(tokens[0]).is_some() {
493        // asctime: "Nov  6 08:49:37 1994"
494        let m = parse_month_name(tokens[0])?;
495        let d = tokens[1].parse::<u32>().ok()?;
496        let time = tokens[2];
497        let y = tokens[3].parse::<i32>().ok()?;
498        (d, m, y, time)
499    } else if tokens.len() >= 4 {
500        // RFC 1123: "06 Nov 1994 08:49:37 GMT"
501        let d = tokens[0].parse::<u32>().ok()?;
502        let m = parse_month_name(tokens[1])?;
503        let y = tokens[2].parse::<i32>().ok()?;
504        (d, m, y, tokens[3])
505    } else {
506        return None;
507    };
508
509    let mut time_parts = time_str.split(':');
510    let hour = time_parts.next()?.parse::<u32>().ok()?;
511    let min = time_parts.next()?.parse::<u32>().ok()?;
512    let sec = time_parts.next()?.parse::<u32>().ok()?;
513
514    if day == 0
515        || day > 31
516        || month == 0
517        || month > 12
518        || hour >= 24
519        || min >= 60
520        || sec >= 60
521        || year < 1970
522    {
523        return None;
524    }
525
526    let days = days_from_1970(year, month, day)?;
527    Some(days as u64 * 86400 + hour as u64 * 3600 + min as u64 * 60 + sec as u64)
528}
529
530fn parse_month_name(s: &str) -> Option<u32> {
531    match &s[..3.min(s.len())].to_ascii_lowercase()[..] {
532        "jan" => Some(1),
533        "feb" => Some(2),
534        "mar" => Some(3),
535        "apr" => Some(4),
536        "may" => Some(5),
537        "jun" => Some(6),
538        "jul" => Some(7),
539        "aug" => Some(8),
540        "sep" => Some(9),
541        "oct" => Some(10),
542        "nov" => Some(11),
543        "dec" => Some(12),
544        _ => None,
545    }
546}
547
548fn is_leap_year(year: i32) -> bool {
549    (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
550}
551
552fn days_from_1970(year: i32, month: u32, day: u32) -> Option<i64> {
553    if year < 1970 {
554        return None;
555    }
556    let mut total_days: i64 = 0;
557    for y in 1970..year {
558        total_days += if is_leap_year(y) { 366 } else { 365 };
559    }
560
561    let month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
562    for m in 1..month {
563        total_days += month_days[(m - 1) as usize] as i64;
564    }
565    if month > 2 && is_leap_year(year) {
566        total_days += 1;
567    }
568    total_days += (day as i64) - 1;
569    Some(total_days)
570}
571
572fn current_time_secs() -> u64 {
573    std::time::SystemTime::now()
574        .duration_since(std::time::UNIX_EPOCH)
575        .unwrap_or(std::time::Duration::from_secs(0))
576        .as_secs()
577}