use super::*; use acaua_core::auth::{AuthService, LoginStep, Role, Scope}; use axum::body::to_bytes; use axum::http::{HeaderMap, Method, Request}; use std::net::{IpAddr, SocketAddr}; use tower::ServiceExt; const PW: &str = "correct horse battery staple"; const PW2: &str = "another long enough passphrase"; fn now() -> u64 { crate::auth_http::unix_now() } fn peer() -> IpAddr { "192.0.2.10".parse().unwrap() } struct H { _dir: tempfile::TempDir, auth: Arc, app: Router, uri: String, recovery: Vec, } struct Reply { status: StatusCode, headers: HeaderMap, body: String, } impl Reply { fn json(&self) -> serde_json::Value { serde_json::from_str(&self.body).unwrap() } } fn request(method: Method, path: &str) -> axum::http::request::Builder { let peer = SocketAddr::new(peer(), 4000); let mut b = Request::builder().method(method).uri(path); b.extensions_mut() .unwrap() .insert(axum::extract::ConnectInfo(peer)); b } fn post_json(path: &str, body: serde_json::Value) -> Request { request(Method::POST, path) .header(header::CONTENT_TYPE, "application/json") .body(Body::from(body.to_string())) .unwrap() } fn empty(method: Method, path: &str) -> Request { request(method, path).body(Body::empty()).unwrap() } async fn send(app: &Router, req: Request) -> Reply { let res = app.clone().oneshot(req).await.unwrap(); let status = res.status(); let headers = res.headers().clone(); let bytes = to_bytes(res.into_body(), 4 * 1024 * 1024).await.unwrap(); Reply { status, headers, body: String::from_utf8_lossy(&bytes).into_owned(), } } fn totp(uri: &str, unix: u64) -> String { totp_rs::Totp::from_url(uri) .unwrap() .generate(unix) .to_string() } fn fresh(transport: Transport) -> (tempfile::TempDir, Arc, Router) { let dir = tempfile::tempdir().unwrap(); let auth = Arc::new(AuthService::open(dir.path(), None).unwrap()); let state = AppState::new( Arc::new(Storage::open(dir.path()).unwrap()), auth.clone(), transport, ); (dir, auth, build_app(state)) } fn fresh_with_state( transport: Transport, ) -> (tempfile::TempDir, Arc, AppState, Router) { let dir = tempfile::tempdir().unwrap(); let auth = Arc::new(AuthService::open(dir.path(), None).unwrap()); let state = AppState::new( Arc::new(Storage::open(dir.path()).unwrap()), auth.clone(), transport, ); let app = build_app(state.clone()); (dir, auth, state, app) } /// Server with `root` (admin, MFA active) and analyst `ana` (no MFA). fn harness(transport: Transport) -> H { let (dir, auth, app) = fresh(transport); let t = now(); let code = auth.ensure_bootstrap(t).unwrap().unwrap(); let pending = auth .complete_bootstrap(&code, "root", PW, peer(), t) .unwrap(); let e = auth.start_enrollment_pending(&pending.token, t).unwrap(); let recovery = auth .confirm_enrollment_pending(&pending.token, &totp(&e.uri, t), t) .unwrap(); auth.create_user("root", "ana", PW, Role::Analyst, t) .unwrap(); H { _dir: dir, auth, app, uri: e.uri, recovery, } } fn cookie_pair(headers: &HeaderMap) -> Option { headers .get(header::SET_COOKIE) .map(|v| v.to_str().unwrap().split(';').next().unwrap().to_string()) } impl H { async fn login(&self, user: &str) -> Reply { send( &self.app, post_json( "/api/auth/login", serde_json::json!({"username": user, "password": PW}), ), ) .await } async fn analyst_cookie(&self) -> String { let r = self.login("ana").await; assert_eq!(r.status, StatusCode::OK, "{}", r.body); cookie_pair(&r.headers).unwrap() } async fn admin_cookie(&self) -> String { let r = self.login("root").await; assert_eq!(r.status, StatusCode::OK, "{}", r.body); assert_eq!(r.json()["step"], "mfa_required"); let code = totp(&self.uri, now() + 30); let m = send( &self.app, post_json( "/api/auth/mfa", serde_json::json!({"pending": r.json()["pending"], "code": code}), ), ) .await; assert_eq!(m.status, StatusCode::OK, "{}", m.body); cookie_pair(&m.headers).unwrap() } async fn csrf(&self, cookie: &str) -> String { let r = send( &self.app, request(Method::GET, "/api/auth/state") .header(header::COOKIE, cookie) .body(Body::empty()) .unwrap(), ) .await; r.json()["csrf"].as_str().unwrap().to_string() } /// A token of `root`, minted through the service. async fn admin_token(&self, scope: Scope) -> String { let cookie = self.admin_cookie().await; self.token_from(&cookie, scope) } /// A TOTP step works once, so a second token reuses the login's session. fn token_from(&self, cookie: &str, scope: Scope) -> String { let session = cookie.split_once('=').unwrap().1.to_string(); let t = now(); let id = self.auth.authenticate_session(&session, t).unwrap().user_id; self.auth .reauthenticate(&id, &session, PW, Some(&self.recovery[0]), t) .unwrap(); let p = self.auth.authenticate_session(&session, t).unwrap(); self.auth .create_api_token(&p, "t", scope, t + 3600, t) .unwrap() .token } /// Mutation with cookie and CSRF. async fn mutate( &self, cookie: &str, method: Method, path: &str, body: serde_json::Value, ) -> Reply { let csrf = self.csrf(cookie).await; send( &self.app, request(method, path) .header(header::COOKIE, cookie) .header("x-acaua-csrf", csrf) .header(header::CONTENT_TYPE, "application/json") .body(Body::from(body.to_string())) .unwrap(), ) .await } } fn verb_method(v: Verb) -> Method { match v { Verb::Get => Method::GET, Verb::Post => Method::POST, Verb::Patch => Method::PATCH, Verb::Delete => Method::DELETE, } } fn is_closed(r: &Reply) -> bool { r.status == StatusCode::UNAUTHORIZED || r.status == StatusCode::SEE_OTHER } #[tokio::test] async fn every_route_is_closed_by_default() { let (_d, _a, app) = fresh(Transport::Local); let mut checked = 0; for route in ALL_ROUTES { if PUBLIC_ROUTES.contains(&(route.verb, route.path)) { continue; } let r = send(&app, empty(verb_method(route.verb), route.path)).await; assert!(is_closed(&r), "{} answered {}", route.path, r.status); checked += 1; } assert!(checked >= 15, "only {checked} protected routes"); for path in [ "/relatorio", "/", "/index.html", "/app.js", "/nao/existe", "/api/nada", ] { let r = send(&app, empty(Method::GET, path)).await; assert!(is_closed(&r), "{path} answered {}", r.status); } // A wrong method on a public path must not reveal the route with a 405. let r = send(&app, empty(Method::POST, "/api/health")).await; assert!(is_closed(&r), "POST /api/health answered {}", r.status); let r = send(&app, empty(Method::DELETE, "/login.html")).await; assert!(is_closed(&r)); } #[test] fn every_public_route_is_registered_and_the_list_is_exact() { for entry in PUBLIC_ROUTES { assert!( ALL_ROUTES.iter().any(|r| (r.verb, r.path) == *entry), "{} not registered", entry.1 ); } let mut paths: Vec<&str> = PUBLIC_ROUTES.iter().map(|e| e.1).collect(); paths.sort_unstable(); assert_eq!( paths, [ "/api/auth/bootstrap", "/api/auth/login", "/api/auth/mfa", "/api/auth/password-change-required", "/api/auth/state", "/api/health", "/app.css", "/i18n-en.js", "/i18n.js", "/login.html", "/login.js", "/logo.png", ] ); } #[tokio::test] async fn unknown_paths_answer_exactly_like_protected_ones() { let (_d, _a, app) = fresh(Transport::Local); for accept in ["application/json", "text/html"] { let ask = |p: &str| { request(Method::GET, p) .header(header::ACCEPT, accept) .body(Body::empty()) .unwrap() }; let known = send(&app, ask("/relatorio")).await; let unknown = send(&app, ask("/talvez-exista")).await; assert_eq!(known.status, unknown.status); assert_eq!(known.body, unknown.body); assert_eq!( known.headers.get(header::LOCATION), unknown.headers.get(header::LOCATION) ); } } #[tokio::test] async fn every_public_asset_is_served() { let (_d, _a, app) = fresh(Transport::Local); for path in [ "/login.html", "/login.js", "/app.css", "/logo.png", "/i18n.js", "/i18n-en.js", ] { let r = send(&app, empty(Method::GET, path)).await; assert_eq!(r.status, StatusCode::OK, "{path}"); } } #[tokio::test] async fn health_has_no_details() { let (_d, _a, app) = fresh(Transport::Local); let r = send(&app, empty(Method::GET, "/api/health")).await; assert_eq!(r.status, StatusCode::OK); assert_eq!(r.body, r#"{"status":"ok"}"#); assert!(!r.body.contains("version")); } #[tokio::test] async fn html_request_redirects_to_login_api_gets_401() { let (_d, _a, app) = fresh(Transport::Local); let html = request(Method::GET, "/relatorio") .header(header::ACCEPT, "text/html,application/xhtml+xml") .body(Body::empty()) .unwrap(); let r = send(&app, html).await; assert_eq!(r.status, StatusCode::SEE_OTHER); assert_eq!(r.headers[header::LOCATION], "/login.html"); let api = request(Method::GET, "/api/status") .header(header::ACCEPT, "text/html") .body(Body::empty()) .unwrap(); assert_eq!(send(&app, api).await.status, StatusCode::UNAUTHORIZED); let r = send(&app, empty(Method::GET, "/relatorio")).await; assert_eq!(r.status, StatusCode::UNAUTHORIZED); } #[tokio::test] async fn hsts_header_only_in_tls_and_proxy() { for (transport, hsts) in [ (Transport::Local, false), ( Transport::Tls { cert: "c".into(), key: "k".into(), }, true, ), ( Transport::Proxy { trusted: vec!["10.0.0.0/8".parse().unwrap()], }, true, ), ] { let (_d, _a, app) = fresh(transport); let r = send(&app, empty(Method::GET, "/api/health")).await; assert_eq!( r.headers.contains_key(header::STRICT_TRANSPORT_SECURITY), hsts ); } } #[tokio::test] async fn cookie_flags() { for (transport, secure) in [ (Transport::Local, false), ( Transport::Tls { cert: "c".into(), key: "k".into(), }, true, ), ( Transport::Proxy { trusted: vec!["10.0.0.0/8".parse().unwrap()], }, true, ), ] { let h = harness(transport); let r = h.login("ana").await; let set = r.headers[header::SET_COOKIE].to_str().unwrap().to_string(); assert!(set.contains("HttpOnly"), "{set}"); assert!(set.contains("SameSite=Strict"), "{set}"); assert!(set.contains("Path=/"), "{set}"); assert_eq!(set.contains("Secure"), secure, "{set}"); // The session token travels only in the cookie. let token = cookie_pair(&r.headers).unwrap(); assert!(!r.body.contains(token.split_once('=').unwrap().1)); } } #[tokio::test] async fn csrf_required_for_cookie_mutation() { let h = harness(Transport::Local); let cookie = h.admin_cookie().await; let bare = request(Method::POST, "/api/analyze") .header(header::COOKIE, &cookie) .header(header::CONTENT_TYPE, "application/json") .body(Body::from(r#"{"path":"/nao/existe"}"#)) .unwrap(); assert_eq!(send(&h.app, bare).await.status, StatusCode::FORBIDDEN); let wrong = request(Method::POST, "/api/analyze") .header(header::COOKIE, &cookie) .header("x-acaua-csrf", "wrong") .header(header::CONTENT_TYPE, "application/json") .body(Body::from(r#"{"path":"/nao/existe"}"#)) .unwrap(); assert_eq!(send(&h.app, wrong).await.status, StatusCode::FORBIDDEN); let good = h .mutate( &cookie, Method::POST, "/api/analyze", serde_json::json!({"path": "/nao/existe"}), ) .await; assert_eq!(good.status, StatusCode::BAD_REQUEST, "{}", good.body); let token = h.token_from(&cookie, Scope::Admin); let bearer = request(Method::POST, "/api/analyze") .header(header::AUTHORIZATION, format!("Bearer {token}")) .header(header::CONTENT_TYPE, "application/json") .body(Body::from(r#"{"path":"/nao/existe"}"#)) .unwrap(); assert_eq!(send(&h.app, bearer).await.status, StatusCode::BAD_REQUEST); } #[tokio::test] async fn session_token_is_not_accepted_as_bearer() { let h = harness(Transport::Local); let cookie = h.analyst_cookie().await; let session = cookie.split_once('=').unwrap().1; let r = send( &h.app, request(Method::GET, "/api/status") .header(header::AUTHORIZATION, format!("Bearer {session}")) .body(Body::empty()) .unwrap(), ) .await; assert_eq!(r.status, StatusCode::UNAUTHORIZED); } #[tokio::test] async fn analyst_forbidden_on_admin_routes() { let h = harness(Transport::Local); let cookie = h.analyst_cookie().await; let csrf = h.csrf(&cookie).await; for route in ALL_ROUTES .iter() .filter(|r| matches!(r.access, Access::Admin | Access::AdminRecentSession)) { let r = send( &h.app, request(verb_method(route.verb), route.path) .header(header::COOKIE, &cookie) .header("x-acaua-csrf", &csrf) .body(Body::empty()) .unwrap(), ) .await; assert_eq!(r.status, StatusCode::FORBIDDEN, "{}", route.path); } let status = send( &h.app, request(Method::GET, "/api/status") .header(header::COOKIE, &cookie) .body(Body::empty()) .unwrap(), ) .await; assert_eq!(status.status, StatusCode::OK); } #[tokio::test] async fn read_token_forbidden_on_admin_routes_and_every_mutation() { let h = harness(Transport::Local); let token = h.admin_token(Scope::Read).await; let bearer = format!("Bearer {token}"); for route in ALL_ROUTES { let public = PUBLIC_ROUTES.contains(&(route.verb, route.path)); if public || (route.access != Access::Admin && route.verb == Verb::Get) { continue; } let r = send( &h.app, request(verb_method(route.verb), route.path) .header(header::AUTHORIZATION, &bearer) .body(Body::empty()) .unwrap(), ) .await; assert_eq!(r.status, StatusCode::FORBIDDEN, "{}", route.path); } for path in [ "/api/status", "/api/alerts", "/relatorio", "/api/auth/tokens", ] { let r = send( &h.app, request(Method::GET, path) .header(header::AUTHORIZATION, &bearer) .body(Body::empty()) .unwrap(), ) .await; assert!( r.status != StatusCode::UNAUTHORIZED && r.status != StatusCode::FORBIDDEN, "{path}" ); } } #[tokio::test] async fn forwarded_for_ignored_unless_proxy() { let h = harness(Transport::Local); let mut last = None; for i in 0..21 { // Distinct unknown names, so only the per-IP limit can answer. let req = request(Method::POST, "/api/auth/login") .header(header::CONTENT_TYPE, "application/json") .header("x-forwarded-for", format!("203.0.113.{i}")) .body(Body::from( serde_json::json!({"username": format!("ghost{i}"), "password": "x"}).to_string(), )) .unwrap(); last = Some(send(&h.app, req).await); } let last = last.unwrap(); assert_eq!(last.status, StatusCode::TOO_MANY_REQUESTS); assert!(last.headers.contains_key(header::RETRY_AFTER)); let audit = h.auth.audit_tail(5).unwrap(); assert!(audit .iter() .all(|e| !serde_json::to_string(e).unwrap().contains("203.0.113"))); } #[tokio::test] async fn auth_responses_have_no_store() { let h = harness(Transport::Local); let replies = [ send(&h.app, empty(Method::GET, "/api/auth/state")).await, h.login("ana").await, send( &h.app, post_json( "/api/auth/login", serde_json::json!({"username": "ana", "password": "nope"}), ), ) .await, send(&h.app, empty(Method::POST, "/api/auth/logout")).await, send(&h.app, empty(Method::GET, "/api/status")).await, ]; for r in replies { assert_eq!(r.headers[header::CACHE_CONTROL], "no-store", "{}", r.body); } } #[tokio::test] async fn secrets_absent_from_responses() { let h = harness(Transport::Local); let token = h.admin_token(Scope::Admin).await; let bearer = format!("Bearer {token}"); for path in [ "/api/admin/users", "/api/admin/audit", "/api/auth/sessions", "/api/auth/tokens", ] { let r = send( &h.app, request(Method::GET, path) .header(header::AUTHORIZATION, &bearer) .body(Body::empty()) .unwrap(), ) .await; assert_eq!(r.status, StatusCode::OK, "{path}: {}", r.body); for leak in [ "$argon2", "password_hash", "token_hash", "totp_sealed", "recovery_hashes", &token, ] { assert!(!r.body.contains(leak), "{leak} in {path}"); } } } #[tokio::test] async fn login_failures_are_identical_and_open_no_session() { let h = harness(Transport::Local); let attempt = |user: &str| { post_json( "/api/auth/login", serde_json::json!({"username": user, "password": "wrong password"}), ) }; let unknown = send(&h.app, attempt("ghost")).await; let wrong = send(&h.app, attempt("ana")).await; assert_eq!(unknown.status, StatusCode::UNAUTHORIZED); assert_eq!(unknown.status, wrong.status); assert_eq!(unknown.body, wrong.body); assert!(!unknown.headers.contains_key(header::SET_COOKIE)); assert!(!wrong.headers.contains_key(header::SET_COOKIE)); let id = h .auth .list_users() .unwrap() .into_iter() .find(|u| u.username == "ana") .unwrap() .id; assert!(h.auth.list_sessions(&id, now()).unwrap().is_empty()); // A cookie the client chose is never honoured or served back. let r = send( &h.app, request(Method::GET, "/api/status") .header(header::COOKIE, "acaua_session=chosen-by-attacker") .body(Body::empty()) .unwrap(), ) .await; assert_eq!(r.status, StatusCode::UNAUTHORIZED); assert!(!r.headers.contains_key(header::SET_COOKIE)); } #[tokio::test] async fn oversized_body_is_refused_before_processing() { let (_d, _a, app) = fresh(Transport::Local); let huge = "a".repeat(70 * 1024); let r = send( &app, post_json( "/api/auth/login", serde_json::json!({"username": huge, "password": "x"}), ), ) .await; assert_eq!(r.status, StatusCode::PAYLOAD_TOO_LARGE); assert!(!r.body.contains(&huge[..100])); } #[tokio::test] async fn first_login_enrolls_with_a_pending_token_only() { let (_d, auth, app) = fresh(Transport::Local); let code = auth.ensure_bootstrap(now()).unwrap().unwrap(); let boot = send( &app, post_json( "/api/auth/bootstrap", serde_json::json!({"code": code, "username": "root", "password": PW}), ), ) .await; assert_eq!(boot.status, StatusCode::OK, "{}", boot.body); assert!(!boot.headers.contains_key(header::SET_COOKIE)); let pending = boot.json()["pending"].as_str().unwrap().to_string(); let anon = send(&app, empty(Method::POST, "/api/auth/enroll/start")).await; assert_eq!(anon.status, StatusCode::UNAUTHORIZED); let forged = request(Method::POST, "/api/auth/enroll/start") .header("x-acaua-pending", "forged") .body(Body::empty()) .unwrap(); assert_eq!(send(&app, forged).await.status, StatusCode::UNAUTHORIZED); // The pending token opens enrollment and nothing else. let other = request(Method::GET, "/api/status") .header("x-acaua-pending", &pending) .body(Body::empty()) .unwrap(); assert_eq!(send(&app, other).await.status, StatusCode::UNAUTHORIZED); let start = request(Method::POST, "/api/auth/enroll/start") .header("x-acaua-pending", &pending) .body(Body::empty()) .unwrap(); let start = send(&app, start).await; assert_eq!(start.status, StatusCode::OK, "{}", start.body); let uri = start.json()["uri"].as_str().unwrap().to_string(); let confirm = request(Method::POST, "/api/auth/enroll/confirm") .header("x-acaua-pending", &pending) .header(header::CONTENT_TYPE, "application/json") .body(Body::from( serde_json::json!({"code": totp(&uri, now())}).to_string(), )) .unwrap(); let confirm = send(&app, confirm).await; assert_eq!(confirm.status, StatusCode::OK, "{}", confirm.body); assert!(!confirm.json()["recovery_codes"] .as_array() .unwrap() .is_empty()); assert!(!confirm.headers.contains_key(header::SET_COOKIE)); // MFA is active now: the same token cannot enroll again. let again = request(Method::POST, "/api/auth/enroll/start") .header("x-acaua-pending", &pending) .body(Body::empty()) .unwrap(); assert_eq!(send(&app, again).await.status, StatusCode::UNAUTHORIZED); let mfa = send( &app, post_json( "/api/auth/mfa", serde_json::json!({"pending": pending, "code": totp(&uri, now() + 30)}), ), ) .await; assert_eq!(mfa.status, StatusCode::OK, "{}", mfa.body); assert!(cookie_pair(&mfa.headers).is_some()); } #[tokio::test] async fn enrolling_or_disabling_from_a_session_needs_recent_reauth() { let h = harness(Transport::Local); let cookie = h.analyst_cookie().await; let start = "/api/auth/enroll/start"; let disable = "/api/auth/mfa/disable"; let nothing = serde_json::json!({}); assert_eq!( h.mutate(&cookie, Method::POST, start, nothing.clone()) .await .status, StatusCode::FORBIDDEN ); assert_eq!( h.mutate(&cookie, Method::POST, disable, nothing.clone()) .await .status, StatusCode::FORBIDDEN ); let bad = h .mutate( &cookie, Method::POST, "/api/auth/reauth", serde_json::json!({"password": "wrong password"}), ) .await; assert_eq!(bad.status, StatusCode::UNAUTHORIZED); let ok = h .mutate( &cookie, Method::POST, "/api/auth/reauth", serde_json::json!({"password": PW}), ) .await; assert_eq!(ok.status, StatusCode::OK, "{}", ok.body); let r = h .mutate(&cookie, Method::POST, start, nothing.clone()) .await; assert_eq!(r.status, StatusCode::OK, "{}", r.body); // Past the reauth check; this analyst never activated MFA. assert_eq!( h.mutate(&cookie, Method::POST, disable, nothing) .await .status, StatusCode::CONFLICT ); } #[tokio::test] async fn confirm_from_a_session_ends_it_and_clears_the_cookie() { let h = harness(Transport::Local); let cookie = h.analyst_cookie().await; h.mutate( &cookie, Method::POST, "/api/auth/reauth", serde_json::json!({"password": PW}), ) .await; let start = h .mutate( &cookie, Method::POST, "/api/auth/enroll/start", serde_json::json!({}), ) .await; let uri = start.json()["uri"].as_str().unwrap().to_string(); let r = h .mutate( &cookie, Method::POST, "/api/auth/enroll/confirm", serde_json::json!({"code": totp(&uri, now())}), ) .await; assert_eq!(r.status, StatusCode::OK, "{}", r.body); assert!(r.headers[header::SET_COOKIE] .to_str() .unwrap() .contains("Max-Age=0")); } #[tokio::test] async fn required_password_change_opens_the_session_through_the_public_route() { let h = harness(Transport::Local); let temp = h.auth.reset_account("root", now()).unwrap(); let login = send( &h.app, post_json( "/api/auth/login", serde_json::json!({"username": "root", "password": temp}), ), ) .await; assert_eq!( login.json()["step"], "mfa_enroll_required", "{}", login.body ); let pending = login.json()["pending"].as_str().unwrap().to_string(); let t = now(); let e = h.auth.start_enrollment_pending(&pending, t).unwrap(); h.auth .confirm_enrollment_pending(&pending, &totp(&e.uri, t), t) .unwrap(); let mfa = send( &h.app, post_json( "/api/auth/mfa", serde_json::json!({"pending": pending, "code": totp(&e.uri, t + 30)}), ), ) .await; assert_eq!( mfa.json()["step"], "password_change_required", "{}", mfa.body ); assert!(!mfa.headers.contains_key(header::SET_COOKIE)); let ticket = mfa.json()["pending"].as_str().unwrap().to_string(); let done = send( &h.app, post_json( "/api/auth/password-change-required", serde_json::json!({"ticket": ticket, "current": temp, "new": PW2}), ), ) .await; assert_eq!(done.status, StatusCode::OK, "{}", done.body); assert!(cookie_pair(&done.headers).is_some()); } #[tokio::test] async fn listings_are_limited_to_the_requester_unless_admin() { let h = harness(Transport::Local); let users = h.auth.list_users().unwrap(); let root = users .iter() .find(|u| u.username == "root") .unwrap() .id .clone(); let cookie = h.analyst_cookie().await; for base in ["/api/auth/sessions", "/api/auth/tokens"] { let ask = |path: String, c: &str| { request(Method::GET, &path) .header(header::COOKIE, c) .body(Body::empty()) .unwrap() }; let own = send(&h.app, ask(base.to_string(), &cookie)).await; assert_eq!(own.status, StatusCode::OK); let other = send(&h.app, ask(format!("{base}?user_id={root}"), &cookie)).await; assert_eq!(other.status, StatusCode::FORBIDDEN, "{base}"); } let admin = h.admin_cookie().await; let ana = users .iter() .find(|u| u.username == "ana") .unwrap() .id .clone(); let r = send( &h.app, request(Method::GET, &format!("/api/auth/sessions?user_id={ana}")) .header(header::COOKIE, &admin) .body(Body::empty()) .unwrap(), ) .await; assert_eq!(r.status, StatusCode::OK); assert_eq!(r.json().as_array().unwrap().len(), 1); } #[tokio::test] async fn logout_ends_the_session() { let h = harness(Transport::Local); let cookie = h.analyst_cookie().await; let r = h .mutate( &cookie, Method::POST, "/api/auth/logout", serde_json::json!({}), ) .await; assert_eq!(r.status, StatusCode::OK, "{}", r.body); assert!(r.headers[header::SET_COOKIE] .to_str() .unwrap() .contains("Max-Age=0")); let after = send( &h.app, request(Method::GET, "/api/status") .header(header::COOKIE, &cookie) .body(Body::empty()) .unwrap(), ) .await; assert_eq!(after.status, StatusCode::UNAUTHORIZED); } #[tokio::test] async fn token_lifecycle_needs_reauth_and_returns_the_secret_once() { let h = harness(Transport::Local); let cookie = h.analyst_cookie().await; let body = serde_json::json!({"name": "ci", "scope": "read", "expires_at": now() + 3600}); let early = h .mutate(&cookie, Method::POST, "/api/auth/tokens", body.clone()) .await; assert_eq!(early.status, StatusCode::FORBIDDEN); h.mutate( &cookie, Method::POST, "/api/auth/reauth", serde_json::json!({"password": PW}), ) .await; let made = h .mutate(&cookie, Method::POST, "/api/auth/tokens", body) .await; assert_eq!(made.status, StatusCode::OK, "{}", made.body); let id = made.json()["id"].as_str().unwrap().to_string(); let secret = made.json()["token"].as_str().unwrap().to_string(); let gone = h .mutate( &cookie, Method::DELETE, "/api/auth/tokens", serde_json::json!({"id": id}), ) .await; assert_eq!(gone.status, StatusCode::OK, "{}", gone.body); let r = send( &h.app, request(Method::GET, "/api/status") .header(header::AUTHORIZATION, format!("Bearer {secret}")) .body(Body::empty()) .unwrap(), ) .await; assert_eq!(r.status, StatusCode::UNAUTHORIZED); } #[test] fn login_step_debug_never_prints_the_token() { let step = LoginStep::MfaRequired(acaua_core::auth::PendingMfa { token: "s3cret".to_string(), expires_at: 1, }); assert!(!format!("{step:?}").contains("s3cret")); } // ---- Fix round 1 ---- const BOOTSTRAP_REFUSAL: &str = r#"{"error":"invalid setup code"}"#; #[tokio::test] async fn bootstrap_after_setup_writes_no_audit_and_has_one_reply() { let h = harness(Transport::Local); let before = h.auth.audit_tail(1000).unwrap().len(); for body in [ serde_json::json!({"code": "x", "username": "new", "password": PW}), serde_json::json!({"code": "x", "username": "", "password": "short"}), ] { let r = send(&h.app, post_json("/api/auth/bootstrap", body)).await; assert_eq!(r.status, StatusCode::UNAUTHORIZED); assert_eq!(r.body, BOOTSTRAP_REFUSAL); } assert_eq!(h.auth.audit_tail(1000).unwrap().len(), before); } #[tokio::test] async fn bootstrap_guesses_are_throttled_per_ip_and_audited_with_it() { let (_d, auth, app) = fresh(Transport::Local); auth.ensure_bootstrap(now()).unwrap().unwrap(); let guess = || { post_json( "/api/auth/bootstrap", serde_json::json!({"code": "wrong", "username": "root", "password": PW}), ) }; for _ in 0..20 { let r = send(&app, guess()).await; assert_eq!(r.status, StatusCode::UNAUTHORIZED); } let before = auth.audit_tail(1000).unwrap(); let r = send(&app, guess()).await; assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS); assert!(r.headers.contains_key(header::RETRY_AFTER)); assert_eq!(auth.audit_tail(1000).unwrap().len(), before.len()); let last = serde_json::to_string(before.last().unwrap()).unwrap(); assert!(last.contains(&peer().to_string()), "{last}"); } #[tokio::test] async fn user_mutations_need_a_session_with_recent_reauth() { let h = harness(Transport::Local); let cookie = h.admin_cookie().await; let new_user = serde_json::json!({"username": "bob", "password": PW2, "role": "admin"}); let users = "/api/admin/users"; let stale = h .mutate(&cookie, Method::POST, users, new_user.clone()) .await; assert_eq!(stale.status, StatusCode::FORBIDDEN); assert_eq!(stale.body, r#"{"error":"recent authentication required"}"#); for method in [Method::PATCH, Method::DELETE] { let r = h .mutate( &cookie, method, users, serde_json::json!({"id": "x", "role": "analyst"}), ) .await; assert_eq!(r.status, StatusCode::FORBIDDEN); } // `token_from` reauthenticates this same session. let token = h.token_from(&cookie, Scope::Admin); for (method, body) in [ (Method::POST, new_user.clone()), ( Method::PATCH, serde_json::json!({"id": "x", "role": "analyst"}), ), (Method::DELETE, serde_json::json!({"id": "x"})), ] { let r = send( &h.app, request(method.clone(), users) .header(header::AUTHORIZATION, format!("Bearer {token}")) .header(header::CONTENT_TYPE, "application/json") .body(Body::from(body.to_string())) .unwrap(), ) .await; assert_eq!(r.status, StatusCode::FORBIDDEN, "{method}"); } assert!(h .auth .list_users() .unwrap() .iter() .all(|u| u.username != "bob")); // Reads stay open to an admin token. let read = send( &h.app, request(Method::GET, users) .header(header::AUTHORIZATION, format!("Bearer {token}")) .body(Body::empty()) .unwrap(), ) .await; assert_eq!(read.status, StatusCode::OK); let made = h.mutate(&cookie, Method::POST, users, new_user).await; assert_eq!(made.status, StatusCode::OK, "{}", made.body); let id = made.json()["id"].as_str().unwrap().to_string(); let role = h .mutate( &cookie, Method::PATCH, users, serde_json::json!({"id": id, "role": "analyst"}), ) .await; assert_eq!(role.status, StatusCode::OK, "{}", role.body); let gone = h .mutate( &cookie, Method::DELETE, users, serde_json::json!({"id": id}), ) .await; assert_eq!(gone.status, StatusCode::OK, "{}", gone.body); } #[tokio::test] async fn analyze_failure_has_a_fixed_message() { let h = harness(Transport::Local); let cookie = h.admin_cookie().await; let r = h .mutate( &cookie, Method::POST, "/api/analyze", serde_json::json!({"path": "/nao/existe"}), ) .await; assert_eq!(r.status, StatusCode::BAD_REQUEST); assert_eq!(r.body, r#"{"error":"analysis failed"}"#); } #[test] fn secret_key_file_comes_from_the_environment() { let with = |value: Option<&'static str>| { secret_key_file(&move |name| { assert_eq!(name, "ACAUA_SECRET_KEY_FILE"); value.map(String::from) }) }; assert_eq!(with(None), None); assert_eq!(with(Some(" ")), None); assert_eq!( with(Some("/run/secrets/acaua_key")), Some(PathBuf::from("/run/secrets/acaua_key")) ); } #[tokio::test] async fn every_response_carries_the_security_headers() { let h = harness(Transport::Local); for path in ["/login.html", "/api/health", "/api/alerts", "/nope"] { let r = send(&h.app, empty(Method::GET, path)).await; let get = |name: header::HeaderName| r.headers.get(name).unwrap().to_str().unwrap(); let csp = get(header::CONTENT_SECURITY_POLICY); assert!(csp.contains("frame-ancestors 'none'"), "{path}"); assert!(csp.contains("script-src 'self'"), "{path}"); assert!(!csp.contains("script-src 'self' 'unsafe"), "{path}"); assert_eq!(get(header::X_FRAME_OPTIONS), "DENY", "{path}"); assert_eq!(get(header::X_CONTENT_TYPE_OPTIONS), "nosniff", "{path}"); assert_eq!(get(header::REFERRER_POLICY), "no-referrer", "{path}"); } } #[tokio::test] async fn auth_state_tells_whether_mfa_is_on() { let h = harness(Transport::Local); let anon = send(&h.app, empty(Method::GET, "/api/auth/state")).await; assert!(anon.json().get("mfa_enabled").is_none()); let state = |c: &str| { request(Method::GET, "/api/auth/state") .header(header::COOKIE, c) .body(Body::empty()) .unwrap() }; let cookie = h.analyst_cookie().await; let off = send(&h.app, state(&cookie)).await; assert_eq!(off.json()["mfa_enabled"], serde_json::json!(false)); let cookie = h.admin_cookie().await; let on = send(&h.app, state(&cookie)).await; assert_eq!(on.json()["mfa_enabled"], serde_json::json!(true)); } async fn login_from(app: &Router, peer: IpAddr, user: &str, pw: &str) -> Reply { let mut r = post_json( "/api/auth/login", serde_json::json!({"username": user, "password": pw}), ); r.extensions_mut() .insert(axum::extract::ConnectInfo(SocketAddr::new(peer, 4000))); send(app, r).await } fn v4_peer(i: u32) -> IpAddr { IpAddr::V4(std::net::Ipv4Addr::from(0x0a00_0000 + i)) } fn spend_budget(auth: &AuthService, user: &str, n: u32, t: u64) { for i in 0..n { let attempt = auth.login_begin(user, v4_peer(i), t).unwrap(); let _ = auth.login_failed(attempt, t); } } #[tokio::test] async fn a_refused_login_takes_no_hashing_permit() { let (_d, auth, state, app) = fresh_with_state(Transport::Local); let code = auth.ensure_bootstrap(now()).unwrap().unwrap(); auth.complete_bootstrap(&code, "root", PW, peer(), now()) .unwrap(); auth.create_user("root", "ana", PW, Role::Analyst, now()) .unwrap(); spend_budget(&auth, "ana", 100, now()); let held = state .argon2 .clone() .acquire_many_owned(crate::auth_http::ARGON2_CONCURRENCY as u32) .await .unwrap(); let refused = tokio::time::timeout( std::time::Duration::from_secs(5), login_from(&app, v4_peer(500), "ana", PW), ) .await .expect("a refusal must not wait for a permit"); assert_eq!(refused.status, StatusCode::TOO_MANY_REQUESTS); assert!(refused.headers.contains_key(header::RETRY_AFTER)); // An attempt that can still succeed does wait for one. let waits = tokio::time::timeout( std::time::Duration::from_millis(300), login_from(&app, v4_peer(501), "root", PW), ) .await; assert!(waits.is_err()); drop(held); // That cancelled attempt gave back what it held. assert_eq!( login_from(&app, v4_peer(501), "root", PW).await.status, StatusCode::OK ); } #[tokio::test] async fn parallel_requests_stop_at_the_cap() { let (_d, auth, _state, app) = fresh_with_state(Transport::Local); let code = auth.ensure_bootstrap(now()).unwrap().unwrap(); auth.complete_bootstrap(&code, "root", PW, peer(), now()) .unwrap(); auth.create_user("root", "ana", PW, Role::Analyst, now()) .unwrap(); spend_budget(&auth, "ana", 96, now()); let mut tasks = Vec::new(); for i in 0..16 { let app = app.clone(); tasks.push(tokio::spawn(async move { login_from(&app, v4_peer(1000 + i), "ana", PW2).await.status })); } let mut wrong = 0; let mut refused = 0; for t in tasks { match t.await.unwrap() { StatusCode::UNAUTHORIZED => wrong += 1, StatusCode::TOO_MANY_REQUESTS => refused += 1, other => panic!("{other}"), } } assert_eq!((wrong, refused), (4, 12)); }