diff --git a/tests/common/mod.rs b/tests/common/mod.rs new file mode 100644 index 0000000..5db46ef --- /dev/null +++ b/tests/common/mod.rs @@ -0,0 +1,121 @@ +//! Shared helpers for the router-level test binaries (`integration`, `persistence`). +//! Drives an `axum::Router` in-process via `tower::ServiceExt::oneshot`. +#![allow(dead_code)] + +use axum::Router; +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use hezarfen_backend::database::Database; +use hezarfen_backend::rate_limit::RateLimitConfig; +use hezarfen_backend::state::AppState; +use hezarfen_backend::{build_router, database}; +use serde_json::{Value, json}; +use tower::ServiceExt; + +pub struct Res { + pub status: StatusCode, + pub body: Value, + /// The `session=` pair, if the response set one. + pub cookie: Option, +} + +/// A router plus a handle to its (shared) in-memory database. Tests that need to +/// grant roles use the handle to seed them directly — the app's only role +/// bootstrap path is out-of-band, exactly like production's manual SQL. +pub async fn app_and_db() -> (Router, Database) { + let db = database::init_mem().await.expect("in-memory db"); + let app = build_router(AppState { + db: db.clone(), + cookie_secure: false, + // Off, so suites hammering the API never trip a limit; the dedicated + // `rate_limit` test binary opts into tight configs on purpose. + rate_limit: RateLimitConfig::unlimited(), + }); + (app, db) +} + +/// A router backed by a fresh in-memory database. +pub async fn mem_app() -> Router { + app_and_db().await.0 +} + +/// Force `username`'s role, mirroring the manual `UPDATE user SET role=...` +/// bootstrap. Roles are read fresh per request, so this takes effect at once. +pub async fn set_role(db: &Database, username: &str, role: &str) { + db.query("UPDATE user SET role = $role WHERE username = $u") + .bind(("role", role.to_string())) + .bind(("u", username.to_string())) + .await + .expect("set_role query") + .check() + .expect("set_role check"); +} + +/// Register (password `secret1`), promote to `role`, then log in. Returns the +/// session `Cookie` value. +pub async fn login_as(app: &Router, db: &Database, username: &str, role: &str) -> String { + let creds = json!({ "username": username, "password": "secret1" }); + let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await; + assert_eq!(reg.status, StatusCode::CREATED, "register {username}"); + set_role(db, username, role).await; + let res = send(app, "POST", "/auth/login", None, Some(creds)).await; + assert_eq!(res.status, StatusCode::OK, "login {username}"); + res.cookie.expect("session cookie set on login") +} + +/// Send one request through `app`. `cookie` is a raw `Cookie` header value. +pub async fn send( + app: &Router, + method: &str, + uri: &str, + cookie: Option<&str>, + body: Option, +) -> Res { + let mut builder = Request::builder().method(method).uri(uri); + if let Some(c) = cookie { + builder = builder.header("cookie", c); + } + let request = match body { + Some(b) => builder + .header("content-type", "application/json") + .body(Body::from(b.to_string())) + .unwrap(), + None => builder.body(Body::empty()).unwrap(), + }; + + let response = app.clone().oneshot(request).await.unwrap(); + let status = response.status(); + let cookie = response + .headers() + .get("set-cookie") + .and_then(|v| v.to_str().ok()) + .and_then(|s| s.split(';').next()) + .map(|s| s.to_string()); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let body = if bytes.is_empty() { + Value::Null + } else { + serde_json::from_slice(&bytes).unwrap_or(Value::Null) + }; + Res { + status, + body, + cookie, + } +} + +/// Register (password `secret1`) then log in; returns the session `Cookie` value. +pub async fn login(app: &Router, username: &str) -> String { + let creds = json!({ "username": username, "password": "secret1" }); + let reg = send(app, "POST", "/auth/register", None, Some(creds.clone())).await; + assert_eq!(reg.status, StatusCode::CREATED, "register {username}"); + let res = send(app, "POST", "/auth/login", None, Some(creds)).await; + assert_eq!(res.status, StatusCode::OK, "login {username}"); + res.cookie.expect("session cookie set on login") +} + +pub fn id_of(v: &Value) -> String { + v["id"].as_str().expect("id field").to_string() +} diff --git a/tests/e2e.rs b/tests/e2e.rs new file mode 100644 index 0000000..a4ee3e4 --- /dev/null +++ b/tests/e2e.rs @@ -0,0 +1,276 @@ +//! End-to-end tests: boot the real server on an ephemeral TCP port and drive it +//! with `reqwest` over HTTP, using its cookie jar exactly like a browser client. + +use hezarfen_backend::database::Database; +use hezarfen_backend::rate_limit::RateLimitConfig; +use hezarfen_backend::state::AppState; +use hezarfen_backend::{build_router, database}; +use reqwest::{Client, StatusCode}; +use serde_json::{Value, json}; + +/// Start the server on a random port. Returns its base URL (e.g. +/// `http://127.0.0.1:54321`) plus a handle to its database, so a test can grant +/// roles the same out-of-band way production does. +async fn spawn_server() -> (String, Database) { + let db = database::init_mem().await.expect("in-memory db"); + let app = build_router(AppState { + db: db.clone(), + cookie_secure: false, + // Every request here comes from 127.0.0.1, so per-IP limits would + // meter the whole suite as one client. Off; `rate_limit.rs` covers it. + rate_limit: RateLimitConfig::unlimited(), + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + // Mirror `main`: expose peer addresses so the limiter key path in + // production is the same one exercised end-to-end. + axum::serve( + listener, + app.into_make_service_with_connect_info::(), + ) + .await + .unwrap(); + }); + (format!("http://{addr}"), db) +} + +/// Grant `user` a role directly (the manual bootstrap path). +async fn promote(db: &Database, user: &str, role: &str) { + db.query("UPDATE user SET role = $r WHERE username = $u") + .bind(("r", role.to_string())) + .bind(("u", user.to_string())) + .await + .unwrap() + .check() + .unwrap(); +} + +/// A reqwest client with its own cookie jar (one per simulated user). +fn client() -> Client { + Client::builder().cookie_store(true).build().unwrap() +} + +async fn register(client: &Client, base: &str, user: &str) -> reqwest::Response { + client + .post(format!("{base}/auth/register")) + .json(&json!({ "username": user, "password": "secret1" })) + .send() + .await + .unwrap() +} + +async fn login(client: &Client, base: &str, user: &str) { + let res = client + .post(format!("{base}/auth/login")) + .json(&json!({ "username": user, "password": "secret1" })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::OK, "login {user}"); +} + +#[tokio::test] +async fn full_user_journey() { + let (base, db) = spawn_server().await; + let ali = client(); + let veli = client(); + + // --- signup + auth --------------------------------------------------- + assert_eq!( + register(&ali, &base, "ali").await.status(), + StatusCode::CREATED + ); + assert_eq!( + register(&veli, &base, "veli").await.status(), + StatusCode::CREATED + ); + // ali runs the class: give her the teacher role. veli stays a student. + promote(&db, "ali", "teacher").await; + + // me before login -> 401 + let res = ali.get(format!("{base}/auth/me")).send().await.unwrap(); + assert_eq!(res.status(), StatusCode::UNAUTHORIZED); + + login(&ali, &base, "ali").await; + login(&veli, &base, "veli").await; + + let me: Value = ali + .get(format!("{base}/auth/me")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(me["username"], "ali"); + + let veli_id = veli + .get(format!("{base}/auth/me")) + .send() + .await + .unwrap() + .json::() + .await + .unwrap()["id"] + .as_str() + .unwrap() + .to_string(); + + // --- notes ----------------------------------------------------------- + let note: Value = ali + .post(format!("{base}/notes")) + .json(&json!({ "title": "first", "content": "hello" })) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let note_id = note["id"].as_str().unwrap().to_string(); + assert_eq!(note["title"], "first"); + + // veli cannot read ali's note + let res = veli + .get(format!("{base}/notes/{note_id}")) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::NOT_FOUND); + + // --- events + attendance -------------------------------------------- + let event: Value = ali + .post(format!("{base}/events")) + .json(&json!({ "title": "standup" })) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let event_id = event["id"].as_str().unwrap().to_string(); + + // ali marks veli present + let res = ali + .post(format!("{base}/events/{event_id}/attendance")) + .json(&json!({ "status": "present", "user_id": veli_id })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::OK); + + let roster: Value = veli + .get(format!("{base}/events/{event_id}/attendance")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(roster.as_array().unwrap().len(), 1); + assert_eq!(roster[0]["user"], veli_id); + assert_eq!(roster[0]["status"], "present"); + + // veli is only a student, so she cannot create events. + let res = veli + .post(format!("{base}/events")) + .json(&json!({ "title": "nope" })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::FORBIDDEN); + + // --- logout invalidates the session --------------------------------- + let res = ali + .post(format!("{base}/auth/logout")) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::NO_CONTENT); + + let res = ali.get(format!("{base}/auth/me")).send().await.unwrap(); + assert_eq!(res.status(), StatusCode::UNAUTHORIZED); +} + +#[tokio::test] +async fn attendance_rollup_across_users() { + let (base, db) = spawn_server().await; + let host = client(); + let a = client(); + let b = client(); + + for (c, name) in [(&host, "host"), (&a, "amy"), (&b, "ben")] { + assert_eq!(register(c, &base, name).await.status(), StatusCode::CREATED); + login(c, &base, name).await; + } + // The host runs the event and records everyone, which is a teacher+ action. + promote(&db, "host", "teacher").await; + + let id_of = |v: &Value| v["id"].as_str().unwrap().to_string(); + let amy_id = id_of( + &a.get(format!("{base}/auth/me")) + .send() + .await + .unwrap() + .json::() + .await + .unwrap(), + ); + let ben_id = id_of( + &b.get(format!("{base}/auth/me")) + .send() + .await + .unwrap() + .json::() + .await + .unwrap(), + ); + + // Host creates an event and records everyone. + let event_id = id_of( + &host + .post(format!("{base}/events")) + .json(&json!({ "title": "all-hands" })) + .send() + .await + .unwrap() + .json::() + .await + .unwrap(), + ); + + for (uid, status) in [(&amy_id, "present"), (&ben_id, "late")] { + let res = host + .post(format!("{base}/events/{event_id}/attendance")) + .json(&json!({ "status": status, "user_id": uid })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::OK); + } + // Host marks self too. + host.post(format!("{base}/events/{event_id}/attendance")) + .json(&json!({ "status": "present" })) + .send() + .await + .unwrap(); + + // Any attendee can read the full roster (3 people). + let roster: Value = b + .get(format!("{base}/events/{event_id}/attendance")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(roster.as_array().unwrap().len(), 3); + + // Unauthenticated client is refused. + let res = client() + .get(format!("{base}/events/{event_id}/attendance")) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::UNAUTHORIZED); +} diff --git a/tests/integration.rs b/tests/integration.rs new file mode 100644 index 0000000..a2eeadb --- /dev/null +++ b/tests/integration.rs @@ -0,0 +1,1895 @@ +//! Integration tests: drive the assembled axum router directly (no network) +//! against a fresh in-memory SurrealDB, via `tower::ServiceExt::oneshot`. + +mod common; + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use common::{app_and_db, id_of, login, login_as, mem_app, send}; +use hezarfen_backend::domain::session::Session; +use hezarfen_backend::state::AppState; +use hezarfen_backend::{build_router, database}; +use serde_json::json; +use tower::ServiceExt; + +// --- health + auth ------------------------------------------------------- + +#[tokio::test] +async fn health_reports_ok() { + let app = mem_app().await; + let res = send(&app, "GET", "/health", None, None).await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["status"], "ok"); +} + +#[tokio::test] +async fn register_validates_input() { + let app = mem_app().await; + + // Password too short -> 400. + let short = json!({ "username": "bob", "password": "123" }); + let res = send(&app, "POST", "/auth/register", None, Some(short)).await; + assert_eq!(res.status, StatusCode::BAD_REQUEST); + + // Blank username -> 400. + let blank = json!({ "username": " ", "password": "secret1" }); + let res = send(&app, "POST", "/auth/register", None, Some(blank)).await; + assert_eq!(res.status, StatusCode::BAD_REQUEST); + + // Valid -> 201, no password echoed back, defaults to the student role. + let ok = json!({ "username": "bob", "password": "secret1" }); + let res = send(&app, "POST", "/auth/register", None, Some(ok.clone())).await; + assert_eq!(res.status, StatusCode::CREATED); + assert_eq!(res.body["username"], "bob"); + assert_eq!(res.body["role"], "student"); + assert!(res.body.get("password_hash").is_none()); + + // Duplicate username -> 409. + let res = send(&app, "POST", "/auth/register", None, Some(ok)).await; + assert_eq!(res.status, StatusCode::CONFLICT); +} + +#[tokio::test] +async fn login_rejects_bad_credentials() { + let app = mem_app().await; + send( + &app, + "POST", + "/auth/register", + None, + Some(json!({ "username": "kate", "password": "secret1" })), + ) + .await; + + // Wrong password. + let res = send( + &app, + "POST", + "/auth/login", + None, + Some(json!({ "username": "kate", "password": "wrong" })), + ) + .await; + assert_eq!(res.status, StatusCode::UNAUTHORIZED); + + // Unknown user. + let res = send( + &app, + "POST", + "/auth/login", + None, + Some(json!({ "username": "ghost", "password": "secret1" })), + ) + .await; + assert_eq!(res.status, StatusCode::UNAUTHORIZED); +} + +#[tokio::test] +async fn protected_routes_require_session() { + let app = mem_app().await; + for (method, uri) in [ + ("GET", "/auth/me"), + ("GET", "/notes"), + ("POST", "/notes"), + ("GET", "/events"), + ("POST", "/events"), + ("GET", "/exams"), + ("POST", "/exams"), + ] { + let res = send(&app, method, uri, None, None).await; + assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{method} {uri}"); + } +} + +#[tokio::test] +async fn garbage_cookie_is_unauthorized() { + let app = mem_app().await; + let res = send(&app, "GET", "/auth/me", Some("session=deadbeef"), None).await; + assert_eq!(res.status, StatusCode::UNAUTHORIZED); +} + +#[tokio::test] +async fn me_returns_current_user_without_secrets() { + let app = mem_app().await; + let ali = login(&app, "ali").await; + let res = send(&app, "GET", "/auth/me", Some(&ali), None).await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["username"], "ali"); + assert_eq!(res.body["role"], "student"); + assert!(res.body.get("password_hash").is_none()); +} + +#[tokio::test] +async fn logout_invalidates_the_session_server_side() { + let app = mem_app().await; + let ali = login(&app, "ali").await; + + assert_eq!( + send(&app, "GET", "/auth/me", Some(&ali), None).await.status, + StatusCode::OK + ); + + let res = send(&app, "POST", "/auth/logout", Some(&ali), None).await; + assert_eq!(res.status, StatusCode::NO_CONTENT); + + // Re-using the same token now fails: the session row is gone. + let res = send(&app, "GET", "/auth/me", Some(&ali), None).await; + assert_eq!(res.status, StatusCode::UNAUTHORIZED); +} + +// --- notes --------------------------------------------------------------- + +#[tokio::test] +async fn notes_crud_is_scoped_to_owner() { + let app = mem_app().await; + let ali = login(&app, "ali").await; + let veli = login(&app, "veli").await; + + let res = send( + &app, + "POST", + "/notes", + Some(&ali), + Some(json!({ "title": "first", "content": "hello" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + let note_id = id_of(&res.body); + + // Partial update keeps the untouched field. + let res = send( + &app, + "PATCH", + &format!("/notes/{note_id}"), + Some(&ali), + Some(json!({ "content": "edited" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["content"], "edited"); + assert_eq!(res.body["title"], "first"); + + // Owner sees exactly one; other user sees none and gets 404 on direct access. + assert_eq!( + send(&app, "GET", "/notes", Some(&ali), None) + .await + .body + .as_array() + .unwrap() + .len(), + 1 + ); + assert_eq!( + send(&app, "GET", &format!("/notes/{note_id}"), Some(&veli), None) + .await + .status, + StatusCode::NOT_FOUND + ); + assert_eq!( + send(&app, "GET", "/notes", Some(&veli), None) + .await + .body + .as_array() + .unwrap() + .len(), + 0 + ); + + // Other user cannot update or delete it either. + assert_eq!( + send( + &app, + "PATCH", + &format!("/notes/{note_id}"), + Some(&veli), + Some(json!({"title":"x"})) + ) + .await + .status, + StatusCode::NOT_FOUND + ); + assert_eq!( + send( + &app, + "DELETE", + &format!("/notes/{note_id}"), + Some(&veli), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); + + // Delete, then it's gone. + assert_eq!( + send( + &app, + "DELETE", + &format!("/notes/{note_id}"), + Some(&ali), + None + ) + .await + .status, + StatusCode::NO_CONTENT + ); + assert_eq!( + send(&app, "GET", &format!("/notes/{note_id}"), Some(&ali), None) + .await + .status, + StatusCode::NOT_FOUND + ); +} + +#[tokio::test] +async fn note_content_defaults_to_empty() { + let app = mem_app().await; + let ali = login(&app, "ali").await; + let res = send( + &app, + "POST", + "/notes", + Some(&ali), + Some(json!({ "title": "solo" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + assert_eq!(res.body["content"], ""); +} + +#[tokio::test] +async fn note_validation_and_missing_ids() { + let app = mem_app().await; + let ali = login(&app, "ali").await; + + // Blank title on create -> 400. + assert_eq!( + send( + &app, + "POST", + "/notes", + Some(&ali), + Some(json!({ "title": " " })) + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + + // Operations on a non-existent id -> 404. + for method in ["GET", "PATCH", "DELETE"] { + let body = (method == "PATCH").then(|| json!({ "title": "x" })); + let res = send(&app, method, "/notes/does-not-exist", Some(&ali), body).await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{method}"); + } + + // Blank title on update -> 400. + let created = send( + &app, + "POST", + "/notes", + Some(&ali), + Some(json!({ "title": "keep" })), + ) + .await; + let id = id_of(&created.body); + assert_eq!( + send( + &app, + "PATCH", + &format!("/notes/{id}"), + Some(&ali), + Some(json!({ "title": "" })) + ) + .await + .status, + StatusCode::BAD_REQUEST + ); +} + +// --- events + attendance ------------------------------------------------- + +#[tokio::test] +async fn events_are_shared_but_creator_guarded() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + let veli = login_as(&app, &db, "veli", "teacher").await; + + let ev = send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({ "title": "standup", "description": "daily" })), + ) + .await; + assert_eq!(ev.status, StatusCode::CREATED); + let event_id = id_of(&ev.body); + + // Any authenticated user can read the event and its roster. + assert_eq!( + send( + &app, + "GET", + &format!("/events/{event_id}"), + Some(&veli), + None + ) + .await + .status, + StatusCode::OK + ); + assert_eq!( + send(&app, "GET", "/events", Some(&veli), None) + .await + .body + .as_array() + .unwrap() + .len(), + 1 + ); + + // Non-creator cannot edit or delete. + assert_eq!( + send( + &app, + "PATCH", + &format!("/events/{event_id}"), + Some(&veli), + Some(json!({"title":"hijack"})) + ) + .await + .status, + StatusCode::FORBIDDEN + ); + assert_eq!( + send( + &app, + "DELETE", + &format!("/events/{event_id}"), + Some(&veli), + None + ) + .await + .status, + StatusCode::FORBIDDEN + ); + + // Creator can edit (partial). + let res = send( + &app, + "PATCH", + &format!("/events/{event_id}"), + Some(&ali), + Some(json!({ "description": "moved" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["description"], "moved"); + assert_eq!(res.body["title"], "standup"); + + // Blank title on update -> 400. Missing event -> 404. + assert_eq!( + send( + &app, + "PATCH", + &format!("/events/{event_id}"), + Some(&ali), + Some(json!({"title":" "})) + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + assert_eq!( + send(&app, "GET", "/events/nope", Some(&ali), None) + .await + .status, + StatusCode::NOT_FOUND + ); +} + +#[tokio::test] +async fn attendance_marking_and_upsert() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + let veli = login(&app, "veli").await; + let veli_id = id_of(&send(&app, "GET", "/auth/me", Some(&veli), None).await.body); + + let event_id = id_of( + &send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({ "title": "standup" })), + ) + .await + .body, + ); + + // Default target is the caller. + let res = send( + &app, + "POST", + &format!("/events/{event_id}/attendance"), + Some(&ali), + Some(json!({ "status": "present" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["status"], "present"); + + // Mark veli, then re-mark: upsert keeps a single row (same id). + let first = send( + &app, + "POST", + &format!("/events/{event_id}/attendance"), + Some(&ali), + Some(json!({ "status": "late", "user_id": veli_id })), + ) + .await; + let second = send( + &app, + "POST", + &format!("/events/{event_id}/attendance"), + Some(&ali), + Some(json!({ "status": "absent", "user_id": veli_id })), + ) + .await; + assert_eq!( + id_of(&first.body), + id_of(&second.body), + "upsert same record" + ); + assert_eq!(second.body["status"], "absent"); + + // Two rows total. + assert_eq!( + send( + &app, + "GET", + &format!("/events/{event_id}/attendance"), + Some(&ali), + None + ) + .await + .body + .as_array() + .unwrap() + .len(), + 2 + ); + + // Remove veli -> one row; removing again -> 404. + assert_eq!( + send( + &app, + "DELETE", + &format!("/events/{event_id}/attendance/{veli_id}"), + Some(&ali), + None + ) + .await + .status, + StatusCode::NO_CONTENT + ); + assert_eq!( + send( + &app, + "GET", + &format!("/events/{event_id}/attendance"), + Some(&ali), + None + ) + .await + .body + .as_array() + .unwrap() + .len(), + 1 + ); + assert_eq!( + send( + &app, + "DELETE", + &format!("/events/{event_id}/attendance/{veli_id}"), + Some(&ali), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); +} + +#[tokio::test] +async fn attendance_input_validation() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + let event_id = id_of( + &send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({ "title": "e" })), + ) + .await + .body, + ); + + // Invalid status -> 400. + assert_eq!( + send( + &app, + "POST", + &format!("/events/{event_id}/attendance"), + Some(&ali), + Some(json!({"status":"maybe"})) + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + + // Unknown target user -> 400. + assert_eq!( + send( + &app, + "POST", + &format!("/events/{event_id}/attendance"), + Some(&ali), + Some(json!({"status":"present","user_id":"ghost"})) + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + + // Attendance on a missing event -> 404. + assert_eq!( + send( + &app, + "POST", + "/events/nope/attendance", + Some(&ali), + Some(json!({"status":"present"})) + ) + .await + .status, + StatusCode::NOT_FOUND + ); +} + +#[tokio::test] +async fn deleting_event_cascades_attendance() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + let event_id = id_of( + &send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({ "title": "e" })), + ) + .await + .body, + ); + send( + &app, + "POST", + &format!("/events/{event_id}/attendance"), + Some(&ali), + Some(json!({"status":"present"})), + ) + .await; + + assert_eq!( + send( + &app, + "DELETE", + &format!("/events/{event_id}"), + Some(&ali), + None + ) + .await + .status, + StatusCode::NO_CONTENT + ); + // Event gone — and its roster endpoint with it (404, not an empty list). + assert_eq!( + send( + &app, + "GET", + &format!("/events/{event_id}"), + Some(&ali), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); + assert_eq!( + send( + &app, + "GET", + &format!("/events/{event_id}/attendance"), + Some(&ali), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); +} + +#[tokio::test] +async fn event_timestamps_echo_and_validate() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + + // Create with unix-millis times. + let res = send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({ "title": "mtg", "starts_at": 1000, "ends_at": 2000 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + assert_eq!(res.body["starts_at"], 1000); + assert_eq!(res.body["ends_at"], 2000); + let event_id = id_of(&res.body); + + // Omitted times serialize as null. + let untimed = send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({ "title": "notime" })), + ) + .await; + assert!(untimed.body["starts_at"].is_null()); + assert!(untimed.body["ends_at"].is_null()); + + // ends_at before starts_at -> 400. + let bad = send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({ "title": "bad", "starts_at": 5000, "ends_at": 1000 })), + ) + .await; + assert_eq!(bad.status, StatusCode::BAD_REQUEST); + + // Updating only ends_at keeps starts_at. + let updated = send( + &app, + "PATCH", + &format!("/events/{event_id}"), + Some(&ali), + Some(json!({ "ends_at": 3000 })), + ) + .await; + assert_eq!(updated.status, StatusCode::OK); + assert_eq!(updated.body["starts_at"], 1000); + assert_eq!(updated.body["ends_at"], 3000); +} + +// --- exams + results ----------------------------------------------------- + +#[tokio::test] +async fn exams_are_shared_but_creator_guarded() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + let veli = login_as(&app, &db, "veli", "teacher").await; + + let ex = send( + &app, + "POST", + "/exams", + Some(&ali), + Some(json!({ "title": "ch3", "description": "algebra", "kind": "quiz" })), + ) + .await; + assert_eq!(ex.status, StatusCode::CREATED); + assert_eq!(ex.body["kind"], "quiz"); + let exam_id = id_of(&ex.body); + + // Any authenticated user can read the exam and the list. + assert_eq!( + send(&app, "GET", &format!("/exams/{exam_id}"), Some(&veli), None) + .await + .status, + StatusCode::OK + ); + assert_eq!( + send(&app, "GET", "/exams", Some(&veli), None) + .await + .body + .as_array() + .unwrap() + .len(), + 1 + ); + + // Non-creator teacher cannot edit or delete. + assert_eq!( + send( + &app, + "PATCH", + &format!("/exams/{exam_id}"), + Some(&veli), + Some(json!({"title":"hijack"})) + ) + .await + .status, + StatusCode::FORBIDDEN + ); + assert_eq!( + send( + &app, + "DELETE", + &format!("/exams/{exam_id}"), + Some(&veli), + None + ) + .await + .status, + StatusCode::FORBIDDEN + ); + + // Creator edits (partial) — kind flips homework, title kept. + let res = send( + &app, + "PATCH", + &format!("/exams/{exam_id}"), + Some(&ali), + Some(json!({ "kind": "homework" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["kind"], "homework"); + assert_eq!(res.body["title"], "ch3"); +} + +#[tokio::test] +async fn exam_input_validation() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + + // Missing/blank title -> 400. + assert_eq!( + send( + &app, + "POST", + "/exams", + Some(&ali), + Some(json!({"title":" ","kind":"quiz"})) + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + // Unknown kind -> 400. + assert_eq!( + send( + &app, + "POST", + "/exams", + Some(&ali), + Some(json!({"title":"t","kind":"final"})) + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + // Missing exam -> 404. + assert_eq!( + send(&app, "GET", "/exams/nope", Some(&ali), None) + .await + .status, + StatusCode::NOT_FOUND + ); +} + +#[tokio::test] +async fn grading_upsert_and_own_result() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let alice = login(&app, "alice").await; // student + let bob = login(&app, "bob").await; // student + let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body); + + let exam_id = id_of( + &send( + &app, + "POST", + "/exams", + Some(&teacher), + Some(json!({"title":"mt","kind":"quiz"})), + ) + .await + .body, + ); + + // Before grading, the student's own result is 404. + assert_eq!( + send( + &app, + "GET", + &format!("/exams/{exam_id}/result"), + Some(&alice), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); + + // Teacher grades alice, then re-grades: upsert keeps one row (same id). + let first = send( + &app, + "POST", + &format!("/exams/{exam_id}/results"), + Some(&teacher), + Some(json!({ "mark": 70, "user_id": alice_id })), + ) + .await; + assert_eq!(first.status, StatusCode::OK); + let second = send( + &app, + "POST", + &format!("/exams/{exam_id}/results"), + Some(&teacher), + Some(json!({ "mark": 88, "user_id": alice_id })), + ) + .await; + assert_eq!( + id_of(&first.body), + id_of(&second.body), + "upsert same record" + ); + assert_eq!(second.body["mark"], 88); + + // Alice reads her own result; bob (ungraded) still 404s and can't see alice's. + let mine = send( + &app, + "GET", + &format!("/exams/{exam_id}/result"), + Some(&alice), + None, + ) + .await; + assert_eq!(mine.status, StatusCode::OK); + assert_eq!(mine.body["mark"], 88); + assert_eq!( + send( + &app, + "GET", + &format!("/exams/{exam_id}/result"), + Some(&bob), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); + + // Teacher sees the full list (one row). + assert_eq!( + send( + &app, + "GET", + &format!("/exams/{exam_id}/results"), + Some(&teacher), + None + ) + .await + .body + .as_array() + .unwrap() + .len(), + 1 + ); + + // Remove alice's result -> her own read 404s again; removing again -> 404. + assert_eq!( + send( + &app, + "DELETE", + &format!("/exams/{exam_id}/results/{alice_id}"), + Some(&teacher), + None + ) + .await + .status, + StatusCode::NO_CONTENT + ); + assert_eq!( + send( + &app, + "GET", + &format!("/exams/{exam_id}/result"), + Some(&alice), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); + assert_eq!( + send( + &app, + "DELETE", + &format!("/exams/{exam_id}/results/{alice_id}"), + Some(&teacher), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); +} + +#[tokio::test] +async fn grading_rbac_and_validation() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let alice = login(&app, "alice").await; // student + let bob = login(&app, "bob").await; // student + let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body); + + let exam_id = id_of( + &send( + &app, + "POST", + "/exams", + Some(&teacher), + Some(json!({"title":"e","kind":"homework"})), + ) + .await + .body, + ); + + // Students cannot create exams, grade anyone, list all results, or delete a result. + assert_eq!( + send( + &app, + "POST", + "/exams", + Some(&alice), + Some(json!({"title":"x","kind":"quiz"})) + ) + .await + .status, + StatusCode::FORBIDDEN + ); + assert_eq!( + send( + &app, + "POST", + &format!("/exams/{exam_id}/results"), + Some(&alice), + Some(json!({"mark":100,"user_id":alice_id})) + ) + .await + .status, + StatusCode::FORBIDDEN + ); + assert_eq!( + send( + &app, + "GET", + &format!("/exams/{exam_id}/results"), + Some(&alice), + None + ) + .await + .status, + StatusCode::FORBIDDEN + ); + assert_eq!( + send( + &app, + "DELETE", + &format!("/exams/{exam_id}/results/{alice_id}"), + Some(&bob), + None + ) + .await + .status, + StatusCode::FORBIDDEN + ); + + // Mark out of range -> 400. + assert_eq!( + send( + &app, + "POST", + &format!("/exams/{exam_id}/results"), + Some(&teacher), + Some(json!({"mark":101,"user_id":alice_id})) + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + // Unknown target user -> 400. + assert_eq!( + send( + &app, + "POST", + &format!("/exams/{exam_id}/results"), + Some(&teacher), + Some(json!({"mark":50,"user_id":"ghost"})) + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + // Grading on a missing exam -> 404. + assert_eq!( + send( + &app, + "POST", + "/exams/nope/results", + Some(&teacher), + Some(json!({"mark":50,"user_id":alice_id})) + ) + .await + .status, + StatusCode::NOT_FOUND + ); +} + +#[tokio::test] +async fn deleting_exam_cascades_results() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let alice = login(&app, "alice").await; + let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body); + + let exam_id = id_of( + &send( + &app, + "POST", + "/exams", + Some(&teacher), + Some(json!({"title":"e","kind":"quiz"})), + ) + .await + .body, + ); + send( + &app, + "POST", + &format!("/exams/{exam_id}/results"), + Some(&teacher), + Some(json!({"mark":60,"user_id":alice_id})), + ) + .await; + + assert_eq!( + send( + &app, + "DELETE", + &format!("/exams/{exam_id}"), + Some(&teacher), + None + ) + .await + .status, + StatusCode::NO_CONTENT + ); + // Exam gone; the student's result is gone with it. + assert_eq!( + send( + &app, + "GET", + &format!("/exams/{exam_id}"), + Some(&teacher), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); + assert_eq!( + send( + &app, + "GET", + &format!("/exams/{exam_id}/result"), + Some(&alice), + None + ) + .await + .status, + StatusCode::NOT_FOUND + ); +} + +// --- roles / RBAC -------------------------------------------------------- + +#[tokio::test] +async fn students_cannot_create_events() { + let app = mem_app().await; + let ali = login(&app, "ali").await; // default role: student + let res = send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({ "title": "class" })), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN); +} + +#[tokio::test] +async fn students_mark_only_themselves() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let alice = login(&app, "alice").await; // student + let bob = login(&app, "bob").await; // student + let bob_id = id_of(&send(&app, "GET", "/auth/me", Some(&bob), None).await.body); + + let ev = id_of( + &send( + &app, + "POST", + "/events", + Some(&teacher), + Some(json!({ "title": "class" })), + ) + .await + .body, + ); + + // A student may mark their own attendance. + assert_eq!( + send( + &app, + "POST", + &format!("/events/{ev}/attendance"), + Some(&alice), + Some(json!({"status":"present"})) + ) + .await + .status, + StatusCode::OK + ); + // But not someone else's. + assert_eq!( + send( + &app, + "POST", + &format!("/events/{ev}/attendance"), + Some(&alice), + Some(json!({"status":"present","user_id":bob_id})) + ) + .await + .status, + StatusCode::FORBIDDEN + ); + // And cannot remove attendance rows. + assert_eq!( + send( + &app, + "DELETE", + &format!("/events/{ev}/attendance/{bob_id}"), + Some(&alice), + None + ) + .await + .status, + StatusCode::FORBIDDEN + ); +} + +#[tokio::test] +async fn event_management_follows_hierarchy() { + let (app, db) = app_and_db().await; + let owner = login_as(&app, &db, "owner", "teacher").await; + let other = login_as(&app, &db, "other", "teacher").await; + let boss = login_as(&app, &db, "boss", "manager").await; + + let ev = id_of( + &send( + &app, + "POST", + "/events", + Some(&owner), + Some(json!({ "title": "orig" })), + ) + .await + .body, + ); + + // A different teacher (not the creator) cannot edit it. + assert_eq!( + send( + &app, + "PATCH", + &format!("/events/{ev}"), + Some(&other), + Some(json!({"title":"hijack"})) + ) + .await + .status, + StatusCode::FORBIDDEN + ); + // A manager can edit anyone's event. + let res = send( + &app, + "PATCH", + &format!("/events/{ev}"), + Some(&boss), + Some(json!({"title":"by mgr"})), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["title"], "by mgr"); + // The creator can still delete their own. + assert_eq!( + send(&app, "DELETE", &format!("/events/{ev}"), Some(&owner), None) + .await + .status, + StatusCode::NO_CONTENT + ); +} + +#[tokio::test] +async fn admin_manages_roles_with_guards() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "admin", "admin").await; + let alice = login(&app, "alice").await; // student + let alice_id = id_of(&send(&app, "GET", "/auth/me", Some(&alice), None).await.body); + + // Non-admins cannot reach the role endpoints. + assert_eq!( + send(&app, "GET", "/users", Some(&alice), None).await.status, + StatusCode::FORBIDDEN + ); + assert_eq!( + send( + &app, + "PATCH", + &format!("/users/{alice_id}/role"), + Some(&alice), + Some(json!({"role":"teacher"})) + ) + .await + .status, + StatusCode::FORBIDDEN + ); + + // Admin lists users (at least admin + alice). + let list = send(&app, "GET", "/users", Some(&admin), None).await; + assert_eq!(list.status, StatusCode::OK); + assert!(list.body.as_array().unwrap().len() >= 2); + + // Admin promotes alice to teacher; the change is reflected in the response... + let promoted = send( + &app, + "PATCH", + &format!("/users/{alice_id}/role"), + Some(&admin), + Some(json!({"role":"teacher"})), + ) + .await; + assert_eq!(promoted.status, StatusCode::OK); + assert_eq!(promoted.body["role"], "teacher"); + // ...and takes effect immediately: alice can now create events. + assert_eq!( + send( + &app, + "POST", + "/events", + Some(&alice), + Some(json!({ "title": "now allowed" })) + ) + .await + .status, + StatusCode::CREATED + ); + + // Unknown role value -> 400. + assert_eq!( + send( + &app, + "PATCH", + &format!("/users/{alice_id}/role"), + Some(&admin), + Some(json!({"role":"wizard"})) + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + // Missing user -> 404. + assert_eq!( + send( + &app, + "PATCH", + "/users/does-not-exist/role", + Some(&admin), + Some(json!({"role":"teacher"})) + ) + .await + .status, + StatusCode::NOT_FOUND + ); + // An admin cannot change their own role (anti-lockout guard). + let admin_id = id_of(&send(&app, "GET", "/auth/me", Some(&admin), None).await.body); + assert_eq!( + send( + &app, + "PATCH", + &format!("/users/{admin_id}/role"), + Some(&admin), + Some(json!({"role":"student"})) + ) + .await + .status, + StatusCode::FORBIDDEN + ); +} + +// --- regression: race safety, session hygiene, CORS ---------------------- + +/// #1 — Many concurrent marks for the *same* (event, user). A find-then-insert +/// implementation races the unique index and 500s; the atomic composite-id +/// upsert must let every request succeed and leave exactly one row. +#[tokio::test] +async fn concurrent_attendance_marks_never_collide() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let student = login(&app, "student").await; + let student_id = id_of( + &send(&app, "GET", "/auth/me", Some(&student), None) + .await + .body, + ); + let event_id = id_of( + &send( + &app, + "POST", + "/events", + Some(&teacher), + Some(json!({ "title": "e" })), + ) + .await + .body, + ); + + let mut handles = Vec::new(); + for i in 0..24 { + let app = app.clone(); + let teacher = teacher.clone(); + let uri = format!("/events/{event_id}/attendance"); + let status = if i % 2 == 0 { "present" } else { "late" }; + let body = json!({ "status": status, "user_id": student_id }); + handles.push(tokio::spawn(async move { + send(&app, "POST", &uri, Some(&teacher), Some(body)) + .await + .status + })); + } + for h in handles { + assert_eq!( + h.await.unwrap(), + StatusCode::OK, + "concurrent mark must not fail" + ); + } + + let roster = send( + &app, + "GET", + &format!("/events/{event_id}/attendance"), + Some(&teacher), + None, + ) + .await; + assert_eq!( + roster.body.as_array().unwrap().len(), + 1, + "upsert keeps a single row" + ); +} + +/// #1 — Same guarantee for exam grading. +#[tokio::test] +async fn concurrent_exam_grades_never_collide() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let student = login(&app, "student").await; + let student_id = id_of( + &send(&app, "GET", "/auth/me", Some(&student), None) + .await + .body, + ); + let exam_id = id_of( + &send( + &app, + "POST", + "/exams", + Some(&teacher), + Some(json!({ "title": "e", "kind": "quiz" })), + ) + .await + .body, + ); + + let mut handles = Vec::new(); + for mark in 0..24i64 { + let app = app.clone(); + let teacher = teacher.clone(); + let uri = format!("/exams/{exam_id}/results"); + let body = json!({ "mark": mark, "user_id": student_id }); + handles.push(tokio::spawn(async move { + send(&app, "POST", &uri, Some(&teacher), Some(body)) + .await + .status + })); + } + for h in handles { + assert_eq!( + h.await.unwrap(), + StatusCode::OK, + "concurrent grade must not fail" + ); + } + + let results = send( + &app, + "GET", + &format!("/exams/{exam_id}/results"), + Some(&teacher), + None, + ) + .await; + assert_eq!( + results.body.as_array().unwrap().len(), + 1, + "upsert keeps a single row" + ); +} + +/// #2 — A successful login sweeps expired session rows but leaves live ones. +#[tokio::test] +async fn login_purges_expired_sessions() { + let (app, db) = app_and_db().await; + let ali = login(&app, "ali").await; // one live session + + // Inject a session that has already expired. + db.query("CREATE session SET user = type::record('user', $u), token = 'expired-token', expires_at = 1") + .bind(("u", "nobody".to_string())) + .await + .unwrap() + .check() + .unwrap(); + assert!( + Session::find_by_token("expired-token", &db) + .await + .unwrap() + .is_some() + ); + + // A later successful login sweeps expired rows... + login(&app, "veli").await; + assert!( + Session::find_by_token("expired-token", &db) + .await + .unwrap() + .is_none(), + "expired session should be purged on login" + ); + // ...while the still-valid session keeps working. + assert_eq!( + send(&app, "GET", "/auth/me", Some(&ali), None).await.status, + StatusCode::OK + ); +} + +/// Regression: `Username::try_new` used to validate the trimmed value but store +/// the raw input, so `"ali"`, `"ali "` and `" ali"` were three distinct, +/// visually identical accounts — and a user who registered with padding could +/// only log in by reproducing it exactly. The name must be canonicalized +/// (trimmed) at construction and at login lookup. +#[tokio::test] +async fn padded_usernames_are_canonicalized_not_distinct_accounts() { + let app = mem_app().await; + + let res = send( + &app, + "POST", + "/auth/register", + None, + Some(json!({ "username": "ali", "password": "secret1" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + + // Padding must not mint a lookalike account. + for spoof in ["ali ", " ali", " ali "] { + let res = send( + &app, + "POST", + "/auth/register", + None, + Some(json!({ "username": spoof, "password": "secret1" })), + ) + .await; + assert_eq!( + res.status, + StatusCode::CONFLICT, + "{spoof:?} must collide with \"ali\"" + ); + } + + // A name registered with padding is stored trimmed... + let res = send( + &app, + "POST", + "/auth/register", + None, + Some(json!({ "username": " veli ", "password": "secret1" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + assert_eq!(res.body["username"], "veli"); + + // ...and the login lookup tolerates padding the same way registration does. + for attempt in ["veli", " veli "] { + let res = send( + &app, + "POST", + "/auth/login", + None, + Some(json!({ "username": attempt, "password": "secret1" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "login as {attempt:?}"); + } +} + +/// Regression: the grade endpoint verified the exam, the mark, and that the +/// target exists — but never that the grader isn't the target, so any teacher +/// could write their own mark. "Grading never targets oneself" (README). +#[tokio::test] +async fn graders_cannot_grade_themselves() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let boss = login_as(&app, &db, "boss", "manager").await; + let teacher_id = id_of( + &send(&app, "GET", "/auth/me", Some(&teacher), None) + .await + .body, + ); + let boss_id = id_of(&send(&app, "GET", "/auth/me", Some(&boss), None).await.body); + + let exam_id = id_of( + &send( + &app, + "POST", + "/exams", + Some(&teacher), + Some(json!({"title":"t","kind":"quiz"})), + ) + .await + .body, + ); + + // Self-grading is forbidden at every privilege level, not just for teachers. + for (cookie, own_id) in [(&teacher, &teacher_id), (&boss, &boss_id)] { + let res = send( + &app, + "POST", + &format!("/exams/{exam_id}/results"), + Some(cookie), + Some(json!({ "mark": 100, "user_id": own_id })), + ) + .await; + assert_eq!( + res.status, + StatusCode::FORBIDDEN, + "self-grade must be rejected" + ); + } + + // And the rejected attempts wrote nothing. + assert_eq!( + send( + &app, + "GET", + &format!("/exams/{exam_id}/results"), + Some(&teacher), + None + ) + .await + .body + .as_array() + .unwrap() + .len(), + 0 + ); + + // Grading someone *else* still works (boss grades teacher). + let res = send( + &app, + "POST", + &format!("/exams/{exam_id}/results"), + Some(&boss), + Some(json!({ "mark": 90, "user_id": teacher_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); +} + +/// Regression: `User::create` pre-checks the username and then inserts, so two +/// concurrent registrations of the same name could both pass the check; the +/// loser then hit the unique index and surfaced as a raw 500. A lost race must +/// report the same 409 as the sequential duplicate, and exactly one account may +/// exist afterwards. +#[tokio::test] +async fn concurrent_duplicate_registrations_conflict_not_500() { + let (app, db) = app_and_db().await; + + let mut handles = Vec::new(); + for _ in 0..24 { + let app = app.clone(); + handles.push(tokio::spawn(async move { + send( + &app, + "POST", + "/auth/register", + None, + Some(json!({ "username": "dup", "password": "secret1" })), + ) + .await + .status + })); + } + + let mut created = 0; + for h in handles { + match h.await.unwrap() { + StatusCode::CREATED => created += 1, + StatusCode::CONFLICT => {} + other => panic!("unexpected status {other} — a lost race must be a 409, not a 500"), + } + } + assert_eq!(created, 1, "exactly one registration wins"); + + // Exactly one row exists for the name. + let users: Vec = db + .query("SELECT * FROM user WHERE username = 'dup'") + .await + .unwrap() + .check() + .unwrap() + .take(0) + .unwrap(); + assert_eq!( + users.len(), + 1, + "exactly one user row for the duplicated name" + ); +} + +/// Regression: listing a child collection of a missing parent used to return an +/// empty 200 list — indistinguishable from "exists but empty". A missing parent +/// is a 404, matching the write endpoints on the same paths. +#[tokio::test] +async fn child_lists_of_missing_parents_are_404() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + + assert_eq!( + send(&app, "GET", "/events/nope/attendance", Some(&teacher), None) + .await + .status, + StatusCode::NOT_FOUND + ); + assert_eq!( + send(&app, "GET", "/exams/nope/results", Some(&teacher), None) + .await + .status, + StatusCode::NOT_FOUND + ); +} + +/// Regression: the session cookie never carried the `Secure` attribute, so a +/// TLS deployment would let browsers replay it over plain HTTP. The attribute +/// now follows `COOKIE_SECURE` (`Config::cookie_secure`); the default stays off +/// so plain-HTTP local dev keeps working. +#[tokio::test] +async fn session_cookie_secure_attribute_follows_config() { + async fn login_set_cookie(app: &axum::Router) -> String { + let creds = json!({ "username": "ada", "password": "secret1" }); + assert_eq!( + send(app, "POST", "/auth/register", None, Some(creds.clone())) + .await + .status, + StatusCode::CREATED + ); + let req = Request::builder() + .method("POST") + .uri("/auth/login") + .header("content-type", "application/json") + .body(Body::from(creds.to_string())) + .unwrap(); + let res = app.clone().oneshot(req).await.unwrap(); + assert_eq!(res.status(), StatusCode::OK); + res.headers() + .get("set-cookie") + .unwrap() + .to_str() + .unwrap() + .to_string() + } + + // Default (dev): HttpOnly but not Secure. + let plain = login_set_cookie(&mem_app().await).await; + assert!( + plain.contains("HttpOnly"), + "cookie must stay HttpOnly: {plain}" + ); + assert!( + !plain.contains("Secure"), + "dev cookie must not be Secure: {plain}" + ); + + // With the flag on: Secure present. + let db = database::init_mem().await.unwrap(); + let app = build_router(AppState { + db, + cookie_secure: true, + rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), + }); + let secure = login_set_cookie(&app).await; + assert!( + secure.contains("Secure"), + "cookie must be Secure when configured: {secure}" + ); + assert!( + secure.contains("HttpOnly"), + "Secure must not displace HttpOnly: {secure}" + ); +} + +/// Regression: PATCH could set an event's times but never clear them — a JSON +/// `null` was indistinguishable from an omitted field and silently kept the old +/// value. An explicit `null` now clears the field; omitted still keeps it. +#[tokio::test] +async fn patch_null_clears_event_times() { + let (app, db) = app_and_db().await; + let ali = login_as(&app, &db, "ali", "teacher").await; + let event_id = id_of( + &send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({"title":"mtg","starts_at":1000,"ends_at":2000})), + ) + .await + .body, + ); + + // Omitted fields still keep their values. + let res = send( + &app, + "PATCH", + &format!("/events/{event_id}"), + Some(&ali), + Some(json!({"title":"mtg2"})), + ) + .await; + assert_eq!(res.body["starts_at"], 1000); + assert_eq!(res.body["ends_at"], 2000); + + // An explicit null clears just that field. + let res = send( + &app, + "PATCH", + &format!("/events/{event_id}"), + Some(&ali), + Some(json!({"ends_at": null})), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["starts_at"], 1000); + assert!(res.body["ends_at"].is_null()); + + // With ends_at cleared, moving starts_at past the old end is legal... + assert_eq!( + send( + &app, + "PATCH", + &format!("/events/{event_id}"), + Some(&ali), + Some(json!({"starts_at": 5000})) + ) + .await + .status, + StatusCode::OK + ); + // ...and a new ends_at before starts_at is still rejected. + assert_eq!( + send( + &app, + "PATCH", + &format!("/events/{event_id}"), + Some(&ali), + Some(json!({"ends_at": 1})) + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + + // Clearing both works. + let res = send( + &app, + "PATCH", + &format!("/events/{event_id}"), + Some(&ali), + Some(json!({"starts_at": null, "ends_at": null})), + ) + .await; + assert!(res.body["starts_at"].is_null()); + assert!(res.body["ends_at"].is_null()); +} + +/// #4 — CORS echoes the caller's origin and allows credentials, never `*` +/// (which browsers reject for cookie-bearing requests). +#[tokio::test] +async fn cors_is_credential_safe_not_wildcard() { + let app = mem_app().await; + let req = Request::builder() + .method("GET") + .uri("/health") + .header("origin", "https://client.example") + .body(Body::empty()) + .unwrap(); + let res = app.oneshot(req).await.unwrap(); + let headers = res.headers(); + assert_eq!( + headers.get("access-control-allow-origin").unwrap(), + "https://client.example", + "origin must be reflected, not wildcarded" + ); + assert_eq!( + headers.get("access-control-allow-credentials").unwrap(), + "true", + ); +} diff --git a/tests/persistence.rs b/tests/persistence.rs new file mode 100644 index 0000000..dc73ed2 --- /dev/null +++ b/tests/persistence.rs @@ -0,0 +1,147 @@ +//! File-backed engine tests: exercise the real surrealkv storage path (not the +//! in-memory engine used elsewhere) against a throwaway `tempfile` directory, +//! including surviving a full close + reopen. + +mod common; + +use std::time::Duration; + +use axum::http::StatusCode; +use common::send; +use hezarfen_backend::config::Config; +use hezarfen_backend::database::Database; +use hezarfen_backend::rate_limit::RateLimitConfig; +use hezarfen_backend::state::AppState; +use hezarfen_backend::{build_router, database}; +use serde_json::json; +use tempfile::TempDir; + +/// Re-open the on-disk database. surrealkv releases its file lock asynchronously +/// once the previous handle drops, so we retry briefly — a real restart is a new +/// process, which never contends. +async fn reopen(cfg: &Config) -> Database { + for _ in 0..100 { + match database::init(cfg).await { + Ok(db) => return db, + Err(_) => tokio::time::sleep(Duration::from_millis(50)).await, + } + } + database::init(cfg).await.expect("reopen after retries") +} + +fn config_at(dir: &TempDir) -> Config { + Config { + host: "127.0.0.1".into(), + port: 0, + db_path: dir.path().join("hezarfen.db").to_str().unwrap().to_string(), + db_ns: "hezarfen".into(), + db_name: "hezarfen".into(), + cookie_secure: false, + rate_limit: RateLimitConfig::unlimited(), + } +} + +fn state(db: Database) -> AppState { + AppState { + db, + cookie_secure: false, + rate_limit: RateLimitConfig::unlimited(), + } +} + +/// The full flow works against the on-disk engine, same as in-memory. +#[tokio::test] +async fn file_engine_runs_full_flow() { + let dir = tempfile::tempdir().unwrap(); + let db = database::init(&config_at(&dir)) + .await + .expect("open file db"); + let app = build_router(state(db)); + + let creds = json!({ "username": "ali", "password": "secret1" }); + assert_eq!( + send(&app, "POST", "/auth/register", None, Some(creds.clone())) + .await + .status, + StatusCode::CREATED + ); + let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) + .await + .cookie + .unwrap(); + + let note = send( + &app, + "POST", + "/notes", + Some(&cookie), + Some(json!({ "title": "disk" })), + ) + .await; + assert_eq!(note.status, StatusCode::CREATED); + assert_eq!( + send(&app, "GET", "/notes", Some(&cookie), None) + .await + .body + .as_array() + .unwrap() + .len(), + 1 + ); +} + +/// Data written in one process lifetime is still readable after closing and +/// re-opening the database at the same path (list endpoints do table scans). +#[tokio::test] +async fn data_survives_reopen() { + let dir = tempfile::tempdir().unwrap(); + let cfg = config_at(&dir); + let creds = json!({ "username": "ali", "password": "secret1" }); + + // First boot: create a user and a note, then drop the handle. + { + let db = database::init(&cfg).await.expect("first open"); + let app = build_router(state(db)); + assert_eq!( + send(&app, "POST", "/auth/register", None, Some(creds.clone())) + .await + .status, + StatusCode::CREATED + ); + let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) + .await + .cookie + .unwrap(); + assert_eq!( + send( + &app, + "POST", + "/notes", + Some(&cookie), + Some(json!({ "title": "persisted" })) + ) + .await + .status, + StatusCode::CREATED + ); + } + + // Second boot from the same path: the user and note are still there. + { + let db = reopen(&cfg).await; + let app = build_router(state(db)); + let login = send(&app, "POST", "/auth/login", None, Some(creds)).await; + assert_eq!(login.status, StatusCode::OK, "user survived reopen"); + let cookie = login.cookie.unwrap(); + let notes = send(&app, "GET", "/notes", Some(&cookie), None).await; + assert_eq!( + notes.status, + StatusCode::OK, + "notes list body: {}", + notes.body + ); + let rows = notes.body.as_array().unwrap(); + assert_eq!(rows.len(), 1, "note survived reopen"); + assert_eq!(rows[0]["title"], "persisted"); + } +} diff --git a/tests/rate_limit.rs b/tests/rate_limit.rs new file mode 100644 index 0000000..6e49ba7 --- /dev/null +++ b/tests/rate_limit.rs @@ -0,0 +1,477 @@ +//! Router-level rate limiting tests. Each test builds the app with a +//! deliberately tight [`RateLimitConfig`] and, with `trust_proxy` on, poses as +//! different clients via the `X-Forwarded-For` header — `oneshot` requests +//! carry no real peer address, so the header path is also the only way to +//! separate callers here. The final tests instead boot a real TCP server to +//! exercise the peer-address (`ConnectInfo`) keying exactly as production runs +//! it. Window-arithmetic and header-parsing edge cases live as unit tests in +//! `src/rate_limit.rs` under paused tokio time. + +use axum::Router; +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use hezarfen_backend::rate_limit::RateLimitConfig; +use hezarfen_backend::state::AppState; +use hezarfen_backend::{build_router, database}; +use serde_json::{Value, json}; +use tower::ServiceExt; + +/// App with the given limits, backed by a fresh in-memory database. +async fn app_with(rate_limit: RateLimitConfig) -> Router { + let db = database::init_mem().await.expect("in-memory db"); + build_router(AppState { + db, + cookie_secure: false, + rate_limit, + }) +} + +/// Send one request posing as client `ip` (via `X-Forwarded-For`). Returns the +/// status, the parsed body, and the `Retry-After` header if present. +async fn send_as( + app: &Router, + ip: &str, + method: &str, + uri: &str, + body: Option, +) -> (StatusCode, Value, Option) { + let builder = Request::builder() + .method(method) + .uri(uri) + .header("x-forwarded-for", ip); + let request = match body { + Some(b) => builder + .header("content-type", "application/json") + .body(Body::from(b.to_string())) + .unwrap(), + None => builder.body(Body::empty()).unwrap(), + }; + + let response = app.clone().oneshot(request).await.unwrap(); + let status = response.status(); + let retry_after = response + .headers() + .get("retry-after") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse().ok()); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let body = serde_json::from_slice(&bytes).unwrap_or(Value::Null); + (status, body, retry_after) +} + +fn bad_login() -> Option { + Some(json!({ "username": "ghost", "password": "wrong-pass" })) +} + +fn auth_only(per_minute: u32) -> RateLimitConfig { + RateLimitConfig { + auth_per_minute: per_minute, + api_per_minute: 0, + trust_proxy: true, + } +} + +#[tokio::test] +async fn login_attempts_hit_the_auth_limit() { + let app = app_with(auth_only(3)).await; + + for i in 1..=3 { + let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; + assert_eq!( + status, + StatusCode::UNAUTHORIZED, + "attempt {i} still allowed" + ); + } + + let (status, body, retry_after) = + send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); + assert_eq!(body["error"], "too many requests"); + let secs = retry_after.expect("429 must carry Retry-After"); + assert!((1..=60).contains(&secs), "Retry-After {secs} out of range"); +} + +#[tokio::test] +async fn register_and_login_share_the_auth_bucket() { + let app = app_with(auth_only(2)).await; + let creds = json!({ "username": "ada", "password": "secret1" }); + + let (status, _, _) = send_as( + &app, + "1.1.1.1", + "POST", + "/auth/register", + Some(creds.clone()), + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", Some(creds.clone())).await; + assert_eq!(status, StatusCode::OK); + + // Two credential requests spent the whole budget; the third is metered + // regardless of whether it would have succeeded. + let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", Some(creds)).await; + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); +} + +#[tokio::test] +async fn clients_are_limited_independently() { + let app = app_with(auth_only(1)).await; + + let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS, "1.1.1.1 exhausted"); + + // A different client is untouched by 1.1.1.1's exhausted bucket. + let (status, _, _) = send_as(&app, "2.2.2.2", "POST", "/auth/login", bad_login()).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); +} + +#[tokio::test] +async fn auth_limit_spares_me_logout_and_the_rest_of_the_api() { + let app = app_with(auth_only(1)).await; + + // Exhaust the credential budget. + let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); + + // Same client: session probing, logout, and plain API stay reachable. + let (status, _, _) = send_as(&app, "1.1.1.1", "GET", "/auth/me", None).await; + assert_eq!(status, StatusCode::UNAUTHORIZED, "me is not rate limited"); + let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/logout", None).await; + assert_eq!(status, StatusCode::NO_CONTENT, "logout is not rate limited"); + let (status, _, _) = send_as(&app, "1.1.1.1", "GET", "/health", None).await; + assert_eq!(status, StatusCode::OK, "health is not rate limited"); +} + +#[tokio::test] +async fn api_limit_meters_every_route() { + let app = app_with(RateLimitConfig { + auth_per_minute: 0, + api_per_minute: 5, + trust_proxy: true, + }) + .await; + + for i in 1..=5 { + let (status, _, _) = send_as(&app, "1.1.1.1", "GET", "/health", None).await; + assert_eq!(status, StatusCode::OK, "request {i} still allowed"); + } + let (status, body, retry_after) = send_as(&app, "1.1.1.1", "GET", "/health", None).await; + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); + assert_eq!(body["error"], "too many requests"); + assert!(retry_after.is_some()); +} + +#[tokio::test] +async fn zero_disables_a_tier() { + let app = app_with(RateLimitConfig::unlimited()).await; + for _ in 0..20 { + let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; + assert_eq!(status, StatusCode::UNAUTHORIZED, "never 429 when disabled"); + } +} + +#[tokio::test] +async fn forwarded_header_is_ignored_unless_proxy_is_trusted() { + let app = app_with(RateLimitConfig { + auth_per_minute: 2, + api_per_minute: 0, + trust_proxy: false, + }) + .await; + + // Without TRUST_PROXY, spoofed X-Forwarded-For must not mint fresh + // buckets: all three land on the shared fallback address and the third + // request trips the limit despite claiming three different clients. + for (i, ip) in ["1.1.1.1", "2.2.2.2"].iter().enumerate() { + let (status, _, _) = send_as(&app, ip, "POST", "/auth/login", bad_login()).await; + assert_eq!(status, StatusCode::UNAUTHORIZED, "attempt {i} allowed"); + } + let (status, _, _) = send_as(&app, "3.3.3.3", "POST", "/auth/login", bad_login()).await; + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); +} + +#[tokio::test] +async fn only_the_rightmost_forwarded_hop_counts() { + let app = app_with(auth_only(2)).await; + + // Different left (client-forgeable) entries, same rightmost hop: one bucket. + let (status, _, _) = + send_as(&app, "6.6.6.6, 9.9.9.9", "POST", "/auth/login", bad_login()).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + let (status, _, _) = + send_as(&app, "7.7.7.7, 9.9.9.9", "POST", "/auth/login", bad_login()).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + let (status, _, _) = + send_as(&app, "8.8.8.8, 9.9.9.9", "POST", "/auth/login", bad_login()).await; + assert_eq!( + status, + StatusCode::TOO_MANY_REQUESTS, + "forged left-hand entries must not evade the limit" + ); +} + +#[tokio::test] +async fn ipv6_clients_are_keyed_too() { + let app = app_with(auth_only(1)).await; + + let (status, _, _) = send_as(&app, "2001:db8::1", "POST", "/auth/login", bad_login()).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + let (status, _, _) = send_as(&app, "2001:db8::1", "POST", "/auth/login", bad_login()).await; + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); + + let (status, _, _) = send_as(&app, "2001:db8::2", "POST", "/auth/login", bad_login()).await; + assert_eq!( + status, + StatusCode::UNAUTHORIZED, + "distinct v6 client is fresh" + ); +} + +#[tokio::test] +async fn malformed_forwarded_entries_share_the_fallback_bucket() { + let app = app_with(auth_only(2)).await; + + // Unparseable entries cannot mint per-garbage buckets — they all collapse + // onto the fallback address, so the third request trips the shared limit. + for garbage in ["not-an-ip", "999.1.2.3"] { + let (status, _, _) = send_as(&app, garbage, "POST", "/auth/login", bad_login()).await; + assert_eq!(status, StatusCode::UNAUTHORIZED, "{garbage:?} allowed once"); + } + let (status, _, _) = send_as(&app, "also;garbage", "POST", "/auth/login", bad_login()).await; + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); +} + +#[tokio::test] +async fn auth_denials_still_spend_the_api_budget() { + // Both tiers on: the catch-all api tier is the outer layer, so it meters + // raw request volume — including credential attempts the inner auth tier + // goes on to reject. + let app = app_with(RateLimitConfig { + auth_per_minute: 1, + api_per_minute: 3, + trust_proxy: true, + }) + .await; + + let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); // api 1/3, auth 1/1 + for _ in 0..2 { + let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/login", bad_login()).await; + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); // auth tier; api 2/3 then 3/3 + } + + // The api budget is gone even though only one login reached a handler. + let (status, _, _) = send_as(&app, "1.1.1.1", "GET", "/health", None).await; + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); + + // Per-IP, not global: another client is unaffected. + let (status, _, _) = send_as(&app, "2.2.2.2", "GET", "/health", None).await; + assert_eq!(status, StatusCode::OK); +} + +#[tokio::test] +async fn concurrent_bursts_never_over_admit() { + let app = app_with(RateLimitConfig { + auth_per_minute: 0, + api_per_minute: 5, + trust_proxy: true, + }) + .await; + + // 20 requests race one 5-token bucket; the mutex must admit exactly 5, + // no matter how the tasks interleave. + let mut set = tokio::task::JoinSet::new(); + for _ in 0..20 { + let app = app.clone(); + set.spawn(async move { send_as(&app, "1.1.1.1", "GET", "/health", None).await.0 }); + } + + let (mut ok, mut limited) = (0, 0); + while let Some(status) = set.join_next().await { + match status.unwrap() { + StatusCode::OK => ok += 1, + StatusCode::TOO_MANY_REQUESTS => limited += 1, + other => panic!("unexpected status {other}"), + } + } + assert_eq!((ok, limited), (5, 15)); +} + +/// Boot the app on a real TCP port, `ConnectInfo` wired exactly like `main`. +async fn spawn_server(rate_limit: RateLimitConfig) -> String { + let db = database::init_mem().await.expect("in-memory db"); + let app = build_router(AppState { + db, + cookie_secure: false, + rate_limit, + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + axum::serve( + listener, + app.into_make_service_with_connect_info::(), + ) + .await + .unwrap(); + }); + format!("http://{addr}") +} + +#[tokio::test] +async fn real_connections_are_keyed_by_peer_address() { + let base = spawn_server(RateLimitConfig { + auth_per_minute: 2, + api_per_minute: 0, + trust_proxy: false, + }) + .await; + let client = reqwest::Client::new(); + + // Every request arrives from 127.0.0.1. Spoofed X-Forwarded-For values + // must not matter with TRUST_PROXY off: one peer, one bucket. + for spoof in ["1.1.1.1", "2.2.2.2"] { + let res = client + .post(format!("{base}/auth/login")) + .header("x-forwarded-for", spoof) + .json(&json!({ "username": "ghost", "password": "wrong-pass" })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::UNAUTHORIZED); + } + + let res = client + .post(format!("{base}/auth/login")) + .header("x-forwarded-for", "3.3.3.3") + .json(&json!({ "username": "ghost", "password": "wrong-pass" })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS); + let retry_after = res + .headers() + .get("retry-after") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse::().ok()) + .expect("429 over real HTTP carries Retry-After"); + assert!((1..=60).contains(&retry_after)); + let body: Value = res.json().await.unwrap(); + assert_eq!(body["error"], "too many requests"); +} + +#[tokio::test] +async fn a_limit_of_fifty_admits_exactly_fifty_requests() { + // Production-scale boundary through the whole HTTP stack: all 50 budgeted + // requests answer 200, the 51st answers 429 — no off-by-one at real sizes. + let app = app_with(RateLimitConfig { + auth_per_minute: 0, + api_per_minute: 50, + trust_proxy: true, + }) + .await; + + for n in 1..=50 { + let (status, _, _) = send_as(&app, "1.1.1.1", "GET", "/health", None).await; + assert_eq!(status, StatusCode::OK, "request {n}/50 must pass"); + } + + let (status, body, retry_after) = send_as(&app, "1.1.1.1", "GET", "/health", None).await; + assert_eq!( + status, + StatusCode::TOO_MANY_REQUESTS, + "request 51 must trip" + ); + assert_eq!(body["error"], "too many requests"); + assert!(retry_after.is_some_and(|s| (1..=60).contains(&s))); + + // The 51st being rejected spent nothing extra: a fresh client still has + // its own full budget. + let (status, _, _) = send_as(&app, "2.2.2.2", "GET", "/health", None).await; + assert_eq!(status, StatusCode::OK); +} + +/// Every route, at the ACTUAL shipped limits: request `limit` passes, request +/// `limit + 1` answers 429. The route list is pulled from the app's own +/// OpenAPI document, so an endpoint added tomorrow is covered automatically; +/// `/` and the Swagger mount don't appear there and are appended by hand. +/// +/// Each (method, path) pair poses as its own client IP, giving it a fresh +/// bucket. Requests carry no body — extractors reject them long after the +/// limiter has counted, which is exactly what makes hammering the credential +/// endpoints cheap (no argon2 runs for a body-less request). +#[tokio::test] +async fn every_route_enforces_the_shipped_limit_plus_one() { + use hezarfen_backend::config::{DEFAULT_API_RATE_LIMIT, DEFAULT_AUTH_RATE_LIMIT}; + + let app = app_with(RateLimitConfig { + auth_per_minute: DEFAULT_AUTH_RATE_LIMIT, + api_per_minute: DEFAULT_API_RATE_LIMIT, + trust_proxy: true, + }) + .await; + + // Enumerate routes from the spec (fetched under a reserved IP so the + // fetch itself doesn't spend any route's budget). + let (status, spec, _) = send_as(&app, "254.0.0.1", "GET", "/api-docs/openapi.json", None).await; + assert_eq!(status, StatusCode::OK); + let paths = spec["paths"].as_object().expect("openapi paths object"); + + let mut routes: Vec<(String, String)> = vec![ + ("GET".into(), "/".into()), + ("GET".into(), "/swagger".into()), + ]; + for (path, item) in paths { + // "/notes/{id}" -> "/notes/id": a well-formed URL whose dummy segment + // fails lookup in the handler, long after the limiter counted it. + let concrete = path.replace(['{', '}'], ""); + for method in item.as_object().expect("path item").keys() { + routes.push((method.to_uppercase(), concrete.clone())); + } + } + assert!( + routes.len() >= 25, + "suspiciously few routes ({}) — OpenAPI enumeration broke?", + routes.len() + ); + + for (i, (method, path)) in routes.iter().enumerate() { + // One unique client per route (203.0.x.x is TEST-NET-3). + let ip = format!("203.0.{}.{}", i / 200, (i % 200) + 1); + // The strict tier owns the two credential endpoints; everything else + // runs into the catch-all api tier. + let limit = if path == "/auth/login" || path == "/auth/register" { + DEFAULT_AUTH_RATE_LIMIT + } else { + DEFAULT_API_RATE_LIMIT + }; + + for n in 1..=limit { + let (status, _, _) = send_as(&app, &ip, method, path, None).await; + assert_ne!( + status, + StatusCode::TOO_MANY_REQUESTS, + "{method} {path}: request {n}/{limit} must not be limited" + ); + } + let (status, _, retry_after) = send_as(&app, &ip, method, path, None).await; + assert_eq!( + status, + StatusCode::TOO_MANY_REQUESTS, + "{method} {path}: request {}/{limit} must be limited", + limit + 1 + ); + assert!( + retry_after.is_some_and(|s| (1..=60).contains(&s)), + "{method} {path}: 429 must carry a sane Retry-After" + ); + } +}