Skip to main content

rustango_cms/api/
http_cache.rs

1//! Conditional requests and cache directives for the v2 API.
2//!
3//! Every API response used to carry no `ETag`, no `Cache-Control`, no
4//! `Last-Modified` and no `Vary`. Two consequences, one for each side:
5//!
6//! * **Clients re-transfer everything.** A SPA polling its navbar pays
7//!   the full body on every request because there is nothing to
8//!   revalidate against.
9//! * **Shared caches can leak.** `tree`, `menus/{slug}` and `detail`'s
10//!   `children` are all functions of the session cookie, and a cache
11//!   keyed on the URL alone may hand a member's response to the next
12//!   anonymous caller. The HTML path already guards against this —
13//!   `persist_locale` appends `Vary: Cookie` to every page response — but
14//!   the API router is mounted as a sibling and never saw that layer.
15//!
16//! This middleware fixes both, and it is deliberately dumb: it hashes the
17//! rendered body. No `updated_at` bookkeeping to keep in sync, no way for
18//! the validator to drift from the content, and it works for endpoints
19//! (like the tree) whose body depends on rows from four tables plus the
20//! caller's permissions. The cost is that the handler still runs — this
21//! saves bandwidth, not database work.
22
23use axum::body::Body;
24use axum::extract::Request;
25use axum::http::header::{CACHE_CONTROL, ETAG, IF_NONE_MATCH, VARY};
26use axum::http::{HeaderValue, StatusCode};
27use axum::middleware::Next;
28use axum::response::{IntoResponse, Response};
29
30/// `private` because the body depends on the caller's session, and
31/// `no-cache` because it must be revalidated rather than served blind —
32/// which is exactly what turns the `ETag` below into a 304.
33const CACHE_DIRECTIVE: &str = "private, no-cache";
34
35/// The body varies with the session cookie on every viewer-aware
36/// endpoint. Stated on all of them rather than only the ones that
37/// currently read a cookie, so adding a viewer to an endpoint later
38/// can't silently make a cached response wrong.
39const VARY_ON: &str = "Cookie";
40
41/// Largest body worth buffering to hash. Responses above this skip the
42/// `ETag` and are simply passed through — no endpoint here should reach
43/// it (the tree caps itself at 5000 nodes), and a streaming body must
44/// not be silently collected into memory.
45const MAX_ETAG_BODY: usize = 8 * 1024 * 1024;
46
47/// Attach validators and directives, and answer `If-None-Match` with 304.
48///
49/// Only 2xx responses get an `ETag`; an error body is not a cacheable
50/// representation of the resource, and giving a 404 a validator invites
51/// a client to revalidate its way into believing the page still doesn't
52/// exist.
53pub async fn layer(req: Request, next: Next) -> Response {
54    let if_none_match = req
55        .headers()
56        .get(IF_NONE_MATCH)
57        .and_then(|v| v.to_str().ok())
58        .map(str::to_owned);
59
60    let resp = next.run(req).await;
61    let status = resp.status();
62
63    let (mut parts, body) = resp.into_parts();
64    parts.headers.insert(
65        CACHE_CONTROL,
66        HeaderValue::from_static(CACHE_DIRECTIVE),
67    );
68    append_vary(&mut parts.headers, VARY_ON);
69
70    if !status.is_success() {
71        return Response::from_parts(parts, body);
72    }
73
74    let bytes = match axum::body::to_bytes(body, MAX_ETAG_BODY).await {
75        Ok(b) => b,
76        // Too large, or the body errored mid-stream. Either way there is
77        // nothing left to hand back, so report it rather than pretending.
78        Err(e) => {
79            tracing::warn!(target: "rustango_cms::api", error = %e, "could not buffer body for ETag");
80            return crate::api::error::ApiError::internal().into_response();
81        }
82    };
83
84    let etag = weak_etag(&bytes);
85    if let Ok(value) = HeaderValue::from_str(&etag) {
86        parts.headers.insert(ETAG, value);
87    }
88
89    // A client that already holds this exact representation gets the
90    // headers and no body.
91    if if_none_match.is_some_and(|h| if_none_match_matches(&h, &etag)) {
92        parts.status = StatusCode::NOT_MODIFIED;
93        parts.headers.remove(axum::http::header::CONTENT_LENGTH);
94        return Response::from_parts(parts, Body::empty());
95    }
96
97    Response::from_parts(parts, Body::from(bytes))
98}
99
100/// A weak validator over the body bytes.
101///
102/// Weak (`W/`) is the honest label: this says "semantically equivalent",
103/// not "byte-identical down to the transfer encoding", and nothing here
104/// promises the latter.
105fn weak_etag(bytes: &[u8]) -> String {
106    // FNV-1a, 64-bit. Not cryptographic — a validator only needs to
107    // change when the content does, and an attacker who can pick the
108    // body can already read it.
109    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
110    for b in bytes {
111        hash ^= u64::from(*b);
112        hash = hash.wrapping_mul(0x100_0000_01b3);
113    }
114    format!("W/\"{hash:016x}-{}\"", bytes.len())
115}
116
117/// RFC 9110 `If-None-Match`: `*`, or a comma-separated list in which any
118/// entry matches under the weak comparison (so `W/"x"` matches `"x"`).
119fn if_none_match_matches(header: &str, etag: &str) -> bool {
120    let strip = |s: &str| s.trim().trim_start_matches("W/").trim().to_owned();
121    let want = strip(etag);
122    header
123        .split(',')
124        .any(|candidate| candidate.trim() == "*" || strip(candidate) == want)
125}
126
127/// Add a value to `Vary` without dropping one that is already there.
128fn append_vary(headers: &mut axum::http::HeaderMap, value: &str) {
129    let existing = headers
130        .get(VARY)
131        .and_then(|v| v.to_str().ok())
132        .unwrap_or_default()
133        .to_owned();
134    if existing
135        .split(',')
136        .any(|v| v.trim().eq_ignore_ascii_case(value))
137    {
138        return;
139    }
140    let merged = if existing.is_empty() {
141        value.to_owned()
142    } else {
143        format!("{existing}, {value}")
144    };
145    if let Ok(v) = HeaderValue::from_str(&merged) {
146        headers.insert(VARY, v);
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    #[test]
155    fn the_etag_changes_with_the_body_and_not_otherwise() {
156        assert_eq!(weak_etag(b"hello"), weak_etag(b"hello"));
157        assert_ne!(weak_etag(b"hello"), weak_etag(b"hellp"));
158        // Length is part of the tag, so a hash collision alone is not
159        // enough to make two different-length bodies look equal.
160        assert_ne!(weak_etag(b"hello"), weak_etag(b"hello "));
161    }
162
163    #[test]
164    fn the_etag_is_marked_weak() {
165        assert!(weak_etag(b"x").starts_with("W/\""));
166    }
167
168    #[test]
169    fn if_none_match_compares_weakly() {
170        let tag = weak_etag(b"body");
171        assert!(if_none_match_matches(&tag, &tag));
172        // A client may echo the tag without the weakness prefix.
173        let stripped = tag.trim_start_matches("W/").to_owned();
174        assert!(if_none_match_matches(&stripped, &tag));
175    }
176
177    #[test]
178    fn if_none_match_accepts_a_list_and_a_wildcard() {
179        let tag = weak_etag(b"body");
180        assert!(if_none_match_matches(&format!("W/\"other\", {tag}"), &tag));
181        assert!(if_none_match_matches("*", &tag));
182        assert!(!if_none_match_matches("W/\"other\"", &tag));
183    }
184
185    #[test]
186    fn append_vary_is_idempotent_and_additive() {
187        let mut h = axum::http::HeaderMap::new();
188        append_vary(&mut h, "Cookie");
189        append_vary(&mut h, "Cookie");
190        assert_eq!(h.get(VARY).unwrap(), "Cookie");
191
192        let mut h = axum::http::HeaderMap::new();
193        h.insert(VARY, HeaderValue::from_static("Accept"));
194        append_vary(&mut h, "Cookie");
195        assert_eq!(h.get(VARY).unwrap(), "Accept, Cookie");
196    }
197
198    #[test]
199    fn append_vary_matches_case_insensitively() {
200        // `Vary` values are case-insensitive field names; adding "Cookie"
201        // to an existing "cookie" must not duplicate it.
202        let mut h = axum::http::HeaderMap::new();
203        h.insert(VARY, HeaderValue::from_static("cookie"));
204        append_vary(&mut h, "Cookie");
205        assert_eq!(h.get(VARY).unwrap(), "cookie");
206    }
207}