forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

etag.rs154 lines, 6.4 KiBHistoryRawDownload
1//! Conditional-GET (`ETag` / `If-None-Match` → `304 Not Modified`) middleware.
2//!
3//! The frontend polls its list endpoints often; this makes an unchanged poll a
4//! cheap header-only `304` instead of a full JSON re-send (the browser HTTP
5//! cache revalidates on its own once we emit the headers — no client change).
6//!
7//! Scoped tightly on purpose. Only a `GET` whose handler returned a
8//! `200 application/json` response is touched; everything else passes through
9//! untouched:
10//! * mutations (`POST`/`PATCH`/`DELETE`) and their non-`200` results,
11//! * errors, redirects, `204`s,
12//! * `text/event-stream` (SSE) and any streamed body — they carry no
13//! `Content-Length`, so they are never buffered (buffering one would hang),
14//! * file blobs (`image/*`, downloads) — non-JSON, so their own `no-store`
15//! survives untouched.
16//!
17//! The validator is a strong `ETag` — a `DefaultHasher` (SipHash) digest of the
18//! body bytes. This is cache validation, not security, so a fast dependency-free
19//! hasher is the right tool; no crypto dep is pulled in for it.
20
21use std::collections::hash_map::DefaultHasher;
22use std::hash::{Hash, Hasher};
23
24use axum::body::{Body, HttpBody};
25use axum::extract::Request;
26use axum::http::header::{CACHE_CONTROL, CONTENT_LENGTH, CONTENT_TYPE, ETAG, IF_NONE_MATCH};
27use axum::http::{HeaderValue, Method, StatusCode};
28use axum::middleware::Next;
29use axum::response::Response;
30
31use crate::constant::MAX_ETAG_BODY_BYTES;
32
33/// Add an `ETag` + revalidation headers to `200` JSON `GET`s, and short-circuit
34/// a matching `If-None-Match` to a bodyless `304`.
35pub async fn etag(request: Request, next: Next) -> Response {
36 // `next.run` consumes the request, so capture the precondition up front.
37 let is_get = request.method() == Method::GET;
38 let if_none_match = request.headers().get(IF_NONE_MATCH).cloned();
39
40 let response = next.run(request).await;
41
42 if !is_get || response.status() != StatusCode::OK || !is_json(&response) {
43 return response;
44 }
45 // A handler that set its own `ETag` owns its validation — its validator
46 // scheme need not be a body hash, so we neither overwrite it nor run our
47 // hash/304 logic against it. Pass it straight through. (No JSON GET handler
48 // does this today; this is preemptive.)
49 if response.headers().contains_key(ETAG) {
50 return response;
51 }
52 // Buffer only an already-measured, bounded body. A body with no known upper
53 // size is a stream (SSE) — never buffer that; over the cap, leave it alone.
54 // (`Content-Length` isn't a header yet here — hyper writes it downstream —
55 // so the size hint is the pre-buffer measurement.)
56 match response.body().size_hint().upper() {
57 Some(len) if len <= MAX_ETAG_BODY_BYTES => {}
58 _ => return response,
59 }
60
61 let (mut parts, body) = response.into_parts();
62 let Ok(bytes) = axum::body::to_bytes(body, MAX_ETAG_BODY_BYTES as usize).await else {
63 // Unreachable given the Content-Length check above; a truncated body is
64 // worse than a missed cache, so fail closed on the empty-parts path.
65 return Response::from_parts(parts, Body::empty());
66 };
67
68 let tag = compute_etag(&bytes);
69 let tag_value = HeaderValue::from_str(&tag).expect("hex etag is a valid header value");
70 parts.headers.insert(ETAG, tag_value);
71 // `no-cache` = store but revalidate every time — this is what makes the
72 // browser resend `If-None-Match` on the next poll. Without it the ETag is
73 // inert. `private`: these are per-user authenticated responses. But if the
74 // handler set its own directive, it knows best — leave it untouched.
75 if !parts.headers.contains_key(CACHE_CONTROL) {
76 parts
77 .headers
78 .insert(CACHE_CONTROL, HeaderValue::from_static("private, no-cache"));
79 }
80
81 if matches(if_none_match.as_ref(), &tag) {
82 parts.status = StatusCode::NOT_MODIFIED;
83 parts.headers.remove(CONTENT_LENGTH);
84 parts.headers.remove(CONTENT_TYPE);
85 return Response::from_parts(parts, Body::empty());
86 }
87
88 Response::from_parts(parts, Body::from(bytes))
89}
90
91/// A JSON response — the only shape worth revalidating. Excludes SSE, blobs,
92/// and Swagger HTML.
93fn is_json(response: &Response) -> bool {
94 response
95 .headers()
96 .get(CONTENT_TYPE)
97 .and_then(|v| v.to_str().ok())
98 .is_some_and(|ct| ct.starts_with("application/json"))
99}
100
101/// Strong `ETag` for `bytes`, formatted as a quoted hex string.
102fn compute_etag(bytes: &[u8]) -> String {
103 let mut hasher = DefaultHasher::new();
104 bytes.hash(&mut hasher);
105 format!("\"{:016x}\"", hasher.finish())
106}
107
108/// `If-None-Match` compare: `*` matches anything, otherwise the (comma-
109/// separated) candidate list must contain our tag. RFC 9110 §13.1.2 mandates the
110/// *weak* comparison function here, so the `W/` prefix is stripped from both
111/// sides and only the opaque quoted strings are compared — an intermediary that
112/// weakens our ETag (nginx does this when it gzips) must still get its `304`.
113fn matches(if_none_match: Option<&HeaderValue>, tag: &str) -> bool {
114 let Some(value) = if_none_match.and_then(|v| v.to_str().ok()) else {
115 return false;
116 };
117 let value = value.trim();
118 value == "*"
119 || value
120 .split(',')
121 .map(str::trim)
122 .any(|candidate| opaque(candidate) == opaque(tag))
123}
124
125/// The opaque part of a validator — the quoted string without any weak prefix.
126fn opaque(validator: &str) -> &str {
127 validator.strip_prefix("W/").unwrap_or(validator)
128}
129
130#[cfg(test)]
131mod tests {
132 use super::matches;
133 use axum::http::HeaderValue;
134
135 fn m(header: &str, tag: &str) -> bool {
136 matches(Some(&HeaderValue::from_str(header).unwrap()), tag)
137 }
138
139 #[test]
140 fn weak_comparison_is_symmetric() {
141 // Both directions and both-weak: the opaque strings decide (RFC 9110
142 // §13.1.2), never the `W/` prefix.
143 assert!(m("W/\"abc\"", "\"abc\""), "weak candidate vs strong tag");
144 assert!(m("\"abc\"", "W/\"abc\""), "strong candidate vs weak tag");
145 assert!(m("W/\"abc\"", "W/\"abc\""), "both weak");
146 assert!(m("\"abc\"", "\"abc\""), "both strong");
147 // A different opaque string still misses, weak prefix or not.
148 assert!(!m("W/\"abd\"", "\"abc\""));
149 // List membership and `*` keep working through the strip.
150 assert!(m("\"x\", W/\"abc\"", "\"abc\""));
151 assert!(m("*", "\"abc\""));
152 assert!(!m("garbage,,,\"", "\"abc\""));
153 }
154}