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 || !value.is_ascii() || &b[3..5] != b", " || &b[25..] != b" GMT" {
174 return None;
175 }
176 let day_names = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
177 if !day_names.contains(&&value[..3]) {
178 return None;
179 }
180 let digits = |range: std::ops::Range<usize>| -> Option<u64> {
181 let part = &value[range];
182 if part.bytes().all(|c| c.is_ascii_digit()) {
183 part.parse().ok()
184 } else {
185 None
186 }
187 };
188 let day = digits(5..7)?;
189 let month = [
190 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
191 ]
192 .iter()
193 .position(|m| *m == &value[8..11])? as u64
194 + 1;
195 let year = digits(12..16)?;
196 if b[7] != b' ' || b[11] != b' ' || b[16] != b' ' || b[19] != b':' || b[22] != b':' {
197 return None;
198 }
199 let (hour, minute, second) = (digits(17..19)?, digits(20..22)?, digits(23..25)?);
200 if !(1..=31).contains(&day) || hour > 23 || minute > 59 || second > 60 || year < 1970 {
201 return None;
202 }
203 let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
204 let month_days = [
205 31,
206 if leap { 29 } else { 28 },
207 31,
208 30,
209 31,
210 30,
211 31,
212 31,
213 30,
214 31,
215 30,
216 31,
217 ];
218 if day > month_days[(month - 1) as usize] {
219 return None;
220 }
221 let mut days = 0u64;
222 for y in 1970..year {
223 days += if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) {
224 366
225 } else {
226 365
227 };
228 }
229 days += month_days[..(month - 1) as usize].iter().sum::<u64>() + (day - 1);
230 Some(days * 86_400 + hour * 3_600 + minute * 60 + second.min(59))
231}
232
233#[must_use]
241pub fn cache_key(method: &str, url: &str, origin: &str, key_id: Option<&str>) -> String {
242 let mut scope = Sha256::new();
243 scope.update(b"libtea-cache-scope-v1\0");
244 scope.update(origin.as_bytes());
245 scope.update(b"\0");
246 scope.update(key_id.unwrap_or("").as_bytes());
247 scope.update(b"\0");
248 scope.update([u8::from(key_id.is_some())]);
249 let mut key = Sha256::new();
250 key.update(b"libtea-cache-key-v1\0");
251 key.update(method.as_bytes());
252 key.update(b"\0");
253 key.update(url.as_bytes());
254 key.update(b"\0");
255 key.update(scope.finalize());
256 hex(&key.finalize())
257}
258
259fn hex(bytes: &[u8]) -> String {
260 use std::fmt::Write;
261 bytes
262 .iter()
263 .fold(String::with_capacity(bytes.len() * 2), |mut out, b| {
264 let _ = write!(out, "{b:02x}");
265 out
266 })
267}
268
269#[must_use]
271pub fn is_cache_key(key: &str) -> bool {
272 key.len() == 64 && key.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
273}
274
275#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
277#[serde(rename_all = "camelCase", deny_unknown_fields)]
278#[non_exhaustive]
279pub struct CacheEntryMeta {
280 pub version: u32,
282 pub key: String,
284 pub request_url: String,
286 pub status: u16,
288 pub stored_at: u64,
290 pub validated_at: u64,
292 pub decoded: bool,
294 pub headers: Vec<(String, String)>,
296 pub body_len: u64,
298 pub body_sha256: String,
300}
301
302impl CacheEntryMeta {
303 #[must_use]
305 pub fn new(
306 key: impl Into<String>,
307 request_url: impl Into<String>,
308 status: u16,
309 now: u64,
310 decoded: bool,
311 headers: &[(String, String)],
312 ) -> Self {
313 let headers = headers
314 .iter()
315 .filter(|(n, v)| is_storable_header(n, v))
316 .take(MAX_HEADERS)
317 .cloned()
318 .collect();
319 Self {
320 version: CACHE_FORMAT_VERSION,
321 key: key.into(),
322 request_url: request_url.into(),
323 status,
324 stored_at: now,
325 validated_at: now,
326 decoded,
327 headers,
328 body_len: 0,
329 body_sha256: String::new(),
330 }
331 }
332
333 #[must_use]
335 pub fn header(&self, name: &str) -> Option<&str> {
336 self.headers
337 .iter()
338 .find(|(n, _)| n == name)
339 .map(|(_, v)| v.as_str())
340 }
341}
342
343#[derive(Debug, Clone, Copy, PartialEq, Eq)]
345#[non_exhaustive]
346pub enum EntryError {
347 Format,
349 Meta,
351 KeyMismatch,
353 Body,
355 TooLarge,
357}
358
359impl std::fmt::Display for EntryError {
360 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
361 f.write_str(match self {
362 Self::Format => "not a cache entry of this version",
363 Self::Meta => "cache entry metadata is invalid",
364 Self::KeyMismatch => "cache entry belongs to another key",
365 Self::Body => "cache entry body does not match its metadata",
366 Self::TooLarge => "cache entry is larger than the limit",
367 })
368 }
369}
370
371impl std::error::Error for EntryError {}
372
373pub struct EntryBuilder {
378 hasher: Sha256,
379 len: u64,
380}
381
382impl Default for EntryBuilder {
383 fn default() -> Self {
384 Self::new()
385 }
386}
387
388impl EntryBuilder {
389 #[must_use]
391 pub fn new() -> Self {
392 Self {
393 hasher: Sha256::new(),
394 len: 0,
395 }
396 }
397
398 #[must_use]
400 pub fn prefix() -> &'static [u8] {
401 MAGIC
402 }
403
404 pub fn update(&mut self, chunk: &[u8]) {
406 self.hasher.update(chunk);
407 self.len = self.len.saturating_add(chunk.len() as u64);
408 }
409
410 #[must_use]
412 pub fn len(&self) -> u64 {
413 self.len
414 }
415
416 #[must_use]
418 pub fn is_empty(&self) -> bool {
419 self.len == 0
420 }
421
422 pub fn trailer(self, mut meta: CacheEntryMeta) -> Result<Vec<u8>, EntryError> {
429 meta.body_len = self.len;
430 meta.body_sha256 = hex(&self.hasher.finalize());
431 let mut json = serde_json::to_vec(&meta).map_err(|_| EntryError::Meta)?;
432 if json.len() > MAX_META_BYTES {
433 return Err(EntryError::Meta);
434 }
435 let length = json.len();
436 json.push(b'\n');
437 json.extend_from_slice(format!("{length:010}\n").as_bytes());
438 Ok(json)
439 }
440}
441
442pub fn encode_entry(meta: CacheEntryMeta, body: &[u8]) -> Result<Vec<u8>, EntryError> {
448 let mut builder = EntryBuilder::new();
449 builder.update(body);
450 let trailer = builder.trailer(meta)?;
451 let mut out = Vec::with_capacity(MAGIC.len() + body.len() + trailer.len());
452 out.extend_from_slice(MAGIC);
453 out.extend_from_slice(body);
454 out.extend_from_slice(&trailer);
455 Ok(out)
456}
457
458pub fn decode_entry(
468 bytes: &[u8],
469 expect_key: &str,
470 max_body: usize,
471) -> Result<(CacheEntryMeta, Vec<u8>), EntryError> {
472 if !bytes.starts_with(MAGIC) || bytes.len() < MAGIC.len() + LEN_FIELD + 2 {
473 return Err(EntryError::Format);
474 }
475 let end = bytes.len();
476 let len_field = &bytes[end - LEN_FIELD..];
477 if len_field[10] != b'\n' || !len_field[..10].iter().all(u8::is_ascii_digit) {
478 return Err(EntryError::Format);
479 }
480 let meta_len: usize = std::str::from_utf8(&len_field[..10])
481 .ok()
482 .and_then(|s| s.parse().ok())
483 .ok_or(EntryError::Format)?;
484 if meta_len == 0 || meta_len > MAX_META_BYTES || meta_len + 1 + LEN_FIELD + MAGIC.len() > end {
485 return Err(EntryError::Meta);
486 }
487 let meta_end = end - LEN_FIELD - 1;
488 if bytes[meta_end] != b'\n' {
489 return Err(EntryError::Format);
490 }
491 let meta_start = meta_end - meta_len;
492 let meta: CacheEntryMeta =
493 serde_json::from_slice(&bytes[meta_start..meta_end]).map_err(|_| EntryError::Meta)?;
494 check_meta(&meta)?;
495 if meta.key != expect_key {
496 return Err(EntryError::KeyMismatch);
497 }
498 let body = &bytes[MAGIC.len()..meta_start];
499 if usize::try_from(meta.body_len) != Ok(body.len()) {
500 return Err(EntryError::Body);
501 }
502 if body.len() > max_body {
503 return Err(EntryError::TooLarge);
504 }
505 if hex(&Sha256::digest(body)) != meta.body_sha256 {
506 return Err(EntryError::Body);
507 }
508 Ok((meta, body.to_vec()))
509}
510
511fn check_meta(meta: &CacheEntryMeta) -> Result<(), EntryError> {
512 let ok = meta.version == CACHE_FORMAT_VERSION
513 && is_cache_key(&meta.key)
514 && (100..=599).contains(&meta.status)
515 && meta.validated_at >= meta.stored_at
516 && meta.request_url.len() <= 2048
517 && meta.headers.len() <= MAX_HEADERS
518 && meta.headers.iter().all(|(n, v)| is_storable_header(n, v))
519 && meta.body_sha256.len() == 64
520 && meta
521 .body_sha256
522 .bytes()
523 .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
524 if ok {
525 Ok(())
526 } else {
527 Err(EntryError::Meta)
528 }
529}
530
531#[cfg(test)]
532mod tests {
533 use super::*;
534
535 const URL: &str = "https://tea.example.com/v1.0.0/product/1";
536
537 fn key() -> String {
538 cache_key("GET", URL, "https://tea.example.com", None)
539 }
540
541 fn meta() -> CacheEntryMeta {
542 CacheEntryMeta::new(
543 key(),
544 "https://tea.example.com/v1.0.0/product/1",
545 200,
546 1_000,
547 false,
548 &[
549 ("etag".into(), "\"abc\"".into()),
550 ("content-type".into(), "application/json".into()),
551 ("set-cookie".into(), "dropped=1".into()),
552 ("x-secret".into(), "dropped".into()),
553 ],
554 )
555 }
556
557 #[test]
558 fn keys_depend_on_method_url_origin_and_key_id_and_nothing_else() {
559 let base = cache_key("GET", URL, "https://a", Some("id-1"));
560 assert!(is_cache_key(&base));
561 assert_eq!(base, cache_key("GET", URL, "https://a", Some("id-1")));
562 for other in [
563 cache_key("HEAD", URL, "https://a", Some("id-1")),
564 cache_key(
565 "GET",
566 "https://tea.example.com/v1.0.0/product/2",
567 "https://a",
568 Some("id-1"),
569 ),
570 cache_key("GET", URL, "https://b", Some("id-1")),
571 cache_key("GET", URL, "https://a", Some("id-2")),
572 cache_key("GET", URL, "https://a", None),
573 cache_key("GET", URL, "https://a", Some("")),
574 ] {
575 assert_ne!(base, other);
576 }
577 }
578
579 #[test]
580 fn the_key_never_contains_the_key_id() {
581 let key = cache_key("GET", URL, "https://a", Some("my-visible-key-id"));
582 assert!(!key.contains("my-visible-key-id"));
583 }
584
585 #[test]
586 fn entries_round_trip_and_drop_unlisted_headers() {
587 let bytes = encode_entry(meta(), b"{\"a\":1}").unwrap();
588 let (decoded, body) = decode_entry(&bytes, &key(), 1 << 20).unwrap();
589 assert_eq!(body, b"{\"a\":1}");
590 assert_eq!(decoded.status, 200);
591 assert_eq!(decoded.header("etag"), Some("\"abc\""));
592 assert_eq!(decoded.header("set-cookie"), None);
593 assert_eq!(decoded.header("x-secret"), None);
594 assert_eq!(decoded.body_len, 7);
595 }
596
597 #[test]
598 fn streamed_and_in_memory_entries_are_identical() {
599 let whole = encode_entry(meta(), b"hello world").unwrap();
600 let mut builder = EntryBuilder::new();
601 builder.update(b"hello ");
602 builder.update(b"world");
603 let mut streamed = EntryBuilder::prefix().to_vec();
604 streamed.extend_from_slice(b"hello world");
605 streamed.extend(builder.trailer(meta()).unwrap());
606 assert_eq!(whole, streamed);
607 }
608
609 #[test]
610 fn every_kind_of_damage_is_refused() {
611 let good = encode_entry(meta(), b"payload-bytes").unwrap();
612 for cut in 0..good.len() {
614 assert!(
615 decode_entry(&good[..cut], &key(), 1 << 20).is_err(),
616 "cut {cut}"
617 );
618 }
619 let body_at = EntryBuilder::prefix().len();
622 for at in (0..body_at).chain(body_at..body_at + 13) {
623 let mut bad = good.clone();
624 bad[at] ^= 0x01;
625 assert!(decode_entry(&bad, &key(), 1 << 20).is_err(), "flip at {at}");
626 }
627 let other = cache_key("GET", "https://x/y", "https://x", None);
629 assert_eq!(
630 decode_entry(&good, &other, 1 << 20).unwrap_err(),
631 EntryError::KeyMismatch
632 );
633 assert_eq!(
635 decode_entry(&good, &key(), 3).unwrap_err(),
636 EntryError::TooLarge
637 );
638 for junk in [
640 &b""[..],
641 b"LIBTEA-CACHE 1\n",
642 b"\x00\x01\x02",
643 &[b'a'; 4096],
644 ] {
645 assert!(decode_entry(junk, &key(), 1 << 20).is_err());
646 }
647 }
648
649 #[test]
650 fn hostile_metadata_is_refused() {
651 let body = b"x";
652 let mut bad = meta();
653 bad.status = 99;
654 assert!(decode_entry(&encode_entry(bad, body).unwrap(), &key(), 10).is_err());
655 let mut bad = meta();
656 bad.validated_at = 1;
657 assert!(decode_entry(&encode_entry(bad, body).unwrap(), &key(), 10).is_err());
658 let mut bad = meta();
659 bad.headers.push(("set-cookie".into(), "a=b".into()));
660 assert!(decode_entry(&encode_entry(bad, body).unwrap(), &key(), 10).is_err());
661 let mut bad = meta();
662 bad.headers = vec![("etag".into(), "a\u{1b}[31m".into())];
663 assert!(decode_entry(&encode_entry(bad, body).unwrap(), &key(), 10).is_err());
664 let mut bad = meta();
665 bad.request_url = "x".repeat(5000);
666 assert!(decode_entry(&encode_entry(bad, body).unwrap(), &key(), 10).is_err());
667 let mut bad = meta();
668 bad.headers = vec![("etag".into(), "x".repeat(9000))];
669 assert!(CacheEntryMeta::new(key(), "u", 200, 1, false, &bad.headers)
671 .headers
672 .is_empty());
673 }
674
675 #[test]
676 fn cache_control_is_parsed_defensively() {
677 let p = |lines: &[&str]| CacheControl::parse(lines);
678 assert!(p(&["no-store"]).no_store);
679 assert!(p(&["max-age=5, No-Store"]).no_store);
680 assert!(p(&["public", "private"]).private);
681 assert!(p(&["NO-CACHE"]).no_cache);
682 assert_eq!(p(&["max-age=60"]).max_age, Some(60));
683 assert_eq!(p(&["max-age=\"60\""]).max_age, Some(60));
684 assert_eq!(p(&["max-age=60", "max-age=10"]).max_age, Some(10));
685 assert_eq!(
686 p(&["max-age=99999999999999999999999999"]).max_age,
687 Some(u64::MAX)
688 );
689 for junk in [
690 "max-age=-1",
691 "max-age=",
692 "max-age=1e3",
693 "max-age= ",
694 "=",
695 ",,,",
696 "max-age=1 2",
697 ] {
698 assert_eq!(p(&[junk]).max_age, None, "{junk}");
699 }
700 assert_eq!(p(&["no-store-ish"]), CacheControl::default());
701 assert_eq!(p(&[]), CacheControl::default());
702 }
703
704 #[test]
705 fn storage_decision_follows_the_rules() {
706 let none = CacheControl::default();
707 let go =
708 |cc: &CacheControl, vary, auth, allow| storage_decision(200, cc, vary, auth, allow);
709 assert_eq!(go(&none, None, false, false), Ok(()));
710 assert_eq!(
711 storage_decision(404, &none, None, false, false),
712 Err(NotStored::Status)
713 );
714 assert_eq!(
715 storage_decision(304, &none, None, false, false),
716 Err(NotStored::Status)
717 );
718 let no_store = CacheControl::parse(&["no-store"]);
719 assert_eq!(go(&no_store, None, false, true), Err(NotStored::NoStore));
720 let private = CacheControl::parse(&["private"]);
721 assert_eq!(go(&private, None, false, false), Err(NotStored::Private));
722 assert_eq!(go(&private, None, false, true), Ok(()));
723 assert_eq!(go(&none, None, true, false), Err(NotStored::Authenticated));
724 assert_eq!(go(&none, None, true, true), Ok(()));
725 assert_eq!(
726 go(&none, Some("Accept-Encoding, *"), false, true),
727 Err(NotStored::VaryStar)
728 );
729 assert_eq!(go(&none, Some("Accept-Encoding"), false, false), Ok(()));
730 }
731
732 #[test]
733 fn retry_after_accepts_seconds_and_http_dates_only() {
734 assert_eq!(parse_retry_after("120", 0), Some(120));
735 assert_eq!(parse_retry_after(" 7 ", 0), Some(7));
736 assert_eq!(parse_retry_after("0", 0), Some(0));
737 assert_eq!(parse_retry_after("99999999999999999999", 0), Some(u64::MAX));
738 assert_eq!(
740 parse_retry_after("Sun, 06 Nov 1994 08:49:37 GMT", 784_111_700),
741 Some(77)
742 );
743 assert_eq!(
744 parse_retry_after("Sun, 06 Nov 1994 08:49:37 GMT", 784_111_777),
745 Some(0)
746 );
747 assert_eq!(
748 parse_retry_after("Sun, 06 Nov 1994 08:49:37 GMT", 900_000_000),
749 Some(0)
750 );
751 assert_eq!(
752 parse_retry_after("Thu, 01 Jan 1970 00:00:00 GMT", 0),
753 Some(0)
754 );
755 assert_eq!(
756 parse_retry_after("Thu, 29 Feb 2024 12:00:00 GMT", 1_709_208_000 - 30),
757 Some(30)
758 );
759 for bad in [
760 "",
761 "-5",
762 "1.5",
763 "5s",
764 "1e3",
765 "Sunday, 06-Nov-94 08:49:37 GMT",
766 "Sun Nov 6 08:49:37 1994",
767 "Sun, 31 Feb 2023 00:00:00 GMT",
768 "Sun, 06 Nov 1994 25:00:00 GMT",
769 "Xyz, 06 Nov 1994 08:49:37 GMT",
770 "Sun, 06 Nov 1994 08:49:37 UTC",
771 "Sun, 06 Nov 1969 00:00:00 GMT",
772 "Sun, 00 Nov 1994 00:00:00 GMT",
773 ] {
774 assert_eq!(parse_retry_after(bad, 0), None, "{bad:?}");
775 }
776 }
777}