forge
Explore
Log in

Don't you dare go Hollow

Integration, e2e, persistence, and rate-limit suites

Browse files at this commit

905da44260f57c4fb35f3420b96ed70aca9b91e7Ahmet Kaan GümüşParent: c4d0a23
  • test
    • integration, e2e, persistence, and rate-limit suites
Show full message
✅ test: integration, e2e, persistence, and rate-limit suites

End-to-end coverage over the assembled router:

- integration.rs: tower::oneshot against an in-memory database — the
  fast path for handler, validation, and access-control behavior.
- e2e.rs: a real TCP listener driven by a reqwest cookie jar,
  exercising the actual session-cookie round trip.
- persistence.rs: the file-backed engine on a tempfile, including
  close-and-reopen to prove data survives a restart.
- rate_limit.rs: both tiers, peer-address vs X-Forwarded-For keying,
  and the shipped limits over every route.
- common/mod.rs: the shared harness — builds the router with limits
  disabled so unrelated suites never trip a limit.
tests/common/mod.rsadded+121 -0
@@ -0,0 +1,121 @@
1+//! Shared helpers for the router-level test binaries (`integration`, `persistence`).
2+//! Drives an `axum::Router` in-process via `tower::ServiceExt::oneshot`.
3+#![allow(dead_code)]
4+
5+use axum::Router;
6+use axum::body::Body;
7+use axum::http::{Request, StatusCode};
8+use hezarfen_backend::database::Database;
9+use hezarfen_backend::rate_limit::RateLimitConfig;
10+use hezarfen_backend::state::AppState;
11+use hezarfen_backend::{build_router, database};
12+use serde_json::{Value, json};
13+use tower::ServiceExt;
14+
15+pub struct Res {
16+ pub status: StatusCode,
17+ pub body: Value,
18+ /// The `session=<token>` pair, if the response set one.
19+ pub cookie: Option<String>,
20+}
21+
22+/// A router plus a handle to its (shared) in-memory database. Tests that need to
23+/// grant roles use the handle to seed them directly — the app's only role
24+/// bootstrap path is out-of-band, exactly like production's manual SQL.
25+pub async fn app_and_db() -> (Router, Database) {
26+ let db = database::init_mem().await.expect("in-memory db");
27+ let app = build_router(AppState {
28+ db: db.clone(),
29+ cookie_secure: false,
30+ // Off, so suites hammering the API never trip a limit; the dedicated
31+ // `rate_limit` test binary opts into tight configs on purpose.
32+ rate_limit: RateLimitConfig::unlimited(),
33+ });
34+ (app, db)
35+}
36+
37+/// A router backed by a fresh in-memory database.
38+pub async fn mem_app() -> Router {
39+ app_and_db().await.0
40+}
41+
42+/// Force `username`'s role, mirroring the manual `UPDATE user SET role=...`
43+/// bootstrap. Roles are read fresh per request, so this takes effect at once.
44+pub async fn set_role(db: &Database, username: &str, role: &str) {
45+ db.query("UPDATE user SET role = $role WHERE username = $u")
46+ .bind(("role", role.to_string()))
47+ .bind(("u", username.to_string()))
48+ .await
49+ .expect("set_role query")
50+ .check()
51+ .expect("set_role check");
52+}
53+
54+/// Register (password `secret1`), promote to `role`, then log in. Returns the
55+/// session `Cookie` value.
56+pub async fn login_as(app: &Router, db: &Database, username: &str, role: &str) -> String {
57+ let creds = json!({ "username": username, "password": "secret1" });
58+ let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await;
59+ assert_eq!(reg.status, StatusCode::CREATED, "register {username}");
60+ set_role(db, username, role).await;
61+ let res = send(app, "POST", "/auth/login", None, Some(creds)).await;
62+ assert_eq!(res.status, StatusCode::OK, "login {username}");
63+ res.cookie.expect("session cookie set on login")
64+}
65+
66+/// Send one request through `app`. `cookie` is a raw `Cookie` header value.
67+pub async fn send(
68+ app: &Router,
69+ method: &str,
70+ uri: &str,
71+ cookie: Option<&str>,
72+ body: Option<Value>,
73+) -> Res {
74+ let mut builder = Request::builder().method(method).uri(uri);
75+ if let Some(c) = cookie {
76+ builder = builder.header("cookie", c);
77+ }
78+ let request = match body {
79+ Some(b) => builder
80+ .header("content-type", "application/json")
81+ .body(Body::from(b.to_string()))
82+ .unwrap(),
83+ None => builder.body(Body::empty()).unwrap(),
84+ };
85+
86+ let response = app.clone().oneshot(request).await.unwrap();
87+ let status = response.status();
88+ let cookie = response
89+ .headers()
90+ .get("set-cookie")
91+ .and_then(|v| v.to_str().ok())
92+ .and_then(|s| s.split(';').next())
93+ .map(|s| s.to_string());
94+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
95+ .await
96+ .unwrap();
97+ let body = if bytes.is_empty() {
98+ Value::Null
99+ } else {
100+ serde_json::from_slice(&bytes).unwrap_or(Value::Null)
101+ };
102+ Res {
103+ status,
104+ body,
105+ cookie,
106+ }
107+}
108+
109+/// Register (password `secret1`) then log in; returns the session `Cookie` value.
110+pub async fn login(app: &Router, username: &str) -> String {
111+ let creds = json!({ "username": username, "password": "secret1" });
112+ let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await;
113+ assert_eq!(reg.status, StatusCode::CREATED, "register {username}");
114+ let res = send(app, "POST", "/auth/login", None, Some(creds)).await;
115+ assert_eq!(res.status, StatusCode::OK, "login {username}");
116+ res.cookie.expect("session cookie set on login")
117+}
118+
119+pub fn id_of(v: &Value) -> String {
120+ v["id"].as_str().expect("id field").to_string()
121+}
tests/e2e.rsadded+276 -0
@@ -0,0 +1,276 @@
1+//! End-to-end tests: boot the real server on an ephemeral TCP port and drive it
2+//! with `reqwest` over HTTP, using its cookie jar exactly like a browser client.
3+
4+use hezarfen_backend::database::Database;
5+use hezarfen_backend::rate_limit::RateLimitConfig;
6+use hezarfen_backend::state::AppState;
7+use hezarfen_backend::{build_router, database};
8+use reqwest::{Client, StatusCode};
9+use serde_json::{Value, json};
10+
11+/// Start the server on a random port. Returns its base URL (e.g.
12+/// `http://127.0.0.1:54321`) plus a handle to its database, so a test can grant
13+/// roles the same out-of-band way production does.
14+async fn spawn_server() -> (String, Database) {
15+ let db = database::init_mem().await.expect("in-memory db");
16+ let app = build_router(AppState {
17+ db: db.clone(),
18+ cookie_secure: false,
19+ // Every request here comes from 127.0.0.1, so per-IP limits would
20+ // meter the whole suite as one client. Off; `rate_limit.rs` covers it.
21+ rate_limit: RateLimitConfig::unlimited(),
22+ });
23+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
24+ let addr = listener.local_addr().unwrap();
25+ tokio::spawn(async move {
26+ // Mirror `main`: expose peer addresses so the limiter key path in
27+ // production is the same one exercised end-to-end.
28+ axum::serve(
29+ listener,
30+ app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
31+ )
32+ .await
33+ .unwrap();
34+ });
35+ (format!("http://{addr}"), db)
36+}
37+
38+/// Grant `user` a role directly (the manual bootstrap path).
39+async fn promote(db: &Database, user: &str, role: &str) {
40+ db.query("UPDATE user SET role = $r WHERE username = $u")
41+ .bind(("r", role.to_string()))
42+ .bind(("u", user.to_string()))
43+ .await
44+ .unwrap()
45+ .check()
46+ .unwrap();
47+}
48+
49+/// A reqwest client with its own cookie jar (one per simulated user).
50+fn client() -> Client {
51+ Client::builder().cookie_store(true).build().unwrap()
52+}
53+
54+async fn register(client: &Client, base: &str, user: &str) -> reqwest::Response {
55+ client
56+ .post(format!("{base}/auth/register"))
57+ .json(&json!({ "username": user, "password": "secret1" }))
58+ .send()
59+ .await
60+ .unwrap()
61+}
62+
63+async fn login(client: &Client, base: &str, user: &str) {
64+ let res = client
65+ .post(format!("{base}/auth/login"))
66+ .json(&json!({ "username": user, "password": "secret1" }))
67+ .send()
68+ .await
69+ .unwrap();
70+ assert_eq!(res.status(), StatusCode::OK, "login {user}");
71+}
72+
73+#[tokio::test]
74+async fn full_user_journey() {
75+ let (base, db) = spawn_server().await;
76+ let ali = client();
77+ let veli = client();
78+
79+ // --- signup + auth ---------------------------------------------------
80+ assert_eq!(
81+ register(&ali, &base, "ali").await.status(),
82+ StatusCode::CREATED
83+ );
84+ assert_eq!(
85+ register(&veli, &base, "veli").await.status(),
86+ StatusCode::CREATED
87+ );
88+ // ali runs the class: give her the teacher role. veli stays a student.
89+ promote(&db, "ali", "teacher").await;
90+
91+ // me before login -> 401
92+ let res = ali.get(format!("{base}/auth/me")).send().await.unwrap();
93+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
94+
95+ login(&ali, &base, "ali").await;
96+ login(&veli, &base, "veli").await;
97+
98+ let me: Value = ali
99+ .get(format!("{base}/auth/me"))
100+ .send()
101+ .await
102+ .unwrap()
103+ .json()
104+ .await
105+ .unwrap();
106+ assert_eq!(me["username"], "ali");
107+
108+ let veli_id = veli
109+ .get(format!("{base}/auth/me"))
110+ .send()
111+ .await
112+ .unwrap()
113+ .json::<Value>()
114+ .await
115+ .unwrap()["id"]
116+ .as_str()
117+ .unwrap()
118+ .to_string();
119+
120+ // --- notes -----------------------------------------------------------
121+ let note: Value = ali
122+ .post(format!("{base}/notes"))
123+ .json(&json!({ "title": "first", "content": "hello" }))
124+ .send()
125+ .await
126+ .unwrap()
127+ .json()
128+ .await
129+ .unwrap();
130+ let note_id = note["id"].as_str().unwrap().to_string();
131+ assert_eq!(note["title"], "first");
132+
133+ // veli cannot read ali's note
134+ let res = veli
135+ .get(format!("{base}/notes/{note_id}"))
136+ .send()
137+ .await
138+ .unwrap();
139+ assert_eq!(res.status(), StatusCode::NOT_FOUND);
140+
141+ // --- events + attendance --------------------------------------------
142+ let event: Value = ali
143+ .post(format!("{base}/events"))
144+ .json(&json!({ "title": "standup" }))
145+ .send()
146+ .await
147+ .unwrap()
148+ .json()
149+ .await
150+ .unwrap();
151+ let event_id = event["id"].as_str().unwrap().to_string();
152+
153+ // ali marks veli present
154+ let res = ali
155+ .post(format!("{base}/events/{event_id}/attendance"))
156+ .json(&json!({ "status": "present", "user_id": veli_id }))
157+ .send()
158+ .await
159+ .unwrap();
160+ assert_eq!(res.status(), StatusCode::OK);
161+
162+ let roster: Value = veli
163+ .get(format!("{base}/events/{event_id}/attendance"))
164+ .send()
165+ .await
166+ .unwrap()
167+ .json()
168+ .await
169+ .unwrap();
170+ assert_eq!(roster.as_array().unwrap().len(), 1);
171+ assert_eq!(roster[0]["user"], veli_id);
172+ assert_eq!(roster[0]["status"], "present");
173+
174+ // veli is only a student, so she cannot create events.
175+ let res = veli
176+ .post(format!("{base}/events"))
177+ .json(&json!({ "title": "nope" }))
178+ .send()
179+ .await
180+ .unwrap();
181+ assert_eq!(res.status(), StatusCode::FORBIDDEN);
182+
183+ // --- logout invalidates the session ---------------------------------
184+ let res = ali
185+ .post(format!("{base}/auth/logout"))
186+ .send()
187+ .await
188+ .unwrap();
189+ assert_eq!(res.status(), StatusCode::NO_CONTENT);
190+
191+ let res = ali.get(format!("{base}/auth/me")).send().await.unwrap();
192+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
193+}
194+
195+#[tokio::test]
196+async fn attendance_rollup_across_users() {
197+ let (base, db) = spawn_server().await;
198+ let host = client();
199+ let a = client();
200+ let b = client();
201+
202+ for (c, name) in [(&host, "host"), (&a, "amy"), (&b, "ben")] {
203+ assert_eq!(register(c, &base, name).await.status(), StatusCode::CREATED);
204+ login(c, &base, name).await;
205+ }
206+ // The host runs the event and records everyone, which is a teacher+ action.
207+ promote(&db, "host", "teacher").await;
208+
209+ let id_of = |v: &Value| v["id"].as_str().unwrap().to_string();
210+ let amy_id = id_of(
211+ &a.get(format!("{base}/auth/me"))
212+ .send()
213+ .await
214+ .unwrap()
215+ .json::<Value>()
216+ .await
217+ .unwrap(),
218+ );
219+ let ben_id = id_of(
220+ &b.get(format!("{base}/auth/me"))
221+ .send()
222+ .await
223+ .unwrap()
224+ .json::<Value>()
225+ .await
226+ .unwrap(),
227+ );
228+
229+ // Host creates an event and records everyone.
230+ let event_id = id_of(
231+ &host
232+ .post(format!("{base}/events"))
233+ .json(&json!({ "title": "all-hands" }))
234+ .send()
235+ .await
236+ .unwrap()
237+ .json::<Value>()
238+ .await
239+ .unwrap(),
240+ );
241+
242+ for (uid, status) in [(&amy_id, "present"), (&ben_id, "late")] {
243+ let res = host
244+ .post(format!("{base}/events/{event_id}/attendance"))
245+ .json(&json!({ "status": status, "user_id": uid }))
246+ .send()
247+ .await
248+ .unwrap();
249+ assert_eq!(res.status(), StatusCode::OK);
250+ }
251+ // Host marks self too.
252+ host.post(format!("{base}/events/{event_id}/attendance"))
253+ .json(&json!({ "status": "present" }))
254+ .send()
255+ .await
256+ .unwrap();
257+
258+ // Any attendee can read the full roster (3 people).
259+ let roster: Value = b
260+ .get(format!("{base}/events/{event_id}/attendance"))
261+ .send()
262+ .await
263+ .unwrap()
264+ .json()
265+ .await
266+ .unwrap();
267+ assert_eq!(roster.as_array().unwrap().len(), 3);
268+
269+ // Unauthenticated client is refused.
270+ let res = client()
271+ .get(format!("{base}/events/{event_id}/attendance"))
272+ .send()
273+ .await
274+ .unwrap();
275+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
276+}
tests/integration.rsadded+1895 -0
@@ -0,0 +1,1895 @@
1+//! Integration tests: drive the assembled axum router directly (no network)
2+//! against a fresh in-memory SurrealDB, via `tower::ServiceExt::oneshot`.
3+
4+mod common;
5+
6+use axum::body::Body;
7+use axum::http::{Request, StatusCode};
8+use common::{app_and_db, id_of, login, login_as, mem_app, send};
9+use hezarfen_backend::domain::session::Session;
10+use hezarfen_backend::state::AppState;
11+use hezarfen_backend::{build_router, database};
12+use serde_json::json;
13+use tower::ServiceExt;
14+
15+// --- health + auth -------------------------------------------------------
16+
17+#[tokio::test]
18+async fn health_reports_ok() {
19+ let app = mem_app().await;
20+ let res = send(&app, "GET", "/health", None, None).await;
21+ assert_eq!(res.status, StatusCode::OK);
22+ assert_eq!(res.body["status"], "ok");
23+}
24+
25+#[tokio::test]
26+async fn register_validates_input() {
27+ let app = mem_app().await;
28+
29+ // Password too short -> 400.
30+ let short = json!({ "username": "bob", "password": "123" });
31+ let res = send(&app, "POST", "/auth/register", None, Some(short)).await;
32+ assert_eq!(res.status, StatusCode::BAD_REQUEST);
33+
34+ // Blank username -> 400.
35+ let blank = json!({ "username": " ", "password": "secret1" });
36+ let res = send(&app, "POST", "/auth/register", None, Some(blank)).await;
37+ assert_eq!(res.status, StatusCode::BAD_REQUEST);
38+
39+ // Valid -> 201, no password echoed back, defaults to the student role.
40+ let ok = json!({ "username": "bob", "password": "secret1" });
41+ let res = send(&app, "POST", "/auth/register", None, Some(ok.clone())).await;
42+ assert_eq!(res.status, StatusCode::CREATED);
43+ assert_eq!(res.body["username"], "bob");
44+ assert_eq!(res.body["role"], "student");
45+ assert!(res.body.get("password_hash").is_none());
46+
47+ // Duplicate username -> 409.
48+ let res = send(&app, "POST", "/auth/register", None, Some(ok)).await;
49+ assert_eq!(res.status, StatusCode::CONFLICT);
50+}
51+
52+#[tokio::test]
53+async fn login_rejects_bad_credentials() {
54+ let app = mem_app().await;
55+ send(
56+ &app,
57+ "POST",
58+ "/auth/register",
59+ None,
60+ Some(json!({ "username": "kate", "password": "secret1" })),
61+ )
62+ .await;
63+
64+ // Wrong password.
65+ let res = send(
66+ &app,
67+ "POST",
68+ "/auth/login",
69+ None,
70+ Some(json!({ "username": "kate", "password": "wrong" })),
71+ )
72+ .await;
73+ assert_eq!(res.status, StatusCode::UNAUTHORIZED);
74+
75+ // Unknown user.
76+ let res = send(
77+ &app,
78+ "POST",
79+ "/auth/login",
80+ None,
81+ Some(json!({ "username": "ghost", "password": "secret1" })),
82+ )
83+ .await;
84+ assert_eq!(res.status, StatusCode::UNAUTHORIZED);
85+}
86+
87+#[tokio::test]
88+async fn protected_routes_require_session() {
89+ let app = mem_app().await;
90+ for (method, uri) in [
91+ ("GET", "/auth/me"),
92+ ("GET", "/notes"),
93+ ("POST", "/notes"),
94+ ("GET", "/events"),
95+ ("POST", "/events"),
96+ ("GET", "/exams"),
97+ ("POST", "/exams"),
98+ ] {
99+ let res = send(&app, method, uri, None, None).await;
100+ assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{method} {uri}");
101+ }
102+}
103+
104+#[tokio::test]
105+async fn garbage_cookie_is_unauthorized() {
106+ let app = mem_app().await;
107+ let res = send(&app, "GET", "/auth/me", Some("session=deadbeef"), None).await;
108+ assert_eq!(res.status, StatusCode::UNAUTHORIZED);
109+}
110+
111+#[tokio::test]
112+async fn me_returns_current_user_without_secrets() {
113+ let app = mem_app().await;
114+ let ali = login(&app, "ali").await;
115+ let res = send(&app, "GET", "/auth/me", Some(&ali), None).await;
116+ assert_eq!(res.status, StatusCode::OK);
117+ assert_eq!(res.body["username"], "ali");
118+ assert_eq!(res.body["role"], "student");
119+ assert!(res.body.get("password_hash").is_none());
120+}
121+
122+#[tokio::test]
123+async fn logout_invalidates_the_session_server_side() {
124+ let app = mem_app().await;
125+ let ali = login(&app, "ali").await;
126+
127+ assert_eq!(
128+ send(&app, "GET", "/auth/me", Some(&ali), None).await.status,
129+ StatusCode::OK
130+ );
131+
132+ let res = send(&app, "POST", "/auth/logout", Some(&ali), None).await;
133+ assert_eq!(res.status, StatusCode::NO_CONTENT);
134+
135+ // Re-using the same token now fails: the session row is gone.
136+ let res = send(&app, "GET", "/auth/me", Some(&ali), None).await;
137+ assert_eq!(res.status, StatusCode::UNAUTHORIZED);
138+}
139+
140+// --- notes ---------------------------------------------------------------
141+
142+#[tokio::test]
143+async fn notes_crud_is_scoped_to_owner() {
144+ let app = mem_app().await;
145+ let ali = login(&app, "ali").await;
146+ let veli = login(&app, "veli").await;
147+
148+ let res = send(
149+ &app,
150+ "POST",
151+ "/notes",
152+ Some(&ali),
153+ Some(json!({ "title": "first", "content": "hello" })),
154+ )
155+ .await;
156+ assert_eq!(res.status, StatusCode::CREATED);
157+ let note_id = id_of(&res.body);
158+
159+ // Partial update keeps the untouched field.
160+ let res = send(
161+ &app,
162+ "PATCH",
163+ &format!("/notes/{note_id}"),
164+ Some(&ali),
165+ Some(json!({ "content": "edited" })),
166+ )
167+ .await;
168+ assert_eq!(res.status, StatusCode::OK);
169+ assert_eq!(res.body["content"], "edited");
170+ assert_eq!(res.body["title"], "first");
171+
172+ // Owner sees exactly one; other user sees none and gets 404 on direct access.
173+ assert_eq!(
174+ send(&app, "GET", "/notes", Some(&ali), None)
175+ .await
176+ .body
177+ .as_array()
178+ .unwrap()
179+ .len(),
180+ 1
181+ );
182+ assert_eq!(
183+ send(&app, "GET", &format!("/notes/{note_id}"), Some(&veli), None)
184+ .await
185+ .status,
186+ StatusCode::NOT_FOUND
187+ );
188+ assert_eq!(
189+ send(&app, "GET", "/notes", Some(&veli), None)
190+ .await
191+ .body
192+ .as_array()
193+ .unwrap()
194+ .len(),
195+ 0
196+ );
197+
198+ // Other user cannot update or delete it either.
199+ assert_eq!(
200+ send(
201+ &app,
202+ "PATCH",
203+ &format!("/notes/{note_id}"),
204+ Some(&veli),
205+ Some(json!({"title":"x"}))
206+ )
207+ .await
208+ .status,
209+ StatusCode::NOT_FOUND
210+ );
211+ assert_eq!(
212+ send(
213+ &app,
214+ "DELETE",
215+ &format!("/notes/{note_id}"),
216+ Some(&veli),
217+ None
218+ )
219+ .await
220+ .status,
221+ StatusCode::NOT_FOUND
222+ );
223+
224+ // Delete, then it's gone.
225+ assert_eq!(
226+ send(
227+ &app,
228+ "DELETE",
229+ &format!("/notes/{note_id}"),
230+ Some(&ali),
231+ None
232+ )
233+ .await
234+ .status,
235+ StatusCode::NO_CONTENT
236+ );
237+ assert_eq!(
238+ send(&app, "GET", &format!("/notes/{note_id}"), Some(&ali), None)
239+ .await
240+ .status,
241+ StatusCode::NOT_FOUND
242+ );
243+}
244+
245+#[tokio::test]
246+async fn note_content_defaults_to_empty() {
247+ let app = mem_app().await;
248+ let ali = login(&app, "ali").await;
249+ let res = send(
250+ &app,
251+ "POST",
252+ "/notes",
253+ Some(&ali),
254+ Some(json!({ "title": "solo" })),
255+ )
256+ .await;
257+ assert_eq!(res.status, StatusCode::CREATED);
258+ assert_eq!(res.body["content"], "");
259+}
260+
261+#[tokio::test]
262+async fn note_validation_and_missing_ids() {
263+ let app = mem_app().await;
264+ let ali = login(&app, "ali").await;
265+
266+ // Blank title on create -> 400.
267+ assert_eq!(
268+ send(
269+ &app,
270+ "POST",
271+ "/notes",
272+ Some(&ali),
273+ Some(json!({ "title": " " }))
274+ )
275+ .await
276+ .status,
277+ StatusCode::BAD_REQUEST
278+ );
279+
280+ // Operations on a non-existent id -> 404.
281+ for method in ["GET", "PATCH", "DELETE"] {
282+ let body = (method == "PATCH").then(|| json!({ "title": "x" }));
283+ let res = send(&app, method, "/notes/does-not-exist", Some(&ali), body).await;
284+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{method}");
285+ }
286+
287+ // Blank title on update -> 400.
288+ let created = send(
289+ &app,
290+ "POST",
291+ "/notes",
292+ Some(&ali),
293+ Some(json!({ "title": "keep" })),
294+ )
295+ .await;
296+ let id = id_of(&created.body);
297+ assert_eq!(
298+ send(
299+ &app,
300+ "PATCH",
301+ &format!("/notes/{id}"),
302+ Some(&ali),
303+ Some(json!({ "title": "" }))
304+ )
305+ .await
306+ .status,
307+ StatusCode::BAD_REQUEST
308+ );
309+}
310+
311+// --- events + attendance -------------------------------------------------
312+
313+#[tokio::test]
314+async fn events_are_shared_but_creator_guarded() {
315+ let (app, db) = app_and_db().await;
316+ let ali = login_as(&app, &db, "ali", "teacher").await;
317+ let veli = login_as(&app, &db, "veli", "teacher").await;
318+
319+ let ev = send(
320+ &app,
321+ "POST",
322+ "/events",
323+ Some(&ali),
324+ Some(json!({ "title": "standup", "description": "daily" })),
325+ )
326+ .await;
327+ assert_eq!(ev.status, StatusCode::CREATED);
328+ let event_id = id_of(&ev.body);
329+
330+ // Any authenticated user can read the event and its roster.
331+ assert_eq!(
332+ send(
333+ &app,
334+ "GET",
335+ &format!("/events/{event_id}"),
336+ Some(&veli),
337+ None
338+ )
339+ .await
340+ .status,
341+ StatusCode::OK
342+ );
343+ assert_eq!(
344+ send(&app, "GET", "/events", Some(&veli), None)
345+ .await
346+ .body
347+ .as_array()
348+ .unwrap()
349+ .len(),
350+ 1
351+ );
352+
353+ // Non-creator cannot edit or delete.
354+ assert_eq!(
355+ send(
356+ &app,
357+ "PATCH",
358+ &format!("/events/{event_id}"),
359+ Some(&veli),
360+ Some(json!({"title":"hijack"}))
361+ )
362+ .await
363+ .status,
364+ StatusCode::FORBIDDEN
365+ );
366+ assert_eq!(
367+ send(
368+ &app,
369+ "DELETE",
370+ &format!("/events/{event_id}"),
371+ Some(&veli),
372+ None
373+ )
374+ .await
375+ .status,
376+ StatusCode::FORBIDDEN
377+ );
378+
379+ // Creator can edit (partial).
380+ let res = send(
381+ &app,
382+ "PATCH",
383+ &format!("/events/{event_id}"),
384+ Some(&ali),
385+ Some(json!({ "description": "moved" })),
386+ )
387+ .await;
388+ assert_eq!(res.status, StatusCode::OK);
389+ assert_eq!(res.body["description"], "moved");
390+ assert_eq!(res.body["title"], "standup");
391+
392+ // Blank title on update -> 400. Missing event -> 404.
393+ assert_eq!(
394+ send(
395+ &app,
396+ "PATCH",
397+ &format!("/events/{event_id}"),
398+ Some(&ali),
399+ Some(json!({"title":" "}))
400+ )
401+ .await
402+ .status,
403+ StatusCode::BAD_REQUEST
404+ );
405+ assert_eq!(
406+ send(&app, "GET", "/events/nope", Some(&ali), None)
407+ .await
408+ .status,
409+ StatusCode::NOT_FOUND
410+ );
411+}
412+
413+#[tokio::test]
414+async fn attendance_marking_and_upsert() {
415+ let (app, db) = app_and_db().await;
416+ let ali = login_as(&app, &db, "ali", "teacher").await;
417+ let veli = login(&app, "veli").await;
418+ let veli_id = id_of(&send(&app, "GET", "/auth/me", Some(&veli), None).await.body);
419+
420+ let event_id = id_of(
421+ &send(
422+ &app,
423+ "POST",
424+ "/events",
425+ Some(&ali),
426+ Some(json!({ "title": "standup" })),
427+ )
428+ .await
429+ .body,
430+ );
431+
432+ // Default target is the caller.
433+ let res = send(
434+ &app,
435+ "POST",
436+ &format!("/events/{event_id}/attendance"),
437+ Some(&ali),
438+ Some(json!({ "status": "present" })),
439+ )
440+ .await;
441+ assert_eq!(res.status, StatusCode::OK);
442+ assert_eq!(res.body["status"], "present");
443+
444+ // Mark veli, then re-mark: upsert keeps a single row (same id).
445+ let first = send(
446+ &app,
447+ "POST",
448+ &format!("/events/{event_id}/attendance"),
449+ Some(&ali),
450+ Some(json!({ "status": "late", "user_id": veli_id })),
451+ )
452+ .await;
453+ let second = send(
454+ &app,
455+ "POST",
456+ &format!("/events/{event_id}/attendance"),
457+ Some(&ali),
458+ Some(json!({ "status": "absent", "user_id": veli_id })),
459+ )
460+ .await;
461+ assert_eq!(
462+ id_of(&first.body),
463+ id_of(&second.body),
464+ "upsert same record"
465+ );
466+ assert_eq!(second.body["status"], "absent");
467+
468+ // Two rows total.
469+ assert_eq!(
470+ send(
471+ &app,
472+ "GET",
473+ &format!("/events/{event_id}/attendance"),
474+ Some(&ali),
475+ None
476+ )
477+ .await
478+ .body
479+ .as_array()
480+ .unwrap()
481+ .len(),
482+ 2
483+ );
484+
485+ // Remove veli -> one row; removing again -> 404.
486+ assert_eq!(
487+ send(
488+ &app,
489+ "DELETE",
490+ &format!("/events/{event_id}/attendance/{veli_id}"),
491+ Some(&ali),
492+ None
493+ )
494+ .await
495+ .status,
496+ StatusCode::NO_CONTENT
497+ );
498+ assert_eq!(
499+ send(
500+ &app,
501+ "GET",
502+ &format!("/events/{event_id}/attendance"),
503+ Some(&ali),
504+ None
505+ )
506+ .await
507+ .body
508+ .as_array()
509+ .unwrap()
510+ .len(),
511+ 1
512+ );
513+ assert_eq!(
514+ send(
515+ &app,
516+ "DELETE",
517+ &format!("/events/{event_id}/attendance/{veli_id}"),
518+ Some(&ali),
519+ None
520+ )
521+ .await
522+ .status,
523+ StatusCode::NOT_FOUND
524+ );
525+}
526+
527+#[tokio::test]
528+async fn attendance_input_validation() {
529+ let (app, db) = app_and_db().await;
530+ let ali = login_as(&app, &db, "ali", "teacher").await;
531+ let event_id = id_of(
532+ &send(
533+ &app,
534+ "POST",
535+ "/events",
536+ Some(&ali),
537+ Some(json!({ "title": "e" })),
538+ )
539+ .await
540+ .body,
541+ );
542+
543+ // Invalid status -> 400.
544+ assert_eq!(
545+ send(
546+ &app,
547+ "POST",
548+ &format!("/events/{event_id}/attendance"),
549+ Some(&ali),
550+ Some(json!({"status":"maybe"}))
551+ )
552+ .await
553+ .status,
554+ StatusCode::BAD_REQUEST
555+ );
556+
557+ // Unknown target user -> 400.
558+ assert_eq!(
559+ send(
560+ &app,
561+ "POST",
562+ &format!("/events/{event_id}/attendance"),
563+ Some(&ali),
564+ Some(json!({"status":"present","user_id":"ghost"}))
565+ )
566+ .await
567+ .status,
568+ StatusCode::BAD_REQUEST
569+ );
570+
571+ // Attendance on a missing event -> 404.
572+ assert_eq!(
573+ send(
574+ &app,
575+ "POST",
576+ "/events/nope/attendance",
577+ Some(&ali),
578+ Some(json!({"status":"present"}))
579+ )
580+ .await
581+ .status,
582+ StatusCode::NOT_FOUND
583+ );
584+}
585+
586+#[tokio::test]
587+async fn deleting_event_cascades_attendance() {
588+ let (app, db) = app_and_db().await;
589+ let ali = login_as(&app, &db, "ali", "teacher").await;
590+ let event_id = id_of(
591+ &send(
592+ &app,
593+ "POST",
594+ "/events",
595+ Some(&ali),
596+ Some(json!({ "title": "e" })),
597+ )
598+ .await
599+ .body,
600+ );
601+ send(
602+ &app,
603+ "POST",
604+ &format!("/events/{event_id}/attendance"),
605+ Some(&ali),
606+ Some(json!({"status":"present"})),
607+ )
608+ .await;
609+
610+ assert_eq!(
611+ send(
612+ &app,
613+ "DELETE",
614+ &format!("/events/{event_id}"),
615+ Some(&ali),
616+ None
617+ )
618+ .await
619+ .status,
620+ StatusCode::NO_CONTENT
621+ );
622+ // Event gone — and its roster endpoint with it (404, not an empty list).
623+ assert_eq!(
624+ send(
625+ &app,
626+ "GET",
627+ &format!("/events/{event_id}"),
628+ Some(&ali),
629+ None
630+ )
631+ .await
632+ .status,
633+ StatusCode::NOT_FOUND
634+ );
635+ assert_eq!(
636+ send(
637+ &app,
638+ "GET",
639+ &format!("/events/{event_id}/attendance"),
640+ Some(&ali),
641+ None
642+ )
643+ .await
644+ .status,
645+ StatusCode::NOT_FOUND
646+ );
647+}
648+
649+#[tokio::test]
650+async fn event_timestamps_echo_and_validate() {
651+ let (app, db) = app_and_db().await;
652+ let ali = login_as(&app, &db, "ali", "teacher").await;
653+
654+ // Create with unix-millis times.
655+ let res = send(
656+ &app,
657+ "POST",
658+ "/events",
659+ Some(&ali),
660+ Some(json!({ "title": "mtg", "starts_at": 1000, "ends_at": 2000 })),
661+ )
662+ .await;
663+ assert_eq!(res.status, StatusCode::CREATED);
664+ assert_eq!(res.body["starts_at"], 1000);
665+ assert_eq!(res.body["ends_at"], 2000);
666+ let event_id = id_of(&res.body);
667+
668+ // Omitted times serialize as null.
669+ let untimed = send(
670+ &app,
671+ "POST",
672+ "/events",
673+ Some(&ali),
674+ Some(json!({ "title": "notime" })),
675+ )
676+ .await;
677+ assert!(untimed.body["starts_at"].is_null());
678+ assert!(untimed.body["ends_at"].is_null());
679+
680+ // ends_at before starts_at -> 400.
681+ let bad = send(
682+ &app,
683+ "POST",
684+ "/events",
685+ Some(&ali),
686+ Some(json!({ "title": "bad", "starts_at": 5000, "ends_at": 1000 })),
687+ )
688+ .await;
689+ assert_eq!(bad.status, StatusCode::BAD_REQUEST);
690+
691+ // Updating only ends_at keeps starts_at.
692+ let updated = send(
693+ &app,
694+ "PATCH",
695+ &format!("/events/{event_id}"),
696+ Some(&ali),
697+ Some(json!({ "ends_at": 3000 })),
698+ )
699+ .await;
700+ assert_eq!(updated.status, StatusCode::OK);
701+ assert_eq!(updated.body["starts_at"], 1000);
702+ assert_eq!(updated.body["ends_at"], 3000);
703+}
704+
705+// --- exams + results -----------------------------------------------------
706+
707+#[tokio::test]
708+async fn exams_are_shared_but_creator_guarded() {
709+ let (app, db) = app_and_db().await;
710+ let ali = login_as(&app, &db, "ali", "teacher").await;
711+ let veli = login_as(&app, &db, "veli", "teacher").await;
712+
713+ let ex = send(
714+ &app,
715+ "POST",
716+ "/exams",
717+ Some(&ali),
718+ Some(json!({ "title": "ch3", "description": "algebra", "kind": "quiz" })),
719+ )
720+ .await;
721+ assert_eq!(ex.status, StatusCode::CREATED);
722+ assert_eq!(ex.body["kind"], "quiz");
723+ let exam_id = id_of(&ex.body);
724+
725+ // Any authenticated user can read the exam and the list.
726+ assert_eq!(
727+ send(&app, "GET", &format!("/exams/{exam_id}"), Some(&veli), None)
728+ .await
729+ .status,
730+ StatusCode::OK
731+ );
732+ assert_eq!(
733+ send(&app, "GET", "/exams", Some(&veli), None)
734+ .await
735+ .body
736+ .as_array()
737+ .unwrap()
738+ .len(),
739+ 1
740+ );
741+
742+ // Non-creator teacher cannot edit or delete.
743+ assert_eq!(
744+ send(
745+ &app,
746+ "PATCH",
747+ &format!("/exams/{exam_id}"),
748+ Some(&veli),
749+ Some(json!({"title":"hijack"}))
750+ )
751+ .await
752+ .status,
753+ StatusCode::FORBIDDEN
754+ );
755+ assert_eq!(
756+ send(
757+ &app,
758+ "DELETE",
759+ &format!("/exams/{exam_id}"),
760+ Some(&veli),
761+ None
762+ )
763+ .await
764+ .status,
765+ StatusCode::FORBIDDEN
766+ );
767+
768+ // Creator edits (partial) — kind flips homework, title kept.
769+ let res = send(
770+ &app,
771+ "PATCH",
772+ &format!("/exams/{exam_id}"),
773+ Some(&ali),
774+ Some(json!({ "kind": "homework" })),
775+ )
776+ .await;
777+ assert_eq!(res.status, StatusCode::OK);
778+ assert_eq!(res.body["kind"], "homework");
779+ assert_eq!(res.body["title"], "ch3");
780+}
781+
782+#[tokio::test]
783+async fn exam_input_validation() {
784+ let (app, db) = app_and_db().await;
785+ let ali = login_as(&app, &db, "ali", "teacher").await;
786+
787+ // Missing/blank title -> 400.
788+ assert_eq!(
789+ send(
790+ &app,
791+ "POST",
792+ "/exams",
793+ Some(&ali),
794+ Some(json!({"title":" ","kind":"quiz"}))
795+ )
796+ .await
797+ .status,
798+ StatusCode::BAD_REQUEST
799+ );
800+ // Unknown kind -> 400.
801+ assert_eq!(
802+ send(
803+ &app,
804+ "POST",
805+ "/exams",
806+ Some(&ali),
807+ Some(json!({"title":"t","kind":"final"}))
808+ )
809+ .await
810+ .status,
811+ StatusCode::BAD_REQUEST
812+ );
813+ // Missing exam -> 404.
814+ assert_eq!(
815+ send(&app, "GET", "/exams/nope", Some(&ali), None)
816+ .await
817+ .status,
818+ StatusCode::NOT_FOUND
819+ );
820+}
821+
822+#[tokio::test]
823+async fn grading_upsert_and_own_result() {
824+ let (app, db) = app_and_db().await;
825+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
826+ let alice = login(&app, "alice").await; // student
827+ let bob = login(&app, "bob").await; // student
828+ let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body);
829+
830+ let exam_id = id_of(
831+ &send(
832+ &app,
833+ "POST",
834+ "/exams",
835+ Some(&teacher),
836+ Some(json!({"title":"mt","kind":"quiz"})),
837+ )
838+ .await
839+ .body,
840+ );
841+
842+ // Before grading, the student's own result is 404.
843+ assert_eq!(
844+ send(
845+ &app,
846+ "GET",
847+ &format!("/exams/{exam_id}/result"),
848+ Some(&alice),
849+ None
850+ )
851+ .await
852+ .status,
853+ StatusCode::NOT_FOUND
854+ );
855+
856+ // Teacher grades alice, then re-grades: upsert keeps one row (same id).
857+ let first = send(
858+ &app,
859+ "POST",
860+ &format!("/exams/{exam_id}/results"),
861+ Some(&teacher),
862+ Some(json!({ "mark": 70, "user_id": alice_id })),
863+ )
864+ .await;
865+ assert_eq!(first.status, StatusCode::OK);
866+ let second = send(
867+ &app,
868+ "POST",
869+ &format!("/exams/{exam_id}/results"),
870+ Some(&teacher),
871+ Some(json!({ "mark": 88, "user_id": alice_id })),
872+ )
873+ .await;
874+ assert_eq!(
875+ id_of(&first.body),
876+ id_of(&second.body),
877+ "upsert same record"
878+ );
879+ assert_eq!(second.body["mark"], 88);
880+
881+ // Alice reads her own result; bob (ungraded) still 404s and can't see alice's.
882+ let mine = send(
883+ &app,
884+ "GET",
885+ &format!("/exams/{exam_id}/result"),
886+ Some(&alice),
887+ None,
888+ )
889+ .await;
890+ assert_eq!(mine.status, StatusCode::OK);
891+ assert_eq!(mine.body["mark"], 88);
892+ assert_eq!(
893+ send(
894+ &app,
895+ "GET",
896+ &format!("/exams/{exam_id}/result"),
897+ Some(&bob),
898+ None
899+ )
900+ .await
901+ .status,
902+ StatusCode::NOT_FOUND
903+ );
904+
905+ // Teacher sees the full list (one row).
906+ assert_eq!(
907+ send(
908+ &app,
909+ "GET",
910+ &format!("/exams/{exam_id}/results"),
911+ Some(&teacher),
912+ None
913+ )
914+ .await
915+ .body
916+ .as_array()
917+ .unwrap()
918+ .len(),
919+ 1
920+ );
921+
922+ // Remove alice's result -> her own read 404s again; removing again -> 404.
923+ assert_eq!(
924+ send(
925+ &app,
926+ "DELETE",
927+ &format!("/exams/{exam_id}/results/{alice_id}"),
928+ Some(&teacher),
929+ None
930+ )
931+ .await
932+ .status,
933+ StatusCode::NO_CONTENT
934+ );
935+ assert_eq!(
936+ send(
937+ &app,
938+ "GET",
939+ &format!("/exams/{exam_id}/result"),
940+ Some(&alice),
941+ None
942+ )
943+ .await
944+ .status,
945+ StatusCode::NOT_FOUND
946+ );
947+ assert_eq!(
948+ send(
949+ &app,
950+ "DELETE",
951+ &format!("/exams/{exam_id}/results/{alice_id}"),
952+ Some(&teacher),
953+ None
954+ )
955+ .await
956+ .status,
957+ StatusCode::NOT_FOUND
958+ );
959+}
960+
961+#[tokio::test]
962+async fn grading_rbac_and_validation() {
963+ let (app, db) = app_and_db().await;
964+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
965+ let alice = login(&app, "alice").await; // student
966+ let bob = login(&app, "bob").await; // student
967+ let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body);
968+
969+ let exam_id = id_of(
970+ &send(
971+ &app,
972+ "POST",
973+ "/exams",
974+ Some(&teacher),
975+ Some(json!({"title":"e","kind":"homework"})),
976+ )
977+ .await
978+ .body,
979+ );
980+
981+ // Students cannot create exams, grade anyone, list all results, or delete a result.
982+ assert_eq!(
983+ send(
984+ &app,
985+ "POST",
986+ "/exams",
987+ Some(&alice),
988+ Some(json!({"title":"x","kind":"quiz"}))
989+ )
990+ .await
991+ .status,
992+ StatusCode::FORBIDDEN
993+ );
994+ assert_eq!(
995+ send(
996+ &app,
997+ "POST",
998+ &format!("/exams/{exam_id}/results"),
999+ Some(&alice),
1000+ Some(json!({"mark":100,"user_id":alice_id}))
1001+ )
1002+ .await
1003+ .status,
1004+ StatusCode::FORBIDDEN
1005+ );
1006+ assert_eq!(
1007+ send(
1008+ &app,
1009+ "GET",
1010+ &format!("/exams/{exam_id}/results"),
1011+ Some(&alice),
1012+ None
1013+ )
1014+ .await
1015+ .status,
1016+ StatusCode::FORBIDDEN
1017+ );
1018+ assert_eq!(
1019+ send(
1020+ &app,
1021+ "DELETE",
1022+ &format!("/exams/{exam_id}/results/{alice_id}"),
1023+ Some(&bob),
1024+ None
1025+ )
1026+ .await
1027+ .status,
1028+ StatusCode::FORBIDDEN
1029+ );
1030+
1031+ // Mark out of range -> 400.
1032+ assert_eq!(
1033+ send(
1034+ &app,
1035+ "POST",
1036+ &format!("/exams/{exam_id}/results"),
1037+ Some(&teacher),
1038+ Some(json!({"mark":101,"user_id":alice_id}))
1039+ )
1040+ .await
1041+ .status,
1042+ StatusCode::BAD_REQUEST
1043+ );
1044+ // Unknown target user -> 400.
1045+ assert_eq!(
1046+ send(
1047+ &app,
1048+ "POST",
1049+ &format!("/exams/{exam_id}/results"),
1050+ Some(&teacher),
1051+ Some(json!({"mark":50,"user_id":"ghost"}))
1052+ )
1053+ .await
1054+ .status,
1055+ StatusCode::BAD_REQUEST
1056+ );
1057+ // Grading on a missing exam -> 404.
1058+ assert_eq!(
1059+ send(
1060+ &app,
1061+ "POST",
1062+ "/exams/nope/results",
1063+ Some(&teacher),
1064+ Some(json!({"mark":50,"user_id":alice_id}))
1065+ )
1066+ .await
1067+ .status,
1068+ StatusCode::NOT_FOUND
1069+ );
1070+}
1071+
1072+#[tokio::test]
1073+async fn deleting_exam_cascades_results() {
1074+ let (app, db) = app_and_db().await;
1075+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
1076+ let alice = login(&app, "alice").await;
1077+ let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body);
1078+
1079+ let exam_id = id_of(
1080+ &send(
1081+ &app,
1082+ "POST",
1083+ "/exams",
1084+ Some(&teacher),
1085+ Some(json!({"title":"e","kind":"quiz"})),
1086+ )
1087+ .await
1088+ .body,
1089+ );
1090+ send(
1091+ &app,
1092+ "POST",
1093+ &format!("/exams/{exam_id}/results"),
1094+ Some(&teacher),
1095+ Some(json!({"mark":60,"user_id":alice_id})),
1096+ )
1097+ .await;
1098+
1099+ assert_eq!(
1100+ send(
1101+ &app,
1102+ "DELETE",
1103+ &format!("/exams/{exam_id}"),
1104+ Some(&teacher),
1105+ None
1106+ )
1107+ .await
1108+ .status,
1109+ StatusCode::NO_CONTENT
1110+ );
1111+ // Exam gone; the student's result is gone with it.
1112+ assert_eq!(
1113+ send(
1114+ &app,
1115+ "GET",
1116+ &format!("/exams/{exam_id}"),
1117+ Some(&teacher),
1118+ None
1119+ )
1120+ .await
1121+ .status,
1122+ StatusCode::NOT_FOUND
1123+ );
1124+ assert_eq!(
1125+ send(
1126+ &app,
1127+ "GET",
1128+ &format!("/exams/{exam_id}/result"),
1129+ Some(&alice),
1130+ None
1131+ )
1132+ .await
1133+ .status,
1134+ StatusCode::NOT_FOUND
1135+ );
1136+}
1137+
1138+// --- roles / RBAC --------------------------------------------------------
1139+
1140+#[tokio::test]
1141+async fn students_cannot_create_events() {
1142+ let app = mem_app().await;
1143+ let ali = login(&app, "ali").await; // default role: student
1144+ let res = send(
1145+ &app,
1146+ "POST",
1147+ "/events",
1148+ Some(&ali),
1149+ Some(json!({ "title": "class" })),
1150+ )
1151+ .await;
1152+ assert_eq!(res.status, StatusCode::FORBIDDEN);
1153+}
1154+
1155+#[tokio::test]
1156+async fn students_mark_only_themselves() {
1157+ let (app, db) = app_and_db().await;
1158+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
1159+ let alice = login(&app, "alice").await; // student
1160+ let bob = login(&app, "bob").await; // student
1161+ let bob_id = id_of(&send(&app, "GET", "/auth/me", Some(&bob), None).await.body);
1162+
1163+ let ev = id_of(
1164+ &send(
1165+ &app,
1166+ "POST",
1167+ "/events",
1168+ Some(&teacher),
1169+ Some(json!({ "title": "class" })),
1170+ )
1171+ .await
1172+ .body,
1173+ );
1174+
1175+ // A student may mark their own attendance.
1176+ assert_eq!(
1177+ send(
1178+ &app,
1179+ "POST",
1180+ &format!("/events/{ev}/attendance"),
1181+ Some(&alice),
1182+ Some(json!({"status":"present"}))
1183+ )
1184+ .await
1185+ .status,
1186+ StatusCode::OK
1187+ );
1188+ // But not someone else's.
1189+ assert_eq!(
1190+ send(
1191+ &app,
1192+ "POST",
1193+ &format!("/events/{ev}/attendance"),
1194+ Some(&alice),
1195+ Some(json!({"status":"present","user_id":bob_id}))
1196+ )
1197+ .await
1198+ .status,
1199+ StatusCode::FORBIDDEN
1200+ );
1201+ // And cannot remove attendance rows.
1202+ assert_eq!(
1203+ send(
1204+ &app,
1205+ "DELETE",
1206+ &format!("/events/{ev}/attendance/{bob_id}"),
1207+ Some(&alice),
1208+ None
1209+ )
1210+ .await
1211+ .status,
1212+ StatusCode::FORBIDDEN
1213+ );
1214+}
1215+
1216+#[tokio::test]
1217+async fn event_management_follows_hierarchy() {
1218+ let (app, db) = app_and_db().await;
1219+ let owner = login_as(&app, &db, "owner", "teacher").await;
1220+ let other = login_as(&app, &db, "other", "teacher").await;
1221+ let boss = login_as(&app, &db, "boss", "manager").await;
1222+
1223+ let ev = id_of(
1224+ &send(
1225+ &app,
1226+ "POST",
1227+ "/events",
1228+ Some(&owner),
1229+ Some(json!({ "title": "orig" })),
1230+ )
1231+ .await
1232+ .body,
1233+ );
1234+
1235+ // A different teacher (not the creator) cannot edit it.
1236+ assert_eq!(
1237+ send(
1238+ &app,
1239+ "PATCH",
1240+ &format!("/events/{ev}"),
1241+ Some(&other),
1242+ Some(json!({"title":"hijack"}))
1243+ )
1244+ .await
1245+ .status,
1246+ StatusCode::FORBIDDEN
1247+ );
1248+ // A manager can edit anyone's event.
1249+ let res = send(
1250+ &app,
1251+ "PATCH",
1252+ &format!("/events/{ev}"),
1253+ Some(&boss),
1254+ Some(json!({"title":"by mgr"})),
1255+ )
1256+ .await;
1257+ assert_eq!(res.status, StatusCode::OK);
1258+ assert_eq!(res.body["title"], "by mgr");
1259+ // The creator can still delete their own.
1260+ assert_eq!(
1261+ send(&app, "DELETE", &format!("/events/{ev}"), Some(&owner), None)
1262+ .await
1263+ .status,
1264+ StatusCode::NO_CONTENT
1265+ );
1266+}
1267+
1268+#[tokio::test]
1269+async fn admin_manages_roles_with_guards() {
1270+ let (app, db) = app_and_db().await;
1271+ let admin = login_as(&app, &db, "admin", "admin").await;
1272+ let alice = login(&app, "alice").await; // student
1273+ let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body);
1274+
1275+ // Non-admins cannot reach the role endpoints.
1276+ assert_eq!(
1277+ send(&app, "GET", "/users", Some(&alice), None).await.status,
1278+ StatusCode::FORBIDDEN
1279+ );
1280+ assert_eq!(
1281+ send(
1282+ &app,
1283+ "PATCH",
1284+ &format!("/users/{alice_id}/role"),
1285+ Some(&alice),
1286+ Some(json!({"role":"teacher"}))
1287+ )
1288+ .await
1289+ .status,
1290+ StatusCode::FORBIDDEN
1291+ );
1292+
1293+ // Admin lists users (at least admin + alice).
1294+ let list = send(&app, "GET", "/users", Some(&admin), None).await;
1295+ assert_eq!(list.status, StatusCode::OK);
1296+ assert!(list.body.as_array().unwrap().len() >= 2);
1297+
1298+ // Admin promotes alice to teacher; the change is reflected in the response...
1299+ let promoted = send(
1300+ &app,
1301+ "PATCH",
1302+ &format!("/users/{alice_id}/role"),
1303+ Some(&admin),
1304+ Some(json!({"role":"teacher"})),
1305+ )
1306+ .await;
1307+ assert_eq!(promoted.status, StatusCode::OK);
1308+ assert_eq!(promoted.body["role"], "teacher");
1309+ // ...and takes effect immediately: alice can now create events.
1310+ assert_eq!(
1311+ send(
1312+ &app,
1313+ "POST",
1314+ "/events",
1315+ Some(&alice),
1316+ Some(json!({ "title": "now allowed" }))
1317+ )
1318+ .await
1319+ .status,
1320+ StatusCode::CREATED
1321+ );
1322+
1323+ // Unknown role value -> 400.
1324+ assert_eq!(
1325+ send(
1326+ &app,
1327+ "PATCH",
1328+ &format!("/users/{alice_id}/role"),
1329+ Some(&admin),
1330+ Some(json!({"role":"wizard"}))
1331+ )
1332+ .await
1333+ .status,
1334+ StatusCode::BAD_REQUEST
1335+ );
1336+ // Missing user -> 404.
1337+ assert_eq!(
1338+ send(
1339+ &app,
1340+ "PATCH",
1341+ "/users/does-not-exist/role",
1342+ Some(&admin),
1343+ Some(json!({"role":"teacher"}))
1344+ )
1345+ .await
1346+ .status,
1347+ StatusCode::NOT_FOUND
1348+ );
1349+ // An admin cannot change their own role (anti-lockout guard).
1350+ let admin_id = id_of(&send(&app, "GET", "/auth/me", Some(&admin), None).await.body);
1351+ assert_eq!(
1352+ send(
1353+ &app,
1354+ "PATCH",
1355+ &format!("/users/{admin_id}/role"),
1356+ Some(&admin),
1357+ Some(json!({"role":"student"}))
1358+ )
1359+ .await
1360+ .status,
1361+ StatusCode::FORBIDDEN
1362+ );
1363+}
1364+
1365+// --- regression: race safety, session hygiene, CORS ----------------------
1366+
1367+/// #1 — Many concurrent marks for the *same* (event, user). A find-then-insert
1368+/// implementation races the unique index and 500s; the atomic composite-id
1369+/// upsert must let every request succeed and leave exactly one row.
1370+#[tokio::test]
1371+async fn concurrent_attendance_marks_never_collide() {
1372+ let (app, db) = app_and_db().await;
1373+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
1374+ let student = login(&app, "student").await;
1375+ let student_id = id_of(
1376+ &send(&app, "GET", "/auth/me", Some(&student), None)
1377+ .await
1378+ .body,
1379+ );
1380+ let event_id = id_of(
1381+ &send(
1382+ &app,
1383+ "POST",
1384+ "/events",
1385+ Some(&teacher),
1386+ Some(json!({ "title": "e" })),
1387+ )
1388+ .await
1389+ .body,
1390+ );
1391+
1392+ let mut handles = Vec::new();
1393+ for i in 0..24 {
1394+ let app = app.clone();
1395+ let teacher = teacher.clone();
1396+ let uri = format!("/events/{event_id}/attendance");
1397+ let status = if i % 2 == 0 { "present" } else { "late" };
1398+ let body = json!({ "status": status, "user_id": student_id });
1399+ handles.push(tokio::spawn(async move {
1400+ send(&app, "POST", &uri, Some(&teacher), Some(body))
1401+ .await
1402+ .status
1403+ }));
1404+ }
1405+ for h in handles {
1406+ assert_eq!(
1407+ h.await.unwrap(),
1408+ StatusCode::OK,
1409+ "concurrent mark must not fail"
1410+ );
1411+ }
1412+
1413+ let roster = send(
1414+ &app,
1415+ "GET",
1416+ &format!("/events/{event_id}/attendance"),
1417+ Some(&teacher),
1418+ None,
1419+ )
1420+ .await;
1421+ assert_eq!(
1422+ roster.body.as_array().unwrap().len(),
1423+ 1,
1424+ "upsert keeps a single row"
1425+ );
1426+}
1427+
1428+/// #1 — Same guarantee for exam grading.
1429+#[tokio::test]
1430+async fn concurrent_exam_grades_never_collide() {
1431+ let (app, db) = app_and_db().await;
1432+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
1433+ let student = login(&app, "student").await;
1434+ let student_id = id_of(
1435+ &send(&app, "GET", "/auth/me", Some(&student), None)
1436+ .await
1437+ .body,
1438+ );
1439+ let exam_id = id_of(
1440+ &send(
1441+ &app,
1442+ "POST",
1443+ "/exams",
1444+ Some(&teacher),
1445+ Some(json!({ "title": "e", "kind": "quiz" })),
1446+ )
1447+ .await
1448+ .body,
1449+ );
1450+
1451+ let mut handles = Vec::new();
1452+ for mark in 0..24i64 {
1453+ let app = app.clone();
1454+ let teacher = teacher.clone();
1455+ let uri = format!("/exams/{exam_id}/results");
1456+ let body = json!({ "mark": mark, "user_id": student_id });
1457+ handles.push(tokio::spawn(async move {
1458+ send(&app, "POST", &uri, Some(&teacher), Some(body))
1459+ .await
1460+ .status
1461+ }));
1462+ }
1463+ for h in handles {
1464+ assert_eq!(
1465+ h.await.unwrap(),
1466+ StatusCode::OK,
1467+ "concurrent grade must not fail"
1468+ );
1469+ }
1470+
1471+ let results = send(
1472+ &app,
1473+ "GET",
1474+ &format!("/exams/{exam_id}/results"),
1475+ Some(&teacher),
1476+ None,
1477+ )
1478+ .await;
1479+ assert_eq!(
1480+ results.body.as_array().unwrap().len(),
1481+ 1,
1482+ "upsert keeps a single row"
1483+ );
1484+}
1485+
1486+/// #2 — A successful login sweeps expired session rows but leaves live ones.
1487+#[tokio::test]
1488+async fn login_purges_expired_sessions() {
1489+ let (app, db) = app_and_db().await;
1490+ let ali = login(&app, "ali").await; // one live session
1491+
1492+ // Inject a session that has already expired.
1493+ db.query("CREATE session SET user = type::record('user', $u), token = 'expired-token', expires_at = 1")
1494+ .bind(("u", "nobody".to_string()))
1495+ .await
1496+ .unwrap()
1497+ .check()
1498+ .unwrap();
1499+ assert!(
1500+ Session::find_by_token("expired-token", &db)
1501+ .await
1502+ .unwrap()
1503+ .is_some()
1504+ );
1505+
1506+ // A later successful login sweeps expired rows...
1507+ login(&app, "veli").await;
1508+ assert!(
1509+ Session::find_by_token("expired-token", &db)
1510+ .await
1511+ .unwrap()
1512+ .is_none(),
1513+ "expired session should be purged on login"
1514+ );
1515+ // ...while the still-valid session keeps working.
1516+ assert_eq!(
1517+ send(&app, "GET", "/auth/me", Some(&ali), None).await.status,
1518+ StatusCode::OK
1519+ );
1520+}
1521+
1522+/// Regression: `Username::try_new` used to validate the trimmed value but store
1523+/// the raw input, so `"ali"`, `"ali "` and `" ali"` were three distinct,
1524+/// visually identical accounts — and a user who registered with padding could
1525+/// only log in by reproducing it exactly. The name must be canonicalized
1526+/// (trimmed) at construction and at login lookup.
1527+#[tokio::test]
1528+async fn padded_usernames_are_canonicalized_not_distinct_accounts() {
1529+ let app = mem_app().await;
1530+
1531+ let res = send(
1532+ &app,
1533+ "POST",
1534+ "/auth/register",
1535+ None,
1536+ Some(json!({ "username": "ali", "password": "secret1" })),
1537+ )
1538+ .await;
1539+ assert_eq!(res.status, StatusCode::CREATED);
1540+
1541+ // Padding must not mint a lookalike account.
1542+ for spoof in ["ali ", " ali", " ali "] {
1543+ let res = send(
1544+ &app,
1545+ "POST",
1546+ "/auth/register",
1547+ None,
1548+ Some(json!({ "username": spoof, "password": "secret1" })),
1549+ )
1550+ .await;
1551+ assert_eq!(
1552+ res.status,
1553+ StatusCode::CONFLICT,
1554+ "{spoof:?} must collide with \"ali\""
1555+ );
1556+ }
1557+
1558+ // A name registered with padding is stored trimmed...
1559+ let res = send(
1560+ &app,
1561+ "POST",
1562+ "/auth/register",
1563+ None,
1564+ Some(json!({ "username": " veli ", "password": "secret1" })),
1565+ )
1566+ .await;
1567+ assert_eq!(res.status, StatusCode::CREATED);
1568+ assert_eq!(res.body["username"], "veli");
1569+
1570+ // ...and the login lookup tolerates padding the same way registration does.
1571+ for attempt in ["veli", " veli "] {
1572+ let res = send(
1573+ &app,
1574+ "POST",
1575+ "/auth/login",
1576+ None,
1577+ Some(json!({ "username": attempt, "password": "secret1" })),
1578+ )
1579+ .await;
1580+ assert_eq!(res.status, StatusCode::OK, "login as {attempt:?}");
1581+ }
1582+}
1583+
1584+/// Regression: the grade endpoint verified the exam, the mark, and that the
1585+/// target exists — but never that the grader isn't the target, so any teacher
1586+/// could write their own mark. "Grading never targets oneself" (README).
1587+#[tokio::test]
1588+async fn graders_cannot_grade_themselves() {
1589+ let (app, db) = app_and_db().await;
1590+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
1591+ let boss = login_as(&app, &db, "boss", "manager").await;
1592+ let teacher_id = id_of(
1593+ &send(&app, "GET", "/auth/me", Some(&teacher), None)
1594+ .await
1595+ .body,
1596+ );
1597+ let boss_id = id_of(&send(&app, "GET", "/auth/me", Some(&boss), None).await.body);
1598+
1599+ let exam_id = id_of(
1600+ &send(
1601+ &app,
1602+ "POST",
1603+ "/exams",
1604+ Some(&teacher),
1605+ Some(json!({"title":"t","kind":"quiz"})),
1606+ )
1607+ .await
1608+ .body,
1609+ );
1610+
1611+ // Self-grading is forbidden at every privilege level, not just for teachers.
1612+ for (cookie, own_id) in [(&teacher, &teacher_id), (&boss, &boss_id)] {
1613+ let res = send(
1614+ &app,
1615+ "POST",
1616+ &format!("/exams/{exam_id}/results"),
1617+ Some(cookie),
1618+ Some(json!({ "mark": 100, "user_id": own_id })),
1619+ )
1620+ .await;
1621+ assert_eq!(
1622+ res.status,
1623+ StatusCode::FORBIDDEN,
1624+ "self-grade must be rejected"
1625+ );
1626+ }
1627+
1628+ // And the rejected attempts wrote nothing.
1629+ assert_eq!(
1630+ send(
1631+ &app,
1632+ "GET",
1633+ &format!("/exams/{exam_id}/results"),
1634+ Some(&teacher),
1635+ None
1636+ )
1637+ .await
1638+ .body
1639+ .as_array()
1640+ .unwrap()
1641+ .len(),
1642+ 0
1643+ );
1644+
1645+ // Grading someone *else* still works (boss grades teacher).
1646+ let res = send(
1647+ &app,
1648+ "POST",
1649+ &format!("/exams/{exam_id}/results"),
1650+ Some(&boss),
1651+ Some(json!({ "mark": 90, "user_id": teacher_id })),
1652+ )
1653+ .await;
1654+ assert_eq!(res.status, StatusCode::OK);
1655+}
1656+
1657+/// Regression: `User::create` pre-checks the username and then inserts, so two
1658+/// concurrent registrations of the same name could both pass the check; the
1659+/// loser then hit the unique index and surfaced as a raw 500. A lost race must
1660+/// report the same 409 as the sequential duplicate, and exactly one account may
1661+/// exist afterwards.
1662+#[tokio::test]
1663+async fn concurrent_duplicate_registrations_conflict_not_500() {
1664+ let (app, db) = app_and_db().await;
1665+
1666+ let mut handles = Vec::new();
1667+ for _ in 0..24 {
1668+ let app = app.clone();
1669+ handles.push(tokio::spawn(async move {
1670+ send(
1671+ &app,
1672+ "POST",
1673+ "/auth/register",
1674+ None,
1675+ Some(json!({ "username": "dup", "password": "secret1" })),
1676+ )
1677+ .await
1678+ .status
1679+ }));
1680+ }
1681+
1682+ let mut created = 0;
1683+ for h in handles {
1684+ match h.await.unwrap() {
1685+ StatusCode::CREATED => created += 1,
1686+ StatusCode::CONFLICT => {}
1687+ other => panic!("unexpected status {other} — a lost race must be a 409, not a 500"),
1688+ }
1689+ }
1690+ assert_eq!(created, 1, "exactly one registration wins");
1691+
1692+ // Exactly one row exists for the name.
1693+ let users: Vec<hezarfen_backend::domain::user::User> = db
1694+ .query("SELECT * FROM user WHERE username = 'dup'")
1695+ .await
1696+ .unwrap()
1697+ .check()
1698+ .unwrap()
1699+ .take(0)
1700+ .unwrap();
1701+ assert_eq!(
1702+ users.len(),
1703+ 1,
1704+ "exactly one user row for the duplicated name"
1705+ );
1706+}
1707+
1708+/// Regression: listing a child collection of a missing parent used to return an
1709+/// empty 200 list — indistinguishable from "exists but empty". A missing parent
1710+/// is a 404, matching the write endpoints on the same paths.
1711+#[tokio::test]
1712+async fn child_lists_of_missing_parents_are_404() {
1713+ let (app, db) = app_and_db().await;
1714+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
1715+
1716+ assert_eq!(
1717+ send(&app, "GET", "/events/nope/attendance", Some(&teacher), None)
1718+ .await
1719+ .status,
1720+ StatusCode::NOT_FOUND
1721+ );
1722+ assert_eq!(
1723+ send(&app, "GET", "/exams/nope/results", Some(&teacher), None)
1724+ .await
1725+ .status,
1726+ StatusCode::NOT_FOUND
1727+ );
1728+}
1729+
1730+/// Regression: the session cookie never carried the `Secure` attribute, so a
1731+/// TLS deployment would let browsers replay it over plain HTTP. The attribute
1732+/// now follows `COOKIE_SECURE` (`Config::cookie_secure`); the default stays off
1733+/// so plain-HTTP local dev keeps working.
1734+#[tokio::test]
1735+async fn session_cookie_secure_attribute_follows_config() {
1736+ async fn login_set_cookie(app: &axum::Router) -> String {
1737+ let creds = json!({ "username": "ada", "password": "secret1" });
1738+ assert_eq!(
1739+ send(app, "POST", "/auth/register", None, Some(creds.clone()))
1740+ .await
1741+ .status,
1742+ StatusCode::CREATED
1743+ );
1744+ let req = Request::builder()
1745+ .method("POST")
1746+ .uri("/auth/login")
1747+ .header("content-type", "application/json")
1748+ .body(Body::from(creds.to_string()))
1749+ .unwrap();
1750+ let res = app.clone().oneshot(req).await.unwrap();
1751+ assert_eq!(res.status(), StatusCode::OK);
1752+ res.headers()
1753+ .get("set-cookie")
1754+ .unwrap()
1755+ .to_str()
1756+ .unwrap()
1757+ .to_string()
1758+ }
1759+
1760+ // Default (dev): HttpOnly but not Secure.
1761+ let plain = login_set_cookie(&mem_app().await).await;
1762+ assert!(
1763+ plain.contains("HttpOnly"),
1764+ "cookie must stay HttpOnly: {plain}"
1765+ );
1766+ assert!(
1767+ !plain.contains("Secure"),
1768+ "dev cookie must not be Secure: {plain}"
1769+ );
1770+
1771+ // With the flag on: Secure present.
1772+ let db = database::init_mem().await.unwrap();
1773+ let app = build_router(AppState {
1774+ db,
1775+ cookie_secure: true,
1776+ rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
1777+ });
1778+ let secure = login_set_cookie(&app).await;
1779+ assert!(
1780+ secure.contains("Secure"),
1781+ "cookie must be Secure when configured: {secure}"
1782+ );
1783+ assert!(
1784+ secure.contains("HttpOnly"),
1785+ "Secure must not displace HttpOnly: {secure}"
1786+ );
1787+}
1788+
1789+/// Regression: PATCH could set an event's times but never clear them — a JSON
1790+/// `null` was indistinguishable from an omitted field and silently kept the old
1791+/// value. An explicit `null` now clears the field; omitted still keeps it.
1792+#[tokio::test]
1793+async fn patch_null_clears_event_times() {
1794+ let (app, db) = app_and_db().await;
1795+ let ali = login_as(&app, &db, "ali", "teacher").await;
1796+ let event_id = id_of(
1797+ &send(
1798+ &app,
1799+ "POST",
1800+ "/events",
1801+ Some(&ali),
1802+ Some(json!({"title":"mtg","starts_at":1000,"ends_at":2000})),
1803+ )
1804+ .await
1805+ .body,
1806+ );
1807+
1808+ // Omitted fields still keep their values.
1809+ let res = send(
1810+ &app,
1811+ "PATCH",
1812+ &format!("/events/{event_id}"),
1813+ Some(&ali),
1814+ Some(json!({"title":"mtg2"})),
1815+ )
1816+ .await;
1817+ assert_eq!(res.body["starts_at"], 1000);
1818+ assert_eq!(res.body["ends_at"], 2000);
1819+
1820+ // An explicit null clears just that field.
1821+ let res = send(
1822+ &app,
1823+ "PATCH",
1824+ &format!("/events/{event_id}"),
1825+ Some(&ali),
1826+ Some(json!({"ends_at": null})),
1827+ )
1828+ .await;
1829+ assert_eq!(res.status, StatusCode::OK);
1830+ assert_eq!(res.body["starts_at"], 1000);
1831+ assert!(res.body["ends_at"].is_null());
1832+
1833+ // With ends_at cleared, moving starts_at past the old end is legal...
1834+ assert_eq!(
1835+ send(
1836+ &app,
1837+ "PATCH",
1838+ &format!("/events/{event_id}"),
1839+ Some(&ali),
1840+ Some(json!({"starts_at": 5000}))
1841+ )
1842+ .await
1843+ .status,
1844+ StatusCode::OK
1845+ );
1846+ // ...and a new ends_at before starts_at is still rejected.
1847+ assert_eq!(
1848+ send(
1849+ &app,
1850+ "PATCH",
1851+ &format!("/events/{event_id}"),
1852+ Some(&ali),
1853+ Some(json!({"ends_at": 1}))
1854+ )
1855+ .await
1856+ .status,
1857+ StatusCode::BAD_REQUEST
1858+ );
1859+
1860+ // Clearing both works.
1861+ let res = send(
1862+ &app,
1863+ "PATCH",
1864+ &format!("/events/{event_id}"),
1865+ Some(&ali),
1866+ Some(json!({"starts_at": null, "ends_at": null})),
1867+ )
1868+ .await;
1869+ assert!(res.body["starts_at"].is_null());
1870+ assert!(res.body["ends_at"].is_null());
1871+}
1872+
1873+/// #4 — CORS echoes the caller's origin and allows credentials, never `*`
1874+/// (which browsers reject for cookie-bearing requests).
1875+#[tokio::test]
1876+async fn cors_is_credential_safe_not_wildcard() {
1877+ let app = mem_app().await;
1878+ let req = Request::builder()
1879+ .method("GET")
1880+ .uri("/health")
1881+ .header("origin", "https://client.example")
1882+ .body(Body::empty())
1883+ .unwrap();
1884+ let res = app.oneshot(req).await.unwrap();
1885+ let headers = res.headers();
1886+ assert_eq!(
1887+ headers.get("access-control-allow-origin").unwrap(),
1888+ "https://client.example",
1889+ "origin must be reflected, not wildcarded"
1890+ );
1891+ assert_eq!(
1892+ headers.get("access-control-allow-credentials").unwrap(),
1893+ "true",
1894+ );
1895+}
tests/persistence.rsadded+147 -0
@@ -0,0 +1,147 @@
1+//! File-backed engine tests: exercise the real surrealkv storage path (not the
2+//! in-memory engine used elsewhere) against a throwaway `tempfile` directory,
3+//! including surviving a full close + reopen.
4+
5+mod common;
6+
7+use std::time::Duration;
8+
9+use axum::http::StatusCode;
10+use common::send;
11+use hezarfen_backend::config::Config;
12+use hezarfen_backend::database::Database;
13+use hezarfen_backend::rate_limit::RateLimitConfig;
14+use hezarfen_backend::state::AppState;
15+use hezarfen_backend::{build_router, database};
16+use serde_json::json;
17+use tempfile::TempDir;
18+
19+/// Re-open the on-disk database. surrealkv releases its file lock asynchronously
20+/// once the previous handle drops, so we retry briefly — a real restart is a new
21+/// process, which never contends.
22+async fn reopen(cfg: &Config) -> Database {
23+ for _ in 0..100 {
24+ match database::init(cfg).await {
25+ Ok(db) => return db,
26+ Err(_) => tokio::time::sleep(Duration::from_millis(50)).await,
27+ }
28+ }
29+ database::init(cfg).await.expect("reopen after retries")
30+}
31+
32+fn config_at(dir: &TempDir) -> Config {
33+ Config {
34+ host: "127.0.0.1".into(),
35+ port: 0,
36+ db_path: dir.path().join("hezarfen.db").to_str().unwrap().to_string(),
37+ db_ns: "hezarfen".into(),
38+ db_name: "hezarfen".into(),
39+ cookie_secure: false,
40+ rate_limit: RateLimitConfig::unlimited(),
41+ }
42+}
43+
44+fn state(db: Database) -> AppState {
45+ AppState {
46+ db,
47+ cookie_secure: false,
48+ rate_limit: RateLimitConfig::unlimited(),
49+ }
50+}
51+
52+/// The full flow works against the on-disk engine, same as in-memory.
53+#[tokio::test]
54+async fn file_engine_runs_full_flow() {
55+ let dir = tempfile::tempdir().unwrap();
56+ let db = database::init(&config_at(&dir))
57+ .await
58+ .expect("open file db");
59+ let app = build_router(state(db));
60+
61+ let creds = json!({ "username": "ali", "password": "secret1" });
62+ assert_eq!(
63+ send(&app, "POST", "/auth/register", None, Some(creds.clone()))
64+ .await
65+ .status,
66+ StatusCode::CREATED
67+ );
68+ let cookie = send(&app, "POST", "/auth/login", None, Some(creds))
69+ .await
70+ .cookie
71+ .unwrap();
72+
73+ let note = send(
74+ &app,
75+ "POST",
76+ "/notes",
77+ Some(&cookie),
78+ Some(json!({ "title": "disk" })),
79+ )
80+ .await;
81+ assert_eq!(note.status, StatusCode::CREATED);
82+ assert_eq!(
83+ send(&app, "GET", "/notes", Some(&cookie), None)
84+ .await
85+ .body
86+ .as_array()
87+ .unwrap()
88+ .len(),
89+ 1
90+ );
91+}
92+
93+/// Data written in one process lifetime is still readable after closing and
94+/// re-opening the database at the same path (list endpoints do table scans).
95+#[tokio::test]
96+async fn data_survives_reopen() {
97+ let dir = tempfile::tempdir().unwrap();
98+ let cfg = config_at(&dir);
99+ let creds = json!({ "username": "ali", "password": "secret1" });
100+
101+ // First boot: create a user and a note, then drop the handle.
102+ {
103+ let db = database::init(&cfg).await.expect("first open");
104+ let app = build_router(state(db));
105+ assert_eq!(
106+ send(&app, "POST", "/auth/register", None, Some(creds.clone()))
107+ .await
108+ .status,
109+ StatusCode::CREATED
110+ );
111+ let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone()))
112+ .await
113+ .cookie
114+ .unwrap();
115+ assert_eq!(
116+ send(
117+ &app,
118+ "POST",
119+ "/notes",
120+ Some(&cookie),
121+ Some(json!({ "title": "persisted" }))
122+ )
123+ .await
124+ .status,
125+ StatusCode::CREATED
126+ );
127+ }
128+
129+ // Second boot from the same path: the user and note are still there.
130+ {
131+ let db = reopen(&cfg).await;
132+ let app = build_router(state(db));
133+ let login = send(&app, "POST", "/auth/login", None, Some(creds)).await;
134+ assert_eq!(login.status, StatusCode::OK, "user survived reopen");
135+ let cookie = login.cookie.unwrap();
136+ let notes = send(&app, "GET", "/notes", Some(&cookie), None).await;
137+ assert_eq!(
138+ notes.status,
139+ StatusCode::OK,
140+ "notes list body: {}",
141+ notes.body
142+ );
143+ let rows = notes.body.as_array().unwrap();
144+ assert_eq!(rows.len(), 1, "note survived reopen");
145+ assert_eq!(rows[0]["title"], "persisted");
146+ }
147+}
tests/rate_limit.rsadded+477 -0
@@ -0,0 +1,477 @@
1+//! Router-level rate limiting tests. Each test builds the app with a
2+//! deliberately tight [`RateLimitConfig`] and, with `trust_proxy` on, poses as
3+//! different clients via the `X-Forwarded-For` header — `oneshot` requests
4+//! carry no real peer address, so the header path is also the only way to
5+//! separate callers here. The final tests instead boot a real TCP server to
6+//! exercise the peer-address (`ConnectInfo`) keying exactly as production runs
7+//! it. Window-arithmetic and header-parsing edge cases live as unit tests in
8+//! `src/rate_limit.rs` under paused tokio time.
9+
10+use axum::Router;
11+use axum::body::Body;
12+use axum::http::{Request, StatusCode};
13+use hezarfen_backend::rate_limit::RateLimitConfig;
14+use hezarfen_backend::state::AppState;
15+use hezarfen_backend::{build_router, database};
16+use serde_json::{Value, json};
17+use tower::ServiceExt;
18+
19+/// App with the given limits, backed by a fresh in-memory database.
20+async fn app_with(rate_limit: RateLimitConfig) -> Router {
21+ let db = database::init_mem().await.expect("in-memory db");
22+ build_router(AppState {
23+ db,
24+ cookie_secure: false,
25+ rate_limit,
26+ })
27+}
28+
29+/// Send one request posing as client `ip` (via `X-Forwarded-For`). Returns the
30+/// status, the parsed body, and the `Retry-After` header if present.
31+async fn send_as(
32+ app: &Router,
33+ ip: &str,
34+ method: &str,
35+ uri: &str,
36+ body: Option<Value>,
37+) -> (StatusCode, Value, Option<u64>) {
38+ let builder = Request::builder()
39+ .method(method)
40+ .uri(uri)
41+ .header("x-forwarded-for", ip);
42+ let request = match body {
43+ Some(b) => builder
44+ .header("content-type", "application/json")
45+ .body(Body::from(b.to_string()))
46+ .unwrap(),
47+ None => builder.body(Body::empty()).unwrap(),
48+ };
49+
50+ let response = app.clone().oneshot(request).await.unwrap();
51+ let status = response.status();
52+ let retry_after = response
53+ .headers()
54+ .get("retry-after")
55+ .and_then(|v| v.to_str().ok())
56+ .and_then(|v| v.parse().ok());
57+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
58+ .await
59+ .unwrap();
60+ let body = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
61+ (status, body, retry_after)
62+}
63+
64+fn bad_login() -> Option<Value> {
65+ Some(json!({ "username": "ghost", "password": "wrong-pass" }))
66+}
67+
68+fn auth_only(per_minute: u32) -> RateLimitConfig {
69+ RateLimitConfig {
70+ auth_per_minute: per_minute,
71+ api_per_minute: 0,
72+ trust_proxy: true,
73+ }
74+}
75+
76+#[tokio::test]
77+async fn login_attempts_hit_the_auth_limit() {
78+ let app = app_with(auth_only(3)).await;
79+
80+ for i in 1..=3 {
81+ let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await;
82+ assert_eq!(
83+ status,
84+ StatusCode::UNAUTHORIZED,
85+ "attempt {i} still allowed"
86+ );
87+ }
88+
89+ let (status, body, retry_after) =
90+ send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await;
91+ assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
92+ assert_eq!(body["error"], "too many requests");
93+ let secs = retry_after.expect("429 must carry Retry-After");
94+ assert!((1..=60).contains(&secs), "Retry-After {secs} out of range");
95+}
96+
97+#[tokio::test]
98+async fn register_and_login_share_the_auth_bucket() {
99+ let app = app_with(auth_only(2)).await;
100+ let creds = json!({ "username": "ada", "password": "secret1" });
101+
102+ let (status, _, _) = send_as(
103+ &app,
104+ "1.1.1.1",
105+ "POST",
106+ "/auth/register",
107+ Some(creds.clone()),
108+ )
109+ .await;
110+ assert_eq!(status, StatusCode::CREATED);
111+ let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", Some(creds.clone())).await;
112+ assert_eq!(status, StatusCode::OK);
113+
114+ // Two credential requests spent the whole budget; the third is metered
115+ // regardless of whether it would have succeeded.
116+ let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", Some(creds)).await;
117+ assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
118+}
119+
120+#[tokio::test]
121+async fn clients_are_limited_independently() {
122+ let app = app_with(auth_only(1)).await;
123+
124+ let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await;
125+ assert_eq!(status, StatusCode::UNAUTHORIZED);
126+ let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await;
127+ assert_eq!(status, StatusCode::TOO_MANY_REQUESTS, "1.1.1.1 exhausted");
128+
129+ // A different client is untouched by 1.1.1.1's exhausted bucket.
130+ let (status, _, _) = send_as(&app, "2.2.2.2", "POST", "/auth/login", bad_login()).await;
131+ assert_eq!(status, StatusCode::UNAUTHORIZED);
132+}
133+
134+#[tokio::test]
135+async fn auth_limit_spares_me_logout_and_the_rest_of_the_api() {
136+ let app = app_with(auth_only(1)).await;
137+
138+ // Exhaust the credential budget.
139+ let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await;
140+ assert_eq!(status, StatusCode::UNAUTHORIZED);
141+ let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await;
142+ assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
143+
144+ // Same client: session probing, logout, and plain API stay reachable.
145+ let (status, _, _) = send_as(&app, "1.1.1.1", "GET", "/auth/me", None).await;
146+ assert_eq!(status, StatusCode::UNAUTHORIZED, "me is not rate limited");
147+ let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/logout", None).await;
148+ assert_eq!(status, StatusCode::NO_CONTENT, "logout is not rate limited");
149+ let (status, _, _) = send_as(&app, "1.1.1.1", "GET", "/health", None).await;
150+ assert_eq!(status, StatusCode::OK, "health is not rate limited");
151+}
152+
153+#[tokio::test]
154+async fn api_limit_meters_every_route() {
155+ let app = app_with(RateLimitConfig {
156+ auth_per_minute: 0,
157+ api_per_minute: 5,
158+ trust_proxy: true,
159+ })
160+ .await;
161+
162+ for i in 1..=5 {
163+ let (status, _, _) = send_as(&app, "1.1.1.1", "GET", "/health", None).await;
164+ assert_eq!(status, StatusCode::OK, "request {i} still allowed");
165+ }
166+ let (status, body, retry_after) = send_as(&app, "1.1.1.1", "GET", "/health", None).await;
167+ assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
168+ assert_eq!(body["error"], "too many requests");
169+ assert!(retry_after.is_some());
170+}
171+
172+#[tokio::test]
173+async fn zero_disables_a_tier() {
174+ let app = app_with(RateLimitConfig::unlimited()).await;
175+ for _ in 0..20 {
176+ let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await;
177+ assert_eq!(status, StatusCode::UNAUTHORIZED, "never 429 when disabled");
178+ }
179+}
180+
181+#[tokio::test]
182+async fn forwarded_header_is_ignored_unless_proxy_is_trusted() {
183+ let app = app_with(RateLimitConfig {
184+ auth_per_minute: 2,
185+ api_per_minute: 0,
186+ trust_proxy: false,
187+ })
188+ .await;
189+
190+ // Without TRUST_PROXY, spoofed X-Forwarded-For must not mint fresh
191+ // buckets: all three land on the shared fallback address and the third
192+ // request trips the limit despite claiming three different clients.
193+ for (i, ip) in ["1.1.1.1", "2.2.2.2"].iter().enumerate() {
194+ let (status, _, _) = send_as(&app, ip, "POST", "/auth/login", bad_login()).await;
195+ assert_eq!(status, StatusCode::UNAUTHORIZED, "attempt {i} allowed");
196+ }
197+ let (status, _, _) = send_as(&app, "3.3.3.3", "POST", "/auth/login", bad_login()).await;
198+ assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
199+}
200+
201+#[tokio::test]
202+async fn only_the_rightmost_forwarded_hop_counts() {
203+ let app = app_with(auth_only(2)).await;
204+
205+ // Different left (client-forgeable) entries, same rightmost hop: one bucket.
206+ let (status, _, _) =
207+ send_as(&app, "6.6.6.6, 9.9.9.9", "POST", "/auth/login", bad_login()).await;
208+ assert_eq!(status, StatusCode::UNAUTHORIZED);
209+ let (status, _, _) =
210+ send_as(&app, "7.7.7.7, 9.9.9.9", "POST", "/auth/login", bad_login()).await;
211+ assert_eq!(status, StatusCode::UNAUTHORIZED);
212+ let (status, _, _) =
213+ send_as(&app, "8.8.8.8, 9.9.9.9", "POST", "/auth/login", bad_login()).await;
214+ assert_eq!(
215+ status,
216+ StatusCode::TOO_MANY_REQUESTS,
217+ "forged left-hand entries must not evade the limit"
218+ );
219+}
220+
221+#[tokio::test]
222+async fn ipv6_clients_are_keyed_too() {
223+ let app = app_with(auth_only(1)).await;
224+
225+ let (status, _, _) = send_as(&app, "2001:db8::1", "POST", "/auth/login", bad_login()).await;
226+ assert_eq!(status, StatusCode::UNAUTHORIZED);
227+ let (status, _, _) = send_as(&app, "2001:db8::1", "POST", "/auth/login", bad_login()).await;
228+ assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
229+
230+ let (status, _, _) = send_as(&app, "2001:db8::2", "POST", "/auth/login", bad_login()).await;
231+ assert_eq!(
232+ status,
233+ StatusCode::UNAUTHORIZED,
234+ "distinct v6 client is fresh"
235+ );
236+}
237+
238+#[tokio::test]
239+async fn malformed_forwarded_entries_share_the_fallback_bucket() {
240+ let app = app_with(auth_only(2)).await;
241+
242+ // Unparseable entries cannot mint per-garbage buckets — they all collapse
243+ // onto the fallback address, so the third request trips the shared limit.
244+ for garbage in ["not-an-ip", "999.1.2.3"] {
245+ let (status, _, _) = send_as(&app, garbage, "POST", "/auth/login", bad_login()).await;
246+ assert_eq!(status, StatusCode::UNAUTHORIZED, "{garbage:?} allowed once");
247+ }
248+ let (status, _, _) = send_as(&app, "also;garbage", "POST", "/auth/login", bad_login()).await;
249+ assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
250+}
251+
252+#[tokio::test]
253+async fn auth_denials_still_spend_the_api_budget() {
254+ // Both tiers on: the catch-all api tier is the outer layer, so it meters
255+ // raw request volume — including credential attempts the inner auth tier
256+ // goes on to reject.
257+ let app = app_with(RateLimitConfig {
258+ auth_per_minute: 1,
259+ api_per_minute: 3,
260+ trust_proxy: true,
261+ })
262+ .await;
263+
264+ let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await;
265+ assert_eq!(status, StatusCode::UNAUTHORIZED); // api 1/3, auth 1/1
266+ for _ in 0..2 {
267+ let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await;
268+ assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); // auth tier; api 2/3 then 3/3
269+ }
270+
271+ // The api budget is gone even though only one login reached a handler.
272+ let (status, _, _) = send_as(&app, "1.1.1.1", "GET", "/health", None).await;
273+ assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
274+
275+ // Per-IP, not global: another client is unaffected.
276+ let (status, _, _) = send_as(&app, "2.2.2.2", "GET", "/health", None).await;
277+ assert_eq!(status, StatusCode::OK);
278+}
279+
280+#[tokio::test]
281+async fn concurrent_bursts_never_over_admit() {
282+ let app = app_with(RateLimitConfig {
283+ auth_per_minute: 0,
284+ api_per_minute: 5,
285+ trust_proxy: true,
286+ })
287+ .await;
288+
289+ // 20 requests race one 5-token bucket; the mutex must admit exactly 5,
290+ // no matter how the tasks interleave.
291+ let mut set = tokio::task::JoinSet::new();
292+ for _ in 0..20 {
293+ let app = app.clone();
294+ set.spawn(async move { send_as(&app, "1.1.1.1", "GET", "/health", None).await.0 });
295+ }
296+
297+ let (mut ok, mut limited) = (0, 0);
298+ while let Some(status) = set.join_next().await {
299+ match status.unwrap() {
300+ StatusCode::OK => ok += 1,
301+ StatusCode::TOO_MANY_REQUESTS => limited += 1,
302+ other => panic!("unexpected status {other}"),
303+ }
304+ }
305+ assert_eq!((ok, limited), (5, 15));
306+}
307+
308+/// Boot the app on a real TCP port, `ConnectInfo` wired exactly like `main`.
309+async fn spawn_server(rate_limit: RateLimitConfig) -> String {
310+ let db = database::init_mem().await.expect("in-memory db");
311+ let app = build_router(AppState {
312+ db,
313+ cookie_secure: false,
314+ rate_limit,
315+ });
316+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
317+ let addr = listener.local_addr().unwrap();
318+ tokio::spawn(async move {
319+ axum::serve(
320+ listener,
321+ app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
322+ )
323+ .await
324+ .unwrap();
325+ });
326+ format!("http://{addr}")
327+}
328+
329+#[tokio::test]
330+async fn real_connections_are_keyed_by_peer_address() {
331+ let base = spawn_server(RateLimitConfig {
332+ auth_per_minute: 2,
333+ api_per_minute: 0,
334+ trust_proxy: false,
335+ })
336+ .await;
337+ let client = reqwest::Client::new();
338+
339+ // Every request arrives from 127.0.0.1. Spoofed X-Forwarded-For values
340+ // must not matter with TRUST_PROXY off: one peer, one bucket.
341+ for spoof in ["1.1.1.1", "2.2.2.2"] {
342+ let res = client
343+ .post(format!("{base}/auth/login"))
344+ .header("x-forwarded-for", spoof)
345+ .json(&json!({ "username": "ghost", "password": "wrong-pass" }))
346+ .send()
347+ .await
348+ .unwrap();
349+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
350+ }
351+
352+ let res = client
353+ .post(format!("{base}/auth/login"))
354+ .header("x-forwarded-for", "3.3.3.3")
355+ .json(&json!({ "username": "ghost", "password": "wrong-pass" }))
356+ .send()
357+ .await
358+ .unwrap();
359+ assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS);
360+ let retry_after = res
361+ .headers()
362+ .get("retry-after")
363+ .and_then(|v| v.to_str().ok())
364+ .and_then(|v| v.parse::<u64>().ok())
365+ .expect("429 over real HTTP carries Retry-After");
366+ assert!((1..=60).contains(&retry_after));
367+ let body: Value = res.json().await.unwrap();
368+ assert_eq!(body["error"], "too many requests");
369+}
370+
371+#[tokio::test]
372+async fn a_limit_of_fifty_admits_exactly_fifty_requests() {
373+ // Production-scale boundary through the whole HTTP stack: all 50 budgeted
374+ // requests answer 200, the 51st answers 429 — no off-by-one at real sizes.
375+ let app = app_with(RateLimitConfig {
376+ auth_per_minute: 0,
377+ api_per_minute: 50,
378+ trust_proxy: true,
379+ })
380+ .await;
381+
382+ for n in 1..=50 {
383+ let (status, _, _) = send_as(&app, "1.1.1.1", "GET", "/health", None).await;
384+ assert_eq!(status, StatusCode::OK, "request {n}/50 must pass");
385+ }
386+
387+ let (status, body, retry_after) = send_as(&app, "1.1.1.1", "GET", "/health", None).await;
388+ assert_eq!(
389+ status,
390+ StatusCode::TOO_MANY_REQUESTS,
391+ "request 51 must trip"
392+ );
393+ assert_eq!(body["error"], "too many requests");
394+ assert!(retry_after.is_some_and(|s| (1..=60).contains(&s)));
395+
396+ // The 51st being rejected spent nothing extra: a fresh client still has
397+ // its own full budget.
398+ let (status, _, _) = send_as(&app, "2.2.2.2", "GET", "/health", None).await;
399+ assert_eq!(status, StatusCode::OK);
400+}
401+
402+/// Every route, at the ACTUAL shipped limits: request `limit` passes, request
403+/// `limit + 1` answers 429. The route list is pulled from the app's own
404+/// OpenAPI document, so an endpoint added tomorrow is covered automatically;
405+/// `/` and the Swagger mount don't appear there and are appended by hand.
406+///
407+/// Each (method, path) pair poses as its own client IP, giving it a fresh
408+/// bucket. Requests carry no body — extractors reject them long after the
409+/// limiter has counted, which is exactly what makes hammering the credential
410+/// endpoints cheap (no argon2 runs for a body-less request).
411+#[tokio::test]
412+async fn every_route_enforces_the_shipped_limit_plus_one() {
413+ use hezarfen_backend::config::{DEFAULT_API_RATE_LIMIT, DEFAULT_AUTH_RATE_LIMIT};
414+
415+ let app = app_with(RateLimitConfig {
416+ auth_per_minute: DEFAULT_AUTH_RATE_LIMIT,
417+ api_per_minute: DEFAULT_API_RATE_LIMIT,
418+ trust_proxy: true,
419+ })
420+ .await;
421+
422+ // Enumerate routes from the spec (fetched under a reserved IP so the
423+ // fetch itself doesn't spend any route's budget).
424+ let (status, spec, _) = send_as(&app, "254.0.0.1", "GET", "/api-docs/openapi.json", None).await;
425+ assert_eq!(status, StatusCode::OK);
426+ let paths = spec["paths"].as_object().expect("openapi paths object");
427+
428+ let mut routes: Vec<(String, String)> = vec![
429+ ("GET".into(), "/".into()),
430+ ("GET".into(), "/swagger".into()),
431+ ];
432+ for (path, item) in paths {
433+ // "/notes/{id}" -> "/notes/id": a well-formed URL whose dummy segment
434+ // fails lookup in the handler, long after the limiter counted it.
435+ let concrete = path.replace(['{', '}'], "");
436+ for method in item.as_object().expect("path item").keys() {
437+ routes.push((method.to_uppercase(), concrete.clone()));
438+ }
439+ }
440+ assert!(
441+ routes.len() >= 25,
442+ "suspiciously few routes ({}) — OpenAPI enumeration broke?",
443+ routes.len()
444+ );
445+
446+ for (i, (method, path)) in routes.iter().enumerate() {
447+ // One unique client per route (203.0.x.x is TEST-NET-3).
448+ let ip = format!("203.0.{}.{}", i / 200, (i % 200) + 1);
449+ // The strict tier owns the two credential endpoints; everything else
450+ // runs into the catch-all api tier.
451+ let limit = if path == "/auth/login" || path == "/auth/register" {
452+ DEFAULT_AUTH_RATE_LIMIT
453+ } else {
454+ DEFAULT_API_RATE_LIMIT
455+ };
456+
457+ for n in 1..=limit {
458+ let (status, _, _) = send_as(&app, &ip, method, path, None).await;
459+ assert_ne!(
460+ status,
461+ StatusCode::TOO_MANY_REQUESTS,
462+ "{method} {path}: request {n}/{limit} must not be limited"
463+ );
464+ }
465+ let (status, _, retry_after) = send_as(&app, &ip, method, path, None).await;
466+ assert_eq!(
467+ status,
468+ StatusCode::TOO_MANY_REQUESTS,
469+ "{method} {path}: request {}/{limit} must be limited",
470+ limit + 1
471+ );
472+ assert!(
473+ retry_after.is_some_and(|s| (1..=60).contains(&s)),
474+ "{method} {path}: 429 must carry a sane Retry-After"
475+ );
476+ }
477+}