From a9627787e16bebc66200c3781eb9fb5467bb8335 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 24 Jul 2026 18:34:05 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=E2=9A=A1=20ETag=20conditional=20GET=20?= =?UTF-8?q?so=20polled=20reads=20become=20cheap=20304s=20-=20add=20src/web?= =?UTF-8?q?/etag.rs:=20global=20axum=20middleware=20on=20the=20top-level?= =?UTF-8?q?=20router=20=20=20(innermost=20layer)=20that,=20for=20GET=20+?= =?UTF-8?q?=20200=20+=20application/json=20responses,=20=20=20hashes=20the?= =?UTF-8?q?=20body=20(SipHash,=20no=20new=20dep)=20into=20a=20strong=20ETa?= =?UTF-8?q?g=20and=20sets=20=20=20Cache-Control:=20private,=20no-cache=20s?= =?UTF-8?q?o=20the=20browser=20revalidates=20-=20matching=20If-None-Match?= =?UTF-8?q?=20returns=20304=20with=20an=20empty=20body=20and=20the=20=20?= =?UTF-8?q?=20validators=20kept;=20frequent=20frontend=20polls=20stop=20re?= =?UTF-8?q?-sending=20full=20payloads=20-=20passthrough=20untouched=20for?= =?UTF-8?q?=20non-GET,=20non-200,=20non-JSON=20(image=20blobs=20keep=20=20?= =?UTF-8?q?=20their=20own=20no-store),=20and=20streaming/oversized=20bodie?= =?UTF-8?q?s=20(size=5Fhint=20guard)=20-=20defensive:=20a=20handler=20that?= =?UTF-8?q?=20sets=20its=20own=20ETag=20is=20passed=20through=20without=20?= =?UTF-8?q?=20=20our=20hash/304=20logic,=20and=20an=20existing=20Cache-Con?= =?UTF-8?q?trol=20is=20never=20overwritten=20-=20responses=20rebuilt=20via?= =?UTF-8?q?=20into=5Fparts/from=5Fparts=20so=20Set-Cookie=20and=20other=20?= =?UTF-8?q?=20=20handler=20headers=20survive=20on=20both=20the=20200=20and?= =?UTF-8?q?=20304=20paths=20-=20tests/etag.rs:=20ETag=20present=20+=20reva?= =?UTF-8?q?lidation,=20matching=20validator=20=E2=86=92=20304=20=20=20empt?= =?UTF-8?q?y,=20mutations=20never=20ETagged,=20handler-owned=20headers=20p?= =?UTF-8?q?reserved?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/lib.rs | 4 ++ src/web/etag.rs | 121 +++++++++++++++++++++++++++++++++++++++ src/web/mod.rs | 1 + tests/etag.rs | 149 ++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 275 insertions(+) create mode 100644 src/web/etag.rs create mode 100644 tests/etag.rs diff --git a/src/lib.rs b/src/lib.rs index 2e977c4..a30a928 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -132,6 +132,10 @@ pub fn build_router(state: AppState) -> Router { router .merge(SwaggerUi::new("/swagger").url("/api-docs/openapi.json", api)) .with_state(state) + // Conditional-GET: revalidatable `ETag` on 200 JSON GETs, `304` on a + // matching `If-None-Match`. Innermost, so it sees the handler's own + // response (mutations and errors pass straight through untouched). + .layer(middleware::from_fn(web::etag::etag)) .layer(middleware::from_fn(move |req: Request, next: Next| { let health = db_up.clone(); async move { db_guard(health, req, next).await } diff --git a/src/web/etag.rs b/src/web/etag.rs new file mode 100644 index 0000000..baa1137 --- /dev/null +++ b/src/web/etag.rs @@ -0,0 +1,121 @@ +//! Conditional-GET (`ETag` / `If-None-Match` → `304 Not Modified`) middleware. +//! +//! The frontend polls its list endpoints often; this makes an unchanged poll a +//! cheap header-only `304` instead of a full JSON re-send (the browser HTTP +//! cache revalidates on its own once we emit the headers — no client change). +//! +//! Scoped tightly on purpose. Only a `GET` whose handler returned a +//! `200 application/json` response is touched; everything else passes through +//! untouched: +//! * mutations (`POST`/`PATCH`/`DELETE`) and their non-`200` results, +//! * errors, redirects, `204`s, +//! * `text/event-stream` (SSE) and any streamed body — they carry no +//! `Content-Length`, so they are never buffered (buffering one would hang), +//! * file blobs (`image/*`, downloads) — non-JSON, so their own `no-store` +//! survives untouched. +//! +//! The validator is a strong `ETag` — a `DefaultHasher` (SipHash) digest of the +//! body bytes. This is cache validation, not security, so a fast dependency-free +//! hasher is the right tool; no crypto dep is pulled in for it. + +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; + +use axum::body::{Body, HttpBody}; +use axum::extract::Request; +use axum::http::header::{CACHE_CONTROL, CONTENT_LENGTH, CONTENT_TYPE, ETAG, IF_NONE_MATCH}; +use axum::http::{HeaderValue, Method, StatusCode}; +use axum::middleware::Next; +use axum::response::Response; + +/// Bodies larger than this are streamed through without buffering — JSON pages +/// sit far below it, so the cap only bounds worst-case memory. A response whose +/// `Content-Length` exceeds it (or is absent, i.e. a stream) skips the feature. +const MAX_BODY: u64 = 1 << 20; // 1 MiB + +/// Add an `ETag` + revalidation headers to `200` JSON `GET`s, and short-circuit +/// a matching `If-None-Match` to a bodyless `304`. +pub async fn etag(request: Request, next: Next) -> Response { + // `next.run` consumes the request, so capture the precondition up front. + let is_get = request.method() == Method::GET; + let if_none_match = request.headers().get(IF_NONE_MATCH).cloned(); + + let response = next.run(request).await; + + if !is_get || response.status() != StatusCode::OK || !is_json(&response) { + return response; + } + // A handler that set its own `ETag` owns its validation — its validator + // scheme need not be a body hash, so we neither overwrite it nor run our + // hash/304 logic against it. Pass it straight through. (No JSON GET handler + // does this today; this is preemptive.) + if response.headers().contains_key(ETAG) { + return response; + } + // Buffer only an already-measured, bounded body. A body with no known upper + // size is a stream (SSE) — never buffer that; over the cap, leave it alone. + // (`Content-Length` isn't a header yet here — hyper writes it downstream — + // so the size hint is the pre-buffer measurement.) + match response.body().size_hint().upper() { + Some(len) if len <= MAX_BODY => {} + _ => return response, + } + + let (mut parts, body) = response.into_parts(); + let Ok(bytes) = axum::body::to_bytes(body, MAX_BODY as usize).await else { + // Unreachable given the Content-Length check above; a truncated body is + // worse than a missed cache, so fail closed on the empty-parts path. + return Response::from_parts(parts, Body::empty()); + }; + + let tag = compute_etag(&bytes); + let tag_value = HeaderValue::from_str(&tag).expect("hex etag is a valid header value"); + parts.headers.insert(ETAG, tag_value); + // `no-cache` = store but revalidate every time — this is what makes the + // browser resend `If-None-Match` on the next poll. Without it the ETag is + // inert. `private`: these are per-user authenticated responses. But if the + // handler set its own directive, it knows best — leave it untouched. + if !parts.headers.contains_key(CACHE_CONTROL) { + parts.headers.insert( + CACHE_CONTROL, + HeaderValue::from_static("private, no-cache"), + ); + } + + if matches(if_none_match.as_ref(), &tag) { + parts.status = StatusCode::NOT_MODIFIED; + parts.headers.remove(CONTENT_LENGTH); + parts.headers.remove(CONTENT_TYPE); + return Response::from_parts(parts, Body::empty()); + } + + Response::from_parts(parts, Body::from(bytes)) +} + +/// A JSON response — the only shape worth revalidating. Excludes SSE, blobs, +/// and Swagger HTML. +fn is_json(response: &Response) -> bool { + response + .headers() + .get(CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|ct| ct.starts_with("application/json")) +} + +/// Strong `ETag` for `bytes`, formatted as a quoted hex string. +fn compute_etag(bytes: &[u8]) -> String { + let mut hasher = DefaultHasher::new(); + bytes.hash(&mut hasher); + format!("\"{:016x}\"", hasher.finish()) +} + +/// Strong `If-None-Match` compare: `*` matches anything, otherwise the (comma- +/// separated) candidate list must contain our exact quoted tag. A weak +/// validator `W/"…"` never equals our strong tag, so it correctly misses. +fn matches(if_none_match: Option<&HeaderValue>, tag: &str) -> bool { + let Some(value) = if_none_match.and_then(|v| v.to_str().ok()) else { + return false; + }; + let value = value.trim(); + value == "*" || value.split(',').map(str::trim).any(|candidate| candidate == tag) +} diff --git a/src/web/mod.rs b/src/web/mod.rs index 9883936..10633fe 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -10,6 +10,7 @@ pub mod auth; pub mod bank_questions; pub mod chatbot; pub mod courses; +pub mod etag; pub mod events; pub mod exam_ws; pub mod exams; diff --git a/tests/etag.rs b/tests/etag.rs new file mode 100644 index 0000000..7f71da1 --- /dev/null +++ b/tests/etag.rs @@ -0,0 +1,149 @@ +//! Conditional-GET: the ETag middleware emits a revalidatable `ETag` + +//! `Cache-Control` on `200` JSON GETs, answers a matching `If-None-Match` with +//! a bodyless `304`, and never touches a mutation. + +mod common; + +use axum::Router; +use axum::body::Body; +use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, ETAG}; +use axum::http::{HeaderMap, Request, StatusCode}; +use axum::middleware; +use axum::response::IntoResponse; +use axum::routing::get as route_get; +use common::mem_app; +use tower::ServiceExt; + +/// Wrap a one-route router in the real ETag middleware — lets a test stand up a +/// JSON GET whose handler pre-sets its own cache headers (no such endpoint +/// exists in the app, so it can't be exercised in-tree). +fn behind_etag(router: Router) -> Router { + router.layer(middleware::from_fn(hezarfen_backend::web::etag::etag)) +} + +/// `GET uri`, optionally carrying an `If-None-Match`. Returns status, headers, +/// and the (possibly empty) body bytes. +async fn get( + app: &axum::Router, + uri: &str, + if_none_match: Option<&str>, +) -> (StatusCode, HeaderMap, Vec) { + let mut builder = Request::builder().method("GET").uri(uri); + if let Some(v) = if_none_match { + builder = builder.header("if-none-match", v); + } + let res = app + .clone() + .oneshot(builder.body(Body::empty()).unwrap()) + .await + .unwrap(); + let status = res.status(); + let headers = res.headers().clone(); + let bytes = axum::body::to_bytes(res.into_body(), usize::MAX) + .await + .unwrap() + .to_vec(); + (status, headers, bytes) +} + +#[tokio::test] +async fn get_carries_etag_and_revalidation() { + let app = mem_app().await; + let (status, headers, body) = get(&app, "/health", None).await; + assert_eq!(status, StatusCode::OK); + assert!(headers.get("etag").is_some(), "a 200 GET carries an ETag"); + assert_eq!( + headers.get("cache-control").unwrap(), + "private, no-cache", + "no-cache is what makes the browser revalidate" + ); + assert!(!body.is_empty(), "the first fetch returns the body"); +} + +#[tokio::test] +async fn matching_if_none_match_gets_304_empty() { + let app = mem_app().await; + let (_, headers, _) = get(&app, "/health", None).await; + let etag = headers.get("etag").unwrap().to_str().unwrap().to_string(); + + // The same fetch with that validator revalidates to a bodyless 304. + let (status, headers, body) = get(&app, "/health", Some(&etag)).await; + assert_eq!(status, StatusCode::NOT_MODIFIED); + assert!(body.is_empty(), "a 304 carries no body"); + assert_eq!(headers.get("etag").unwrap().to_str().unwrap(), etag); + + // A stale validator still gets the full 200 payload. + let (status, _, body) = get(&app, "/health", Some("\"deadbeef\"")).await; + assert_eq!(status, StatusCode::OK); + assert!(!body.is_empty()); +} + +#[tokio::test] +async fn handler_cache_control_is_not_overwritten() { + async fn handler() -> impl IntoResponse { + ( + [ + (CONTENT_TYPE, "application/json"), + (CACHE_CONTROL, "public, max-age=60"), + ], + "{\"a\":1}", + ) + } + let app = behind_etag(Router::new().route("/x", route_get(handler))); + let (status, headers, _) = get(&app, "/x", None).await; + assert_eq!(status, StatusCode::OK); + // We still add our validator... + assert!(headers.get("etag").is_some(), "no handler ETag, so we set one"); + // ...but the handler's own directive wins. + assert_eq!(headers.get("cache-control").unwrap(), "public, max-age=60"); +} + +#[tokio::test] +async fn handler_owned_etag_passes_through_and_never_304s() { + async fn handler() -> impl IntoResponse { + ( + [ + (CONTENT_TYPE, "application/json"), + (ETAG, "\"handler-owned\""), + ], + "{\"a\":1}", + ) + } + let app = behind_etag(Router::new().route("/x", route_get(handler))); + + // The handler's ETag is left exactly as-is; no Cache-Control is imposed. + let (status, headers, body) = get(&app, "/x", None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(headers.get("etag").unwrap(), "\"handler-owned\""); + assert!(headers.get("cache-control").is_none()); + assert!(!body.is_empty()); + + // Even If-None-Match matching that ETag stays a full 200 — our body-hash + // 304 logic never runs against a handler's own validator. + let (status, _, body) = get(&app, "/x", Some("\"handler-owned\"")).await; + assert_eq!(status, StatusCode::OK); + assert!(!body.is_empty()); +} + +#[tokio::test] +async fn mutations_are_never_etagged() { + let app = mem_app().await; + let creds = serde_json::json!({ "username": "ann", "password": "secret1" }); + let res = app + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri("/auth/register") + .header("content-type", "application/json") + .body(Body::from(creds.to_string())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::CREATED); + assert!( + res.headers().get("etag").is_none(), + "a mutation is never given an ETag" + ); +}