diff --git a/src/domain/user.rs b/src/domain/user.rs index 1e05c23..1049905 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -57,6 +57,21 @@ impl Username { } } +/// Bounds how many argon2 hashes run at once. `spawn_blocking` is unbounded — +/// tokio grows the blocking pool to 512 threads — and argon2's default `m_cost` +/// is 19 MiB, so an un-capped login flood claims gigabytes (measured: ~17 MB +/// per in-flight hash) and gets the whole process OOM-killed. A permit turns +/// that into queueing: latency instead of memory. `nproc * 2` keeps every core +/// busy while a hash waits on memory bandwidth, with a floor of 2 permits so a +/// single-core box still makes progress. +fn argon2_permits() -> &'static tokio::sync::Semaphore { + static PERMITS: OnceLock = OnceLock::new(); + PERMITS.get_or_init(|| { + let cores = std::thread::available_parallelism().map_or(2, |n| n.get()); + tokio::sync::Semaphore::new(cores * 2) + }) +} + /// A validated plaintext password. Never stored — only hashed or verified. pub struct Password(String); @@ -85,6 +100,10 @@ impl Password { /// and they come back as 503. Every request path must use this, not `hash`. pub async fn hash_async(&self) -> Result { let plain = self.0.clone(); + let _permit = argon2_permits() + .acquire() + .await + .map_err(|e| AppError::Internal(format!("hash permit: {e}")))?; tokio::task::spawn_blocking(move || Password(plain).hash()) .await .map_err(|e| AppError::Internal(format!("hash task: {e}")))? @@ -130,6 +149,12 @@ impl PasswordHash { pub async fn verify_async(&self, password: &Password) -> bool { let hash = self.0.clone(); let plain = password.0.clone(); + // A closed semaphore can't happen (it is `'static` and never closed), but + // if it ever did this must fail like a pool panic does — 401, never a + // status an attacker could tell apart from the unknown-user branch. + let Ok(_permit) = argon2_permits().acquire().await else { + return false; + }; tokio::task::spawn_blocking(move || PasswordHash(hash).verify(&Password(plain))) .await .unwrap_or(false) @@ -142,8 +167,25 @@ impl PasswordHash { /// reply would let an attacker enumerate valid usernames by timing. pub async fn verify_decoy_async(password: &Password) { let plain = password.0.clone(); + // Same permit as the real check, so both login branches queue alike. + let Ok(_permit) = argon2_permits().acquire().await else { + return; + }; let _ = tokio::task::spawn_blocking(move || decoy_hash().verify(&Password(plain))).await; } + + /// Compute the decoy hash at startup, off the async runtime. Without this the + /// process's first unknown-username login pays hash + verify while a + /// wrong-password login pays only verify — a one-shot timing tell. The + /// `OnceLock` still initialises inside a blocking context, just earlier, and + /// the task is detached so boot never waits on it. + pub fn prewarm_decoy() { + // No permit: one hash at boot, and taking one here could only delay the + // seed's own hash. + tokio::task::spawn_blocking(|| { + decoy_hash(); + }); + } } #[derive(Debug, Clone, SurrealValue)] diff --git a/src/main.rs b/src/main.rs index 573487d..883b014 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,6 +18,9 @@ async fn main() -> anyhow::Result<()> { let cfg = Config::from_env(); let db = database::init(&cfg).await?; + // Hash the login decoy now, so the first unknown-username login is not the + // one request that pays for it (see `PasswordHash::prewarm_decoy`). + hezarfen_backend::domain::user::PasswordHash::prewarm_decoy(); seed_admin(&cfg, &db).await?; let db_up = DbHealth::default(); keepalive(db.clone(), db_up.clone()); diff --git a/src/web/auth.rs b/src/web/auth.rs index 04eb3c7..0c4ad10 100644 --- a/src/web/auth.rs +++ b/src/web/auth.rs @@ -10,8 +10,9 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS}; +use crate::domain::role::Role; use crate::domain::session::Session; -use crate::domain::user::{Password, PasswordHash, User, Username}; +use crate::domain::user::{Password, PasswordHash, User, UserId, Username}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::rate_limit::{RateLimitConfig, RateLimiter}; use crate::state::AppState; @@ -45,15 +46,21 @@ struct Credentials { } /// Register a new user account. +/// +/// Answers `201` whether or not the username was free: a distinguishable +/// "already taken" reply lets anyone unauthenticated enumerate every account in +/// the school, which would make the constant-cost decoy on the login path +/// pointless. A taken username is *not* re-created or overwritten — only the +/// reply is uniform. The UX cost (a typo-collision looks like success until the +/// user tries to log in) is deliberate. #[utoipa::path( post, path = "/register", tag = "auth", request_body = Credentials, responses( - (status = 201, description = "Account created", body = UserResponse), + (status = 201, description = "Account created, or the username was already taken — deliberately indistinguishable", body = UserResponse), (status = 400, description = "Invalid username or password", body = ErrorResponse), - (status = 409, description = "Username already taken", body = ErrorResponse), (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), ), )] @@ -72,9 +79,38 @@ async fn register( } .into()); } + // Hash BEFORE the availability check inside `User::create`, never after: the + // ~33ms of argon2 is what makes both outcomes cost the same, so a taken + // username can't be spotted by a fast reply. The only work the taken path + // skips is the insert itself, orders of magnitude below hashing. let password_hash = Password::try_new(&req.password)?.hash_async().await?; - let user = User::create(username, password_hash, &st.db).await?; - Ok((StatusCode::CREATED, Json(UserResponse::new(&user)))) + match User::create(username.clone(), password_hash, &st.db).await { + Ok(user) => Ok((StatusCode::CREATED, Json(UserResponse::new(&user)))), + // Taken. Log the real reason server-side and hand back a response shaped + // exactly like a fresh registration's — same status, same fields. The id + // is a throwaway that matches no row; nothing unauthenticated can + // resolve it, and telling the two apart is the whole thing we're denying. + Err(AppError::Conflict(_)) => { + tracing::info!("register: username already taken, answering 201"); + Ok(( + StatusCode::CREATED, + Json(UserResponse { + id: UserId::generate().key().to_string(), + username: username.as_str().to_string(), + // Every fresh account starts as a student (`User::create`). + role: Role::Student.into(), + name: None, + surname: None, + email: None, + phone: None, + birth_date: None, + theme: None, + language: None, + }), + )) + } + Err(err) => Err(err), + } } /// Log in with username + password. Sets a `session` cookie on success. diff --git a/tests/auth_enumeration.rs b/tests/auth_enumeration.rs new file mode 100644 index 0000000..1d1496f --- /dev/null +++ b/tests/auth_enumeration.rs @@ -0,0 +1,109 @@ +//! `POST /auth/register` must not tell an unauthenticated caller whether a +//! username exists — not by status, not by body, not by how long it takes. + +mod common; + +use std::time::Instant; + +use axum::http::StatusCode; +use common::{app_and_db, items, send, set_role}; +use serde_json::json; + +#[tokio::test] +async fn duplicate_register_is_indistinguishable_from_a_fresh_one() { + let (app, db) = app_and_db().await; + let taken = json!({ "username": "ada", "password": "secret1" }); + + let first = send(&app, "POST", "/auth/register", None, Some(taken.clone())).await; + assert_eq!(first.status, StatusCode::CREATED); + + // Same username again, different password: still 201, same body shape. + let dup_creds = json!({ "username": "ada", "password": "attacker" }); + let started = Instant::now(); + let dup = send( + &app, + "POST", + "/auth/register", + None, + Some(dup_creds.clone()), + ) + .await; + let dup_elapsed = started.elapsed(); + + let fresh = send( + &app, + "POST", + "/auth/register", + None, + Some(json!({ "username": "grace", "password": "secret1" })), + ) + .await; + + assert_eq!(dup.status, fresh.status, "status leaks existence"); + assert_eq!(dup.status, StatusCode::CREATED); + + // Structurally identical: same keys, and every value either the echoed + // username or the same default. Only `id` may differ (it is a ULID). + let dup_obj = dup.body.as_object().expect("dup body object"); + let fresh_obj = fresh.body.as_object().expect("fresh body object"); + assert_eq!( + dup_obj.keys().collect::>(), + fresh_obj.keys().collect::>(), + "field set leaks existence" + ); + for (key, value) in dup_obj { + if key == "id" || key == "username" { + continue; + } + assert_eq!(value, &fresh_obj[key], "field {key} leaks existence"); + } + assert_eq!(dup_obj["username"], "ada"); + assert_eq!(dup_obj["role"], "student"); + assert_eq!( + dup_obj["id"].as_str().map(str::len), + fresh_obj["id"].as_str().map(str::len), + "id shape leaks existence" + ); + assert!(dup.cookie.is_none() && fresh.cookie.is_none()); + + // The argon2 work is what equalises timing, so pin that the taken path pays + // it. A floor, not a comparison between the two paths — a gap assertion + // would be flaky, whereas this can only fail if hashing got skipped + // (argon2's default cost is ~33ms; 8ms leaves room for a loaded CI box). + assert!( + dup_elapsed.as_millis() >= 8, + "taken-username register returned in {dup_elapsed:?} — it skipped argon2, \ + which re-opens the timing oracle" + ); + + // The original account is untouched: its password still works and the + // attacker's does not. + let login = send(&app, "POST", "/auth/login", None, Some(taken)).await; + assert_eq!( + login.status, + StatusCode::OK, + "original password stopped working" + ); + let hijack = send(&app, "POST", "/auth/login", None, Some(dup_creds)).await; + assert_eq!( + hijack.status, + StatusCode::UNAUTHORIZED, + "the duplicate register overwrote the password" + ); + + // And no second row was written: exactly two users exist (ada, grace). + set_role(&db, "ada", "admin").await; + let cookie = login.cookie.expect("session cookie"); + let list = send(&app, "GET", "/users", Some(&cookie), None).await; + assert_eq!(list.status, StatusCode::OK); + let names: Vec<&str> = items(&list.body) + .iter() + .map(|u| u["username"].as_str().expect("username")) + .collect(); + assert_eq!( + names.iter().filter(|n| **n == "ada").count(), + 1, + "duplicate register created a second row: {names:?}" + ); + assert_eq!(names.len(), 2, "unexpected user rows: {names:?}"); +} diff --git a/tests/integration.rs b/tests/integration.rs index 373b4c1..dda66b4 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -110,9 +110,25 @@ async fn register_validates_input() { 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); + // A duplicate answers 201 like any other register (the "taken" reply is + // deliberately indistinguishable — see tests/auth_enumeration.rs), but the + // write is still rejected: the original password keeps working and the + // second one never becomes valid. + let dup = json!({ "username": "bob", "password": "hijack1" }); + let res = send(&app, "POST", "/auth/register", None, Some(dup.clone())).await; + assert_eq!(res.status, StatusCode::CREATED); + let res = send(&app, "POST", "/auth/login", None, Some(ok)).await; + assert_eq!( + res.status, + StatusCode::OK, + "original password stopped working" + ); + let res = send(&app, "POST", "/auth/login", None, Some(dup)).await; + assert_eq!( + res.status, + StatusCode::UNAUTHORIZED, + "the duplicate register overwrote the account" + ); } #[tokio::test] @@ -4773,7 +4789,7 @@ async fn expired_session_is_unauthorized_before_any_purge() { /// (trimmed) at construction and at login lookup. #[tokio::test] async fn padded_usernames_are_canonicalized_not_distinct_accounts() { - let app = mem_app().await; + let (app, db) = app_and_db().await; let res = send( &app, @@ -4785,20 +4801,66 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { .await; assert_eq!(res.status, StatusCode::CREATED); - // Padding must not mint a lookalike account. + // Padding must not mint a lookalike account. Register answers 201 either way + // (username enumeration is denied, see tests/auth_enumeration.rs), so the + // collision is observed through the account itself: each spoof asks for a + // different password, and none of them may take effect. for spoof in ["ali ", " ali", " ali "] { let res = send( &app, "POST", "/auth/register", None, - Some(json!({ "username": spoof, "password": "secret1" })), + Some(json!({ "username": spoof, "password": "spoof1" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{spoof:?}"); + } + + // One row, not four — the padded forms collided with the canonical name. + let rows: Vec = db + .query("SELECT * FROM user WHERE username = 'ali'") + .await + .unwrap() + .check() + .unwrap() + .take(0) + .unwrap(); + assert_eq!(rows.len(), 1, "padding minted a lookalike account"); + let all: Vec = db + .query("SELECT * FROM user") + .await + .unwrap() + .check() + .unwrap() + .take(0) + .unwrap(); + assert_eq!(all.len(), 1, "unexpected extra user rows"); + + // That one account still belongs to the first registration, and every + // spelling of the name resolves to it. + for attempt in ["ali", "ali ", " ali", " ali "] { + let res = send( + &app, + "POST", + "/auth/login", + None, + Some(json!({ "username": attempt, "password": "secret1" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "login as {attempt:?}"); + let res = send( + &app, + "POST", + "/auth/login", + None, + Some(json!({ "username": attempt, "password": "spoof1" })), ) .await; assert_eq!( res.status, - StatusCode::CONFLICT, - "{spoof:?} must collide with \"ali\"" + StatusCode::UNAUTHORIZED, + "a padded register overwrote \"ali\" (as {attempt:?})" ); } @@ -5099,8 +5161,9 @@ async fn promotion_via_role_endpoint_sweeps_enrollments() { /// 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. +/// answer the same uniform 201 as the winner (the "taken" reply is deliberately +/// indistinguishable), exactly one account may exist afterwards, and the +/// winner's password must be the one that works. #[tokio::test] async fn concurrent_duplicate_registrations_conflict_not_500() { let (app, db) = app_and_db().await; @@ -5121,15 +5184,14 @@ async fn concurrent_duplicate_registrations_conflict_not_500() { })); } - 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"), - } + let status = h.await.unwrap(); + assert_eq!( + status, + StatusCode::CREATED, + "a lost race must answer 201 like the winner, not a 500" + ); } - assert_eq!(created, 1, "exactly one registration wins"); // Exactly one row exists for the name. let users: Vec = db @@ -5145,6 +5207,40 @@ async fn concurrent_duplicate_registrations_conflict_not_500() { 1, "exactly one user row for the duplicated name" ); + + // And the winner's credentials survived the pile-up: a further duplicate + // asking for a different password does not replace them. + let res = send( + &app, + "POST", + "/auth/register", + None, + Some(json!({ "username": "dup", "password": "hijack1" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + let res = send( + &app, + "POST", + "/auth/login", + None, + Some(json!({ "username": "dup", "password": "secret1" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "the winning password broke"); + let res = send( + &app, + "POST", + "/auth/login", + None, + Some(json!({ "username": "dup", "password": "hijack1" })), + ) + .await; + assert_eq!( + res.status, + StatusCode::UNAUTHORIZED, + "a duplicate register overwrote the account" + ); } /// Regression: listing a child collection of a missing parent used to return an