1use serde::{Deserialize, Serialize};
16use sha2::{Digest, Sha256};
17
18pub const CACHE_FORMAT_VERSION: u32 = 1;
20
21const MAGIC: &[u8] = b"LIBTEA-CACHE 1\n";
22const LEN_FIELD: usize = 11;
25pub const MAX_META_BYTES: usize = 64 * 1024;
27const MAX_HEADERS: usize = 16;
28const MAX_HEADER_VALUE: usize = 8 * 1024;
29
30pub 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#[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#[derive(Debug, Clone, Default, PartialEq, Eq)]
55#[non_exhaustive]
56pub struct CacheControl {
57 pub no_store: bool,
59 pub private: bool,
61 pub no_cache: bool,
63 pub max_age: Option<u64>,
65}
66
67impl CacheControl {
68 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106#[non_exhaustive]
107pub enum NotStored {
108 Status,
110 NoStore,
112 Private,
114 Authenticated,
116 VaryStar,
118}
119
120pub 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#[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 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#[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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
276#[serde(rename_all = "camelCase", deny_unknown_fields)]
277#[non_exhaustive]
278pub struct CacheEntryMeta {
279 pub version: u32,
281 pub key: String,
283 pub request_url: String,
285 pub status: u16,
287 pub stored_at: u64,
289 pub validated_at: u64,
291 pub decoded: bool,
293 pub headers: Vec<(String, String)>,
295 pub body_len: u64,
297 pub body_sha256: String,
299}
300
301impl CacheEntryMeta {
302 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
344#[non_exhaustive]
345pub enum EntryError {
346 Format,
348 Meta,
350 KeyMismatch,
352 Body,
354 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
372pub 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 #[must_use]
390 pub fn new() -> Self {
391 Self {
392 hasher: Sha256::new(),
393 len: 0,
394 }
395 }
396
397 #[must_use]
399 pub fn prefix() -> &'static [u8] {
400 MAGIC
401 }
402
403 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 #[must_use]
411 pub fn len(&self) -> u64 {
412 self.len
413 }
414
415 #[must_use]
417 pub fn is_empty(&self) -> bool {
418 self.len == 0
419 }
420
421 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
441pub 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
457pub 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 for cut in 0..good.len() {
613 assert!(
614 decode_entry(&good[..cut], &key(), 1 << 20).is_err(),
615 "cut {cut}"
616 );
617 }
618 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 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 assert_eq!(
634 decode_entry(&good, &key(), 3).unwrap_err(),
635 EntryError::TooLarge
636 );
637 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 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 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}