From cf042586d2e8bb3da2278d9a73e48a05de1f52d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 25 Jul 2026 07:35:38 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=94=91=20argon2=20no=20longer=20st?= =?UTF-8?q?arves=20the=20async=20runtime=20-=20hash=20and=20verify=20passw?= =?UTF-8?q?ords=20on=20`spawn=5Fblocking`;=20argon2=20is=20deliberately=20?= =?UTF-8?q?=20=20CPU-expensive,=20so=20running=20it=20on=20an=20async=20wo?= =?UTF-8?q?rker=20stalled=20the=20whole=20=20=20runtime=20and=20pushed=20r?= =?UTF-8?q?equests=20past=20`REQUEST=5FTIMEOUT=5FSECS`=20into=20a=20503=20?= =?UTF-8?q?-=20login=20verifies=20in=20the=20match=20arm=20instead=20of=20?= =?UTF-8?q?a=20match=20guard,=20since=20guards=20=20=20cannot=20await=20-?= =?UTF-8?q?=20the=20decoy=20verification=20that=20hides=20username=20enume?= =?UTF-8?q?ration=20moves=20off=20the=20=20=20runtime=20too,=20along=20wit?= =?UTF-8?q?h=20the=20one-time=20decoy=20hash=20-=20the=20seed's=20admin=20?= =?UTF-8?q?hash=20goes=20through=20the=20same=20path=20-=20make=20the=20bl?= =?UTF-8?q?ocking=20`hash`/`verify`/`verify=5Fdecoy`=20private=20so=20no?= =?UTF-8?q?=20request=20=20=20path=20can=20call=20them=20again=20by=20acci?= =?UTF-8?q?dent?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/domain/user.rs | 43 ++++++++++++++++++++++++++++++++++--------- src/web/auth.rs | 15 +++++++++++---- 2 files changed, 45 insertions(+), 13 deletions(-) diff --git a/src/domain/user.rs b/src/domain/user.rs index d37556a..a03b5f6 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -65,7 +65,9 @@ impl Password { Ok(Self(value.to_string())) } - pub fn hash(&self) -> Result { + /// Private on purpose: argon2 must never run on an async worker. Callers + /// outside this module go through [`Password::hash_async`]. + fn hash(&self) -> Result { let mut salt_bytes = [0u8; 16]; getrandom::fill(&mut salt_bytes).map_err(|e| AppError::Internal(format!("rng: {e}")))?; let salt = SaltString::encode_b64(&salt_bytes) @@ -75,6 +77,17 @@ impl Password { .to_string(); Ok(PasswordHash(hash)) } + + /// [`Password::hash`] moved onto the blocking pool. argon2 is deliberately + /// CPU-expensive, so hashing on an async worker starves the runtime: under + /// load a registration burst pushes requests past `REQUEST_TIMEOUT_SECS` + /// 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(); + tokio::task::spawn_blocking(move || Password(plain).hash()) + .await + .map_err(|e| AppError::Internal(format!("hash task: {e}")))? + } } /// An argon2 PHC hash, safe to persist. @@ -102,7 +115,8 @@ impl PasswordHash { &self.0 } - pub fn verify(&self, password: &Password) -> bool { + /// Private on purpose — see [`Password::hash`]. Use [`PasswordHash::verify_async`]. + fn verify(&self, password: &Password) -> bool { match argon2::password_hash::PasswordHash::new(&self.0) { Ok(parsed) => Argon2::default() .verify_password(password.0.as_bytes(), &parsed) @@ -111,12 +125,23 @@ impl PasswordHash { } } - /// Run a throwaway verification against the decoy hash. Login calls this when - /// the username is unknown, so a missing user costs the same argon2 time as a - /// real (wrong-password) check — otherwise the faster reply would let an - /// attacker enumerate valid usernames by timing. - pub fn verify_decoy(password: &Password) { - let _ = decoy_hash().verify(password); + /// [`PasswordHash::verify`] on the blocking pool — see [`Password::hash_async`]. + pub async fn verify_async(&self, password: &Password) -> bool { + let hash = self.0.clone(); + let plain = password.0.clone(); + tokio::task::spawn_blocking(move || PasswordHash(hash).verify(&Password(plain))) + .await + .unwrap_or(false) + } + + /// Run a throwaway verification against the decoy hash, on the blocking pool + /// (see [`Password::hash_async`]; the one-time decoy hash happens there too). + /// Login calls this when the username is unknown, so a missing user costs the + /// same argon2 time as a real (wrong-password) check — otherwise the faster + /// reply would let an attacker enumerate valid usernames by timing. + pub async fn verify_decoy_async(password: &Password) { + let plain = password.0.clone(); + let _ = tokio::task::spawn_blocking(move || decoy_hash().verify(&Password(plain))).await; } } @@ -255,7 +280,7 @@ impl User { Ok(()) } None => { - let created = Self::create(username, password.hash()?, db).await?; + let created = Self::create(username, password.hash_async().await?, db).await?; let admin = created.set_role(Role::Admin, db).await?; tracing::info!(username = admin.username.as_str(), "seeded admin account"); Ok(()) diff --git a/src/web/auth.rs b/src/web/auth.rs index 3d7b310..04eb3c7 100644 --- a/src/web/auth.rs +++ b/src/web/auth.rs @@ -72,7 +72,7 @@ async fn register( } .into()); } - let password_hash = Password::try_new(&req.password)?.hash()?; + 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)))) } @@ -98,13 +98,20 @@ async fn login( // Usernames are stored trimmed (see `Username::try_new`); trim the lookup // the same way so a padded login attempt matches the canonical name. let user = match User::find_by_username(req.username.trim(), &st.db).await? { - Some(user) if user.get_password_hash().verify(&password) => user, - Some(_) => return Err(AppError::Unauthorized), + // Verification is `.await`ed so argon2 runs on the blocking pool instead + // of stalling an async worker; that rules out a match guard, which + // cannot await. + Some(user) => { + if !user.get_password_hash().verify_async(&password).await { + return Err(AppError::Unauthorized); + } + user + } None => { // No such user. Still do the argon2 work against a decoy so the reply // takes as long as a real (wrong-password) check — otherwise the // timing difference leaks which usernames exist. - PasswordHash::verify_decoy(&password); + PasswordHash::verify_decoy_async(&password).await; return Err(AppError::Unauthorized); } };