Skip to main content

libtea_core/
http_cache.rs

1//! Pure pieces of the client's HTTP cache: key derivation, `Cache-Control` and
2//! `Retry-After` parsing, the storage decision, and the on-disk entry format.
3//!
4//! *Experimental until 0.9.* This module does no I/O and reads no clock; callers
5//! pass times as Unix seconds. `libtea-client` does the file work
6//! (`docs/cache.md`).
7//!
8//! **A cache entry is not a trusted statement.** The entry format carries a
9//! length and a SHA-256 of the body so that truncation and accidental
10//! corruption are detected. Anyone who can write the cache directory can write
11//! a consistent entry, so the hash is not authentication. Artifact bytes are
12//! therefore checked against the declared checksums every time they are used,
13//! and the directory is created private (`docs/cache.md`).
14
15use serde::{Deserialize, Serialize};
16use sha2::{Digest, Sha256};
17
18/// Entry layout version written and read by this crate.
19pub const CACHE_FORMAT_VERSION: u32 = 1;
20
21const MAGIC: &[u8] = b"LIBTEA-CACHE 1\n";
22/// The entry ends with `<meta JSON>\n<10 digits>\n`; this is the length of the
23/// last part.
24const LEN_FIELD: usize = 11;
25/// Largest metadata block accepted.
26pub const MAX_META_BYTES: usize = 64 * 1024;
27const MAX_HEADERS: usize = 16;
28const MAX_HEADER_VALUE: usize = 8 * 1024;
29
30/// Response headers an entry keeps, and nothing else.
31pub const STORED_HEADERS: &[&str] = &[
32    "content-type",
33    "content-encoding",
34    "etag",
35    "last-modified",
36    "cache-control",
37    "content-location",
38    "vary",
39    "repr-digest",
40];
41
42/// Whether a header may be written to an entry: allow-listed, and a value of
43/// visible ASCII (and tab) no longer than 8 KiB.
44#[must_use]
45pub fn is_storable_header(name: &str, value: &str) -> bool {
46    STORED_HEADERS.contains(&name)
47        && value.len() <= MAX_HEADER_VALUE
48        && value
49            .bytes()
50            .all(|b| b == b'\t' || (0x20..=0x7e).contains(&b))
51}
52
53/// The directives of `Cache-Control` this client acts on.
54#[derive(Debug, Clone, Default, PartialEq, Eq)]
55#[non_exhaustive]
56pub struct CacheControl {
57    /// `no-store`: nothing may be stored.
58    pub no_store: bool,
59    /// `private`: meant for a single user's cache.
60    pub private: bool,
61    /// `no-cache`: always revalidate before use.
62    pub no_cache: bool,
63    /// `max-age` in seconds; saturates instead of overflowing.
64    pub max_age: Option<u64>,
65}
66
67impl CacheControl {
68    /// Parse every `Cache-Control` header line of a response. Unknown
69    /// directives and malformed values are ignored; the strictest reading of
70    /// repeated directives wins.
71    #[must_use]
72    pub fn parse(lines: &[&str]) -> Self {
73        let mut out = Self::default();
74        for line in lines {
75            for part in line.split(',') {
76                let part = part.trim();
77                let (name, value) = match part.split_once('=') {
78                    Some((n, v)) => (n.trim(), Some(v.trim().trim_matches('"'))),
79                    None => (part, None),
80                };
81                match name.to_ascii_lowercase().as_str() {
82                    "no-store" => out.no_store = true,
83                    "private" => out.private = true,
84                    "no-cache" => out.no_cache = true,
85                    "max-age" => {
86                        if let Some(value) = value {
87                            if !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()) {
88                                let seconds = value.parse::<u64>().unwrap_or(u64::MAX);
89                                out.max_age = Some(match out.max_age {
90                                    Some(existing) => existing.min(seconds),
91                                    None => seconds,
92                                });
93                            }
94                        }
95                    }
96                    _ => {}
97                }
98            }
99        }
100        out
101    }
102}
103
104/// Why a response was not stored.
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106#[non_exhaustive]
107pub enum NotStored {
108    /// Only `200` responses are stored.
109    Status,
110    /// `Cache-Control: no-store`.
111    NoStore,
112    /// `Cache-Control: private` and shared-credential caching was not enabled.
113    Private,
114    /// The request carried credentials and authenticated caching was not enabled.
115    Authenticated,
116    /// `Vary: *`.
117    VaryStar,
118}
119
120/// Decide whether a response may be stored.
121///
122/// A private per-user cache may in principle keep `private` responses; this
123/// client keeps them only when the caller opted in to authenticated caching,
124/// the conservative reading of the F6 requirement.
125///
126/// # Errors
127///
128/// Returns the reason when the response must not be stored.
129pub fn storage_decision(
130    status: u16,
131    control: &CacheControl,
132    vary: Option<&str>,
133    request_was_authenticated: bool,
134    allow_authenticated: bool,
135) -> Result<(), NotStored> {
136    if status != 200 {
137        return Err(NotStored::Status);
138    }
139    if control.no_store {
140        return Err(NotStored::NoStore);
141    }
142    if vary.is_some_and(|v| v.split(',').any(|t| t.trim() == "*")) {
143        return Err(NotStored::VaryStar);
144    }
145    if request_was_authenticated && !allow_authenticated {
146        return Err(NotStored::Authenticated);
147    }
148    if control.private && !allow_authenticated {
149        return Err(NotStored::Private);
150    }
151    Ok(())
152}
153
154/// Seconds to wait according to a `Retry-After` value.
155///
156/// Accepts delta-seconds (digits only) or an IMF-fixdate such as
157/// `Sun, 06 Nov 1994 08:49:37 GMT`. A date in the past gives `Some(0)`.
158/// Anything else, including the obsolete date formats, gives `None`.
159#[must_use]
160pub fn parse_retry_after(value: &str, now_epoch_secs: u64) -> Option<u64> {
161    let value = value.trim();
162    if !value.is_empty() && value.len() <= 20 && value.bytes().all(|b| b.is_ascii_digit()) {
163        return Some(value.parse::<u64>().unwrap_or(u64::MAX));
164    }
165    let when = parse_imf_fixdate(value)?;
166    Some(when.saturating_sub(now_epoch_secs))
167}
168
169fn parse_imf_fixdate(value: &str) -> Option<u64> {
170    // "Sun, 06 Nov 1994 08:49:37 GMT"
171    let b = value.as_bytes();
172    if b.len() != 29 || &b[3..5] != b", " || &b[25..] != b" GMT" {
173        return None;
174    }
175    let day_names = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
176    if !day_names.contains(&&value[..3]) {
177        return None;
178    }
179    let digits = |range: std::ops::Range<usize>| -> Option<u64> {
180        let part = &value[range];
181        if part.bytes().all(|c| c.is_ascii_digit()) {
182            part.parse().ok()
183        } else {
184            None
185        }
186    };
187    let day = digits(5..7)?;
188    let month = [
189        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
190    ]
191    .iter()
192    .position(|m| *m == &value[8..11])? as u64
193        + 1;
194    let year = digits(12..16)?;
195    if b[7] != b' ' || b[11] != b' ' || b[16] != b' ' || b[19] != b':' || b[22] != b':' {
196        return None;
197    }
198    let (hour, minute, second) = (digits(17..19)?, digits(20..22)?, digits(23..25)?);
199    if !(1..=31).contains(&day) || hour > 23 || minute > 59 || second > 60 || year < 1970 {
200        return None;
201    }
202    let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
203    let month_days = [
204        31,
205        if leap { 29 } else { 28 },
206        31,
207        30,
208        31,
209        30,
210        31,
211        31,
212        30,
213        31,
214        30,
215        31,
216    ];
217    if day > month_days[(month - 1) as usize] {
218        return None;
219    }
220    let mut days = 0u64;
221    for y in 1970..year {
222        days += if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) {
223            366
224        } else {
225            365
226        };
227    }
228    days += month_days[..(month - 1) as usize].iter().sum::<u64>() + (day - 1);
229    Some(days * 86_400 + hour * 3_600 + minute * 60 + second.min(59))
230}
231
232/// The cache key of a request: lowercase hex SHA-256 over the method, the
233/// normalized URL, and a digest of the origin and the API key id (never the
234/// secret). Requests from different keys, or to different origins, never share
235/// an entry.
236///
237/// `url` should already be normalized: lowercase scheme and host, default port
238/// removed, no fragment, no userinfo. The query is part of the key verbatim.
239#[must_use]
240pub fn cache_key(method: &str, url: &str, origin: &str, key_id: Option<&str>) -> String {
241    let mut scope = Sha256::new();
242    scope.update(b"libtea-cache-scope-v1\0");
243    scope.update(origin.as_bytes());
244    scope.update(b"\0");
245    scope.update(key_id.unwrap_or("").as_bytes());
246    scope.update(b"\0");
247    scope.update([u8::from(key_id.is_some())]);
248    let mut key = Sha256::new();
249    key.update(b"libtea-cache-key-v1\0");
250    key.update(method.as_bytes());
251    key.update(b"\0");
252    key.update(url.as_bytes());
253    key.update(b"\0");
254    key.update(scope.finalize());
255    hex(&key.finalize())
256}
257
258fn hex(bytes: &[u8]) -> String {
259    use std::fmt::Write;
260    bytes
261        .iter()
262        .fold(String::with_capacity(bytes.len() * 2), |mut out, b| {
263            let _ = write!(out, "{b:02x}");
264            out
265        })
266}
267
268/// Whether `key` looks like a key produced by [`cache_key`].
269#[must_use]
270pub fn is_cache_key(key: &str) -> bool {
271    key.len() == 64 && key.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
272}
273
274/// Metadata of one stored response.
275#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
276#[serde(rename_all = "camelCase", deny_unknown_fields)]
277#[non_exhaustive]
278pub struct CacheEntryMeta {
279    /// Layout version, [`CACHE_FORMAT_VERSION`].
280    pub version: u32,
281    /// The entry's cache key; must equal the key it is looked up under.
282    pub key: String,
283    /// The request URL without query or fragment. For display only.
284    pub request_url: String,
285    /// HTTP status of the stored response.
286    pub status: u16,
287    /// When the body was first stored (Unix seconds).
288    pub stored_at: u64,
289    /// When the body was last confirmed current (Unix seconds).
290    pub validated_at: u64,
291    /// Whether the body is already free of HTTP content coding.
292    pub decoded: bool,
293    /// Allow-listed response headers.
294    pub headers: Vec<(String, String)>,
295    /// Body length in bytes (set by the encoder).
296    pub body_len: u64,
297    /// Lowercase hex SHA-256 of the body (set by the encoder).
298    pub body_sha256: String,
299}
300
301impl CacheEntryMeta {
302    /// Start metadata for a response. Headers that are not storable are dropped.
303    #[must_use]
304    pub fn new(
305        key: impl Into<String>,
306        request_url: impl Into<String>,
307        status: u16,
308        now: u64,
309        decoded: bool,
310        headers: &[(String, String)],
311    ) -> Self {
312        let headers = headers
313            .iter()
314            .filter(|(n, v)| is_storable_header(n, v))
315            .take(MAX_HEADERS)
316            .cloned()
317            .collect();
318        Self {
319            version: CACHE_FORMAT_VERSION,
320            key: key.into(),
321            request_url: request_url.into(),
322            status,
323            stored_at: now,
324            validated_at: now,
325            decoded,
326            headers,
327            body_len: 0,
328            body_sha256: String::new(),
329        }
330    }
331
332    /// A stored header value, by lowercase name.
333    #[must_use]
334    pub fn header(&self, name: &str) -> Option<&str> {
335        self.headers
336            .iter()
337            .find(|(n, _)| n == name)
338            .map(|(_, v)| v.as_str())
339    }
340}
341
342/// Why an entry was refused.
343#[derive(Debug, Clone, Copy, PartialEq, Eq)]
344#[non_exhaustive]
345pub enum EntryError {
346    /// Not an entry of this version.
347    Format,
348    /// The metadata is malformed or has an out-of-range field.
349    Meta,
350    /// The entry belongs to a different key.
351    KeyMismatch,
352    /// The body is shorter, longer or different from what the metadata states.
353    Body,
354    /// The body is larger than the caller's limit.
355    TooLarge,
356}
357
358impl std::fmt::Display for EntryError {
359    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
360        f.write_str(match self {
361            Self::Format => "not a cache entry of this version",
362            Self::Meta => "cache entry metadata is invalid",
363            Self::KeyMismatch => "cache entry belongs to another key",
364            Self::Body => "cache entry body does not match its metadata",
365            Self::TooLarge => "cache entry is larger than the limit",
366        })
367    }
368}
369
370impl std::error::Error for EntryError {}
371
372/// Builds an entry while the body is still arriving.
373///
374/// Write [`EntryBuilder::prefix`], then each body chunk (also passed to
375/// [`EntryBuilder::update`]), then [`EntryBuilder::trailer`].
376pub struct EntryBuilder {
377    hasher: Sha256,
378    len: u64,
379}
380
381impl Default for EntryBuilder {
382    fn default() -> Self {
383        Self::new()
384    }
385}
386
387impl EntryBuilder {
388    /// Start an entry.
389    #[must_use]
390    pub fn new() -> Self {
391        Self {
392            hasher: Sha256::new(),
393            len: 0,
394        }
395    }
396
397    /// The bytes that start every entry.
398    #[must_use]
399    pub fn prefix() -> &'static [u8] {
400        MAGIC
401    }
402
403    /// Account for one body chunk.
404    pub fn update(&mut self, chunk: &[u8]) {
405        self.hasher.update(chunk);
406        self.len = self.len.saturating_add(chunk.len() as u64);
407    }
408
409    /// Body bytes seen so far.
410    #[must_use]
411    pub fn len(&self) -> u64 {
412        self.len
413    }
414
415    /// Whether no body byte was seen.
416    #[must_use]
417    pub fn is_empty(&self) -> bool {
418        self.len == 0
419    }
420
421    /// The bytes that end the entry: the metadata (with length and digest
422    /// filled in) and its length.
423    ///
424    /// # Errors
425    ///
426    /// Returns an error when the metadata cannot be serialised or is too large.
427    pub fn trailer(self, mut meta: CacheEntryMeta) -> Result<Vec<u8>, EntryError> {
428        meta.body_len = self.len;
429        meta.body_sha256 = hex(&self.hasher.finalize());
430        let mut json = serde_json::to_vec(&meta).map_err(|_| EntryError::Meta)?;
431        if json.len() > MAX_META_BYTES {
432            return Err(EntryError::Meta);
433        }
434        let length = json.len();
435        json.push(b'\n');
436        json.extend_from_slice(format!("{length:010}\n").as_bytes());
437        Ok(json)
438    }
439}
440
441/// Encode a whole entry in memory.
442///
443/// # Errors
444///
445/// Returns an error when the metadata cannot be serialised or is too large.
446pub fn encode_entry(meta: CacheEntryMeta, body: &[u8]) -> Result<Vec<u8>, EntryError> {
447    let mut builder = EntryBuilder::new();
448    builder.update(body);
449    let trailer = builder.trailer(meta)?;
450    let mut out = Vec::with_capacity(MAGIC.len() + body.len() + trailer.len());
451    out.extend_from_slice(MAGIC);
452    out.extend_from_slice(body);
453    out.extend_from_slice(&trailer);
454    Ok(out)
455}
456
457/// Decode and check an entry.
458///
459/// The key must equal `expect_key`, the body must have exactly the stated
460/// length and SHA-256, and no field may be out of range. Nothing in the entry
461/// is believed beyond that: see the module documentation.
462///
463/// # Errors
464///
465/// Returns why the entry was refused.
466pub fn decode_entry(
467    bytes: &[u8],
468    expect_key: &str,
469    max_body: usize,
470) -> Result<(CacheEntryMeta, Vec<u8>), EntryError> {
471    if !bytes.starts_with(MAGIC) || bytes.len() < MAGIC.len() + LEN_FIELD + 2 {
472        return Err(EntryError::Format);
473    }
474    let end = bytes.len();
475    let len_field = &bytes[end - LEN_FIELD..];
476    if len_field[10] != b'\n' || !len_field[..10].iter().all(u8::is_ascii_digit) {
477        return Err(EntryError::Format);
478    }
479    let meta_len: usize = std::str::from_utf8(&len_field[..10])
480        .ok()
481        .and_then(|s| s.parse().ok())
482        .ok_or(EntryError::Format)?;
483    if meta_len == 0 || meta_len > MAX_META_BYTES || meta_len + 1 + LEN_FIELD + MAGIC.len() > end {
484        return Err(EntryError::Meta);
485    }
486    let meta_end = end - LEN_FIELD - 1;
487    if bytes[meta_end] != b'\n' {
488        return Err(EntryError::Format);
489    }
490    let meta_start = meta_end - meta_len;
491    let meta: CacheEntryMeta =
492        serde_json::from_slice(&bytes[meta_start..meta_end]).map_err(|_| EntryError::Meta)?;
493    check_meta(&meta)?;
494    if meta.key != expect_key {
495        return Err(EntryError::KeyMismatch);
496    }
497    let body = &bytes[MAGIC.len()..meta_start];
498    if usize::try_from(meta.body_len) != Ok(body.len()) {
499        return Err(EntryError::Body);
500    }
501    if body.len() > max_body {
502        return Err(EntryError::TooLarge);
503    }
504    if hex(&Sha256::digest(body)) != meta.body_sha256 {
505        return Err(EntryError::Body);
506    }
507    Ok((meta, body.to_vec()))
508}
509
510fn check_meta(meta: &CacheEntryMeta) -> Result<(), EntryError> {
511    let ok = meta.version == CACHE_FORMAT_VERSION
512        && is_cache_key(&meta.key)
513        && (100..=599).contains(&meta.status)
514        && meta.validated_at >= meta.stored_at
515        && meta.request_url.len() <= 2048
516        && meta.headers.len() <= MAX_HEADERS
517        && meta.headers.iter().all(|(n, v)| is_storable_header(n, v))
518        && meta.body_sha256.len() == 64
519        && meta
520            .body_sha256
521            .bytes()
522            .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
523    if ok {
524        Ok(())
525    } else {
526        Err(EntryError::Meta)
527    }
528}
529
530#[cfg(test)]
531mod tests {
532    use super::*;
533
534    const URL: &str = "https://tea.example.com/v1.0.0/product/1";
535
536    fn key() -> String {
537        cache_key("GET", URL, "https://tea.example.com", None)
538    }
539
540    fn meta() -> CacheEntryMeta {
541        CacheEntryMeta::new(
542            key(),
543            "https://tea.example.com/v1.0.0/product/1",
544            200,
545            1_000,
546            false,
547            &[
548                ("etag".into(), "\"abc\"".into()),
549                ("content-type".into(), "application/json".into()),
550                ("set-cookie".into(), "dropped=1".into()),
551                ("x-secret".into(), "dropped".into()),
552            ],
553        )
554    }
555
556    #[test]
557    fn keys_depend_on_method_url_origin_and_key_id_and_nothing_else() {
558        let base = cache_key("GET", URL, "https://a", Some("id-1"));
559        assert!(is_cache_key(&base));
560        assert_eq!(base, cache_key("GET", URL, "https://a", Some("id-1")));
561        for other in [
562            cache_key("HEAD", URL, "https://a", Some("id-1")),
563            cache_key(
564                "GET",
565                "https://tea.example.com/v1.0.0/product/2",
566                "https://a",
567                Some("id-1"),
568            ),
569            cache_key("GET", URL, "https://b", Some("id-1")),
570            cache_key("GET", URL, "https://a", Some("id-2")),
571            cache_key("GET", URL, "https://a", None),
572            cache_key("GET", URL, "https://a", Some("")),
573        ] {
574            assert_ne!(base, other);
575        }
576    }
577
578    #[test]
579    fn the_key_never_contains_the_key_id() {
580        let key = cache_key("GET", URL, "https://a", Some("my-visible-key-id"));
581        assert!(!key.contains("my-visible-key-id"));
582    }
583
584    #[test]
585    fn entries_round_trip_and_drop_unlisted_headers() {
586        let bytes = encode_entry(meta(), b"{\"a\":1}").unwrap();
587        let (decoded, body) = decode_entry(&bytes, &key(), 1 << 20).unwrap();
588        assert_eq!(body, b"{\"a\":1}");
589        assert_eq!(decoded.status, 200);
590        assert_eq!(decoded.header("etag"), Some("\"abc\""));
591        assert_eq!(decoded.header("set-cookie"), None);
592        assert_eq!(decoded.header("x-secret"), None);
593        assert_eq!(decoded.body_len, 7);
594    }
595
596    #[test]
597    fn streamed_and_in_memory_entries_are_identical() {
598        let whole = encode_entry(meta(), b"hello world").unwrap();
599        let mut builder = EntryBuilder::new();
600        builder.update(b"hello ");
601        builder.update(b"world");
602        let mut streamed = EntryBuilder::prefix().to_vec();
603        streamed.extend_from_slice(b"hello world");
604        streamed.extend(builder.trailer(meta()).unwrap());
605        assert_eq!(whole, streamed);
606    }
607
608    #[test]
609    fn every_kind_of_damage_is_refused() {
610        let good = encode_entry(meta(), b"payload-bytes").unwrap();
611        // truncation at every length
612        for cut in 0..good.len() {
613            assert!(
614                decode_entry(&good[..cut], &key(), 1 << 20).is_err(),
615                "cut {cut}"
616            );
617        }
618        // A flipped bit in the magic or the body is caught. (The timestamps in
619        // the metadata are not covered by the body digest and are not trusted.)
620        let body_at = EntryBuilder::prefix().len();
621        for at in (0..body_at).chain(body_at..body_at + 13) {
622            let mut bad = good.clone();
623            bad[at] ^= 0x01;
624            assert!(decode_entry(&bad, &key(), 1 << 20).is_err(), "flip at {at}");
625        }
626        // another key
627        let other = cache_key("GET", "https://x/y", "https://x", None);
628        assert_eq!(
629            decode_entry(&good, &other, 1 << 20).unwrap_err(),
630            EntryError::KeyMismatch
631        );
632        // too large
633        assert_eq!(
634            decode_entry(&good, &key(), 3).unwrap_err(),
635            EntryError::TooLarge
636        );
637        // garbage
638        for junk in [
639            &b""[..],
640            b"LIBTEA-CACHE 1\n",
641            b"\x00\x01\x02",
642            &[b'a'; 4096],
643        ] {
644            assert!(decode_entry(junk, &key(), 1 << 20).is_err());
645        }
646    }
647
648    #[test]
649    fn hostile_metadata_is_refused() {
650        let body = b"x";
651        let mut bad = meta();
652        bad.status = 99;
653        assert!(decode_entry(&encode_entry(bad, body).unwrap(), &key(), 10).is_err());
654        let mut bad = meta();
655        bad.validated_at = 1;
656        assert!(decode_entry(&encode_entry(bad, body).unwrap(), &key(), 10).is_err());
657        let mut bad = meta();
658        bad.headers.push(("set-cookie".into(), "a=b".into()));
659        assert!(decode_entry(&encode_entry(bad, body).unwrap(), &key(), 10).is_err());
660        let mut bad = meta();
661        bad.headers = vec![("etag".into(), "a\u{1b}[31m".into())];
662        assert!(decode_entry(&encode_entry(bad, body).unwrap(), &key(), 10).is_err());
663        let mut bad = meta();
664        bad.request_url = "x".repeat(5000);
665        assert!(decode_entry(&encode_entry(bad, body).unwrap(), &key(), 10).is_err());
666        let mut bad = meta();
667        bad.headers = vec![("etag".into(), "x".repeat(9000))];
668        // an oversized value is dropped when the metadata is built...
669        assert!(CacheEntryMeta::new(key(), "u", 200, 1, false, &bad.headers)
670            .headers
671            .is_empty());
672    }
673
674    #[test]
675    fn cache_control_is_parsed_defensively() {
676        let p = |lines: &[&str]| CacheControl::parse(lines);
677        assert!(p(&["no-store"]).no_store);
678        assert!(p(&["max-age=5, No-Store"]).no_store);
679        assert!(p(&["public", "private"]).private);
680        assert!(p(&["NO-CACHE"]).no_cache);
681        assert_eq!(p(&["max-age=60"]).max_age, Some(60));
682        assert_eq!(p(&["max-age=\"60\""]).max_age, Some(60));
683        assert_eq!(p(&["max-age=60", "max-age=10"]).max_age, Some(10));
684        assert_eq!(
685            p(&["max-age=99999999999999999999999999"]).max_age,
686            Some(u64::MAX)
687        );
688        for junk in [
689            "max-age=-1",
690            "max-age=",
691            "max-age=1e3",
692            "max-age= ",
693            "=",
694            ",,,",
695            "max-age=1 2",
696        ] {
697            assert_eq!(p(&[junk]).max_age, None, "{junk}");
698        }
699        assert_eq!(p(&["no-store-ish"]), CacheControl::default());
700        assert_eq!(p(&[]), CacheControl::default());
701    }
702
703    #[test]
704    fn storage_decision_follows_the_rules() {
705        let none = CacheControl::default();
706        let go =
707            |cc: &CacheControl, vary, auth, allow| storage_decision(200, cc, vary, auth, allow);
708        assert_eq!(go(&none, None, false, false), Ok(()));
709        assert_eq!(
710            storage_decision(404, &none, None, false, false),
711            Err(NotStored::Status)
712        );
713        assert_eq!(
714            storage_decision(304, &none, None, false, false),
715            Err(NotStored::Status)
716        );
717        let no_store = CacheControl::parse(&["no-store"]);
718        assert_eq!(go(&no_store, None, false, true), Err(NotStored::NoStore));
719        let private = CacheControl::parse(&["private"]);
720        assert_eq!(go(&private, None, false, false), Err(NotStored::Private));
721        assert_eq!(go(&private, None, false, true), Ok(()));
722        assert_eq!(go(&none, None, true, false), Err(NotStored::Authenticated));
723        assert_eq!(go(&none, None, true, true), Ok(()));
724        assert_eq!(
725            go(&none, Some("Accept-Encoding, *"), false, true),
726            Err(NotStored::VaryStar)
727        );
728        assert_eq!(go(&none, Some("Accept-Encoding"), false, false), Ok(()));
729    }
730
731    #[test]
732    fn retry_after_accepts_seconds_and_http_dates_only() {
733        assert_eq!(parse_retry_after("120", 0), Some(120));
734        assert_eq!(parse_retry_after(" 7 ", 0), Some(7));
735        assert_eq!(parse_retry_after("0", 0), Some(0));
736        assert_eq!(parse_retry_after("99999999999999999999", 0), Some(u64::MAX));
737        // 1994-11-06T08:49:37Z is 784111777.
738        assert_eq!(
739            parse_retry_after("Sun, 06 Nov 1994 08:49:37 GMT", 784_111_700),
740            Some(77)
741        );
742        assert_eq!(
743            parse_retry_after("Sun, 06 Nov 1994 08:49:37 GMT", 784_111_777),
744            Some(0)
745        );
746        assert_eq!(
747            parse_retry_after("Sun, 06 Nov 1994 08:49:37 GMT", 900_000_000),
748            Some(0)
749        );
750        assert_eq!(
751            parse_retry_after("Thu, 01 Jan 1970 00:00:00 GMT", 0),
752            Some(0)
753        );
754        assert_eq!(
755            parse_retry_after("Thu, 29 Feb 2024 12:00:00 GMT", 1_709_208_000 - 30),
756            Some(30)
757        );
758        for bad in [
759            "",
760            "-5",
761            "1.5",
762            "5s",
763            "1e3",
764            "Sunday, 06-Nov-94 08:49:37 GMT",
765            "Sun Nov  6 08:49:37 1994",
766            "Sun, 31 Feb 2023 00:00:00 GMT",
767            "Sun, 06 Nov 1994 25:00:00 GMT",
768            "Xyz, 06 Nov 1994 08:49:37 GMT",
769            "Sun, 06 Nov 1994 08:49:37 UTC",
770            "Sun, 06 Nov 1969 00:00:00 GMT",
771            "Sun, 00 Nov 1994 00:00:00 GMT",
772        ] {
773            assert_eq!(parse_retry_after(bad, 0), None, "{bad:?}");
774        }
775    }
776}