rustango_cms/api/
http_cache.rs1use 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
30const CACHE_DIRECTIVE: &str = "private, no-cache";
34
35const VARY_ON: &str = "Cookie";
40
41const MAX_ETAG_BODY: usize = 8 * 1024 * 1024;
46
47pub 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 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 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
100fn weak_etag(bytes: &[u8]) -> String {
106 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
117fn 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
127fn 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 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 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 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}