Skip to main content

day_part_http/
validators.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Explicit conditional GET/HEAD for applications that store their own representations.
5use crate::{Method, Request, Response};
6
7/// Origin-supplied validators for one stored URL/representation. Keep these with the body:
8/// a 304 has no replacement body. `ETags` are opaque, including quotes and the `W/` prefix.
9#[derive(Clone, Debug, Default, PartialEq, Eq)]
10pub struct CacheValidators {
11    pub etag: Option<String>,
12    pub last_modified: Option<String>,
13}
14
15impl CacheValidators {
16    pub fn is_empty(&self) -> bool {
17        self.etag.as_deref().and_then(valid).is_none()
18            && self.last_modified.as_deref().and_then(valid).is_none()
19    }
20
21    /// Learn validators after successfully storing a 2xx representation, or merge those on
22    /// a 304 with the existing ones. Other statuses leave the cached validators unchanged.
23    /// A new 2xx without validators clears old ones; they described the previous body.
24    #[must_use]
25    pub fn updated(&self, response: &Response) -> Self {
26        let etag = response.header("etag").and_then(valid).map(str::to_owned);
27        let modified = response
28            .header("last-modified")
29            .and_then(valid)
30            .map(str::to_owned);
31        match response.status {
32            304 => Self {
33                etag: etag.or_else(|| self.etag.clone()),
34                last_modified: modified.or_else(|| self.last_modified.clone()),
35            },
36            200..=299 => Self {
37                etag,
38                last_modified: modified,
39            },
40            _ => self.clone(),
41        }
42    }
43}
44
45fn valid(value: &str) -> Option<&str> {
46    let value = value.trim();
47    (!value.is_empty() && value.len() <= 8192 && !value.bytes().any(|b| b < 0x20 || b == 0x7f))
48        .then_some(value)
49}
50
51impl Request {
52    /// Revalidate a locally stored GET/HEAD representation on every backend. Installs
53    /// `If-None-Match` and `If-Modified-Since` (ETag takes precedence at compliant servers).
54    /// Replaces existing copies of these headers. Does not add preconditions to mutations.
55    /// This is independent of the platform HTTP cache and does not turn a 304 into a 200.
56    pub fn conditional(mut self, validators: &CacheValidators) -> Self {
57        if !matches!(self.method, Method::Get | Method::Head) {
58            return self;
59        }
60        self.headers.retain(|(name, _)| {
61            !name.eq_ignore_ascii_case("if-none-match")
62                && !name.eq_ignore_ascii_case("if-modified-since")
63        });
64        if let Some(value) = validators.etag.as_deref().and_then(valid) {
65            self = self.header("If-None-Match", value);
66        }
67        if let Some(value) = validators.last_modified.as_deref().and_then(valid) {
68            self = self.header("If-Modified-Since", value);
69        }
70        self
71    }
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77    #[test]
78    fn preserves_opaque_etags_replaces_headers_and_keeps_304_metadata() {
79        let old = CacheValidators {
80            etag: Some("W/\"revision-1\"".into()),
81            last_modified: Some("Wed, 30 Sep 2026 10:00:00 GMT".into()),
82        };
83        let req = Request::get("https://fixture.example/feed")
84            .header("if-none-match", "old")
85            .conditional(&old);
86        assert_eq!(req.headers().len(), 2);
87        assert_eq!(req.headers()[0].1, "W/\"revision-1\"");
88        let response = Response::new(304, vec![("ETag".into(), "\"revision-2\"".into())], vec![]);
89        let next = old.updated(&response);
90        assert_eq!(next.etag.as_deref(), Some("\"revision-2\""));
91        assert_eq!(next.last_modified, old.last_modified);
92        assert!(old.updated(&Response::new(200, vec![], vec![])).is_empty());
93        assert_eq!(old.updated(&Response::new(503, vec![], vec![])), old);
94    }
95    #[test]
96    fn ignores_unsafe_values_and_does_not_change_mutating_requests() {
97        let validators = CacheValidators {
98            etag: Some("\"tag\"\r\nX-Injected: value".into()),
99            last_modified: Some(String::new()),
100        };
101        assert!(validators.is_empty());
102        assert_eq!(
103            Request::get("https://fixture.example")
104                .conditional(&validators)
105                .headers(),
106            []
107        );
108        let mut req = Request::get("https://fixture.example");
109        req.method = Method::Post;
110        assert_eq!(
111            req.conditional(&CacheValidators {
112                etag: Some("\"tag\"".into()),
113                last_modified: None
114            })
115            .headers(),
116            []
117        );
118    }
119}