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.rs175 lines, 6.1 KiBHistoryRawDownload
1//! Conditional-GET: the ETag middleware emits a revalidatable `ETag` +
2//! `Cache-Control` on `200` JSON GETs, answers a matching `If-None-Match` with
3//! a bodyless `304`, and never touches a mutation.
4
5mod common;
6
7use axum::Router;
8use axum::body::Body;
9use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, ETAG};
10use axum::http::{HeaderMap, Request, StatusCode};
11use axum::middleware;
12use axum::response::IntoResponse;
13use axum::routing::get as route_get;
14use common::mem_app;
15use tower::ServiceExt;
16
17/// Wrap a one-route router in the real ETag middleware — lets a test stand up a
18/// JSON GET whose handler pre-sets its own cache headers (no such endpoint
19/// exists in the app, so it can't be exercised in-tree).
20fn behind_etag(router: Router) -> Router {
21 router.layer(middleware::from_fn(hezarfen_backend::web::etag::etag))
22}
23
24/// `GET uri`, optionally carrying an `If-None-Match`. Returns status, headers,
25/// and the (possibly empty) body bytes.
26async fn get(
27 app: &axum::Router,
28 uri: &str,
29 if_none_match: Option<&str>,
30) -> (StatusCode, HeaderMap, Vec<u8>) {
31 let mut builder = Request::builder().method("GET").uri(uri);
32 if let Some(v) = if_none_match {
33 builder = builder.header("if-none-match", v);
34 }
35 let res = app
36 .clone()
37 .oneshot(builder.body(Body::empty()).unwrap())
38 .await
39 .unwrap();
40 let status = res.status();
41 let headers = res.headers().clone();
42 let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
43 .await
44 .unwrap()
45 .to_vec();
46 (status, headers, bytes)
47}
48
49#[tokio::test]
50async fn get_carries_etag_and_revalidation() {
51 let app = mem_app().await;
52 let (status, headers, body) = get(&app, "/health", None).await;
53 assert_eq!(status, StatusCode::OK);
54 assert!(headers.get("etag").is_some(), "a 200 GET carries an ETag");
55 assert_eq!(
56 headers.get("cache-control").unwrap(),
57 "private, no-cache",
58 "no-cache is what makes the browser revalidate"
59 );
60 assert!(!body.is_empty(), "the first fetch returns the body");
61}
62
63#[tokio::test]
64async fn matching_if_none_match_gets_304_empty() {
65 let app = mem_app().await;
66 let (_, headers, _) = get(&app, "/health", None).await;
67 let etag = headers.get("etag").unwrap().to_str().unwrap().to_string();
68
69 // The same fetch with that validator revalidates to a bodyless 304.
70 let (status, headers, body) = get(&app, "/health", Some(&etag)).await;
71 assert_eq!(status, StatusCode::NOT_MODIFIED);
72 assert!(body.is_empty(), "a 304 carries no body");
73 assert_eq!(headers.get("etag").unwrap().to_str().unwrap(), etag);
74
75 // A stale validator still gets the full 200 payload.
76 let (status, _, body) = get(&app, "/health", Some("\"deadbeef\"")).await;
77 assert_eq!(status, StatusCode::OK);
78 assert!(!body.is_empty());
79}
80
81/// RFC 9110 §13.1.2: `If-None-Match` uses the *weak* comparison function, so a
82/// weakened copy of our own tag — what a gzipping reverse proxy sends back —
83/// must still revalidate to a `304`.
84#[tokio::test]
85async fn weak_if_none_match_gets_304_empty() {
86 let app = mem_app().await;
87 let (_, headers, _) = get(&app, "/health", None).await;
88 let etag = headers.get("etag").unwrap().to_str().unwrap().to_string();
89
90 let (status, _, body) = get(&app, "/health", Some(&format!("W/{etag}"))).await;
91 assert_eq!(
92 status,
93 StatusCode::NOT_MODIFIED,
94 "W/ prefix must not defeat the match"
95 );
96 assert!(body.is_empty(), "a 304 carries no body");
97
98 // A weakened *different* tag is still a miss.
99 let (status, _, body) = get(&app, "/health", Some("W/\"deadbeef\"")).await;
100 assert_eq!(status, StatusCode::OK);
101 assert!(!body.is_empty());
102}
103
104#[tokio::test]
105async fn handler_cache_control_is_not_overwritten() {
106 async fn handler() -> impl IntoResponse {
107 (
108 [
109 (CONTENT_TYPE, "application/json"),
110 (CACHE_CONTROL, "public, max-age=60"),
111 ],
112 "{\"a\":1}",
113 )
114 }
115 let app = behind_etag(Router::new().route("/x", route_get(handler)));
116 let (status, headers, _) = get(&app, "/x", None).await;
117 assert_eq!(status, StatusCode::OK);
118 // We still add our validator...
119 assert!(
120 headers.get("etag").is_some(),
121 "no handler ETag, so we set one"
122 );
123 // ...but the handler's own directive wins.
124 assert_eq!(headers.get("cache-control").unwrap(), "public, max-age=60");
125}
126
127#[tokio::test]
128async fn handler_owned_etag_passes_through_and_never_304s() {
129 async fn handler() -> impl IntoResponse {
130 (
131 [
132 (CONTENT_TYPE, "application/json"),
133 (ETAG, "\"handler-owned\""),
134 ],
135 "{\"a\":1}",
136 )
137 }
138 let app = behind_etag(Router::new().route("/x", route_get(handler)));
139
140 // The handler's ETag is left exactly as-is; no Cache-Control is imposed.
141 let (status, headers, body) = get(&app, "/x", None).await;
142 assert_eq!(status, StatusCode::OK);
143 assert_eq!(headers.get("etag").unwrap(), "\"handler-owned\"");
144 assert!(headers.get("cache-control").is_none());
145 assert!(!body.is_empty());
146
147 // Even If-None-Match matching that ETag stays a full 200 — our body-hash
148 // 304 logic never runs against a handler's own validator.
149 let (status, _, body) = get(&app, "/x", Some("\"handler-owned\"")).await;
150 assert_eq!(status, StatusCode::OK);
151 assert!(!body.is_empty());
152}
153
154#[tokio::test]
155async fn mutations_are_never_etagged() {
156 let app = mem_app().await;
157 let creds = serde_json::json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ann", "password": "secret1" });
158 let res = app
159 .clone()
160 .oneshot(
161 Request::builder()
162 .method("POST")
163 .uri("/auth/register")
164 .header("content-type", "application/json")
165 .body(Body::from(creds.to_string()))
166 .unwrap(),
167 )
168 .await
169 .unwrap();
170 assert_eq!(res.status(), StatusCode::CREATED);
171 assert!(
172 res.headers().get("etag").is_none(),
173 "a mutation is never given an ETag"
174 );
175}