🔑 argon2 no longer starves the async runtime
Browse files at this commitcf042586d2e8bb3da2278d9a73e48a05de1f52d1Parent: 352b0b0- fix
- 🔑 argon2 no longer starves the async runtime
2 changed files +45 -13
- src/domain/user.rs +34 -9
- src/web/auth.rs +11 -4
src/domain/user.rsmodified+34 -9
| @@ -65,7 +65,9 @@ impl Password { | |||
| 65 | Ok(Self(value.to_string())) | 65 | Ok(Self(value.to_string())) |
| 66 | } | 66 | } |
| 67 | 67 | ||
| 68 | - pub fn hash(&self) -> Result<PasswordHash, AppError> { | 68 | + /// Private on purpose: argon2 must never run on an async worker. Callers |
| 69 | + /// outside this module go through [`Password::hash_async`]. | ||
| 70 | + fn hash(&self) -> Result<PasswordHash, AppError> { | ||
| 69 | let mut salt_bytes = [0u8; 16]; | 71 | let mut salt_bytes = [0u8; 16]; |
| 70 | getrandom::fill(&mut salt_bytes).map_err(|e| AppError::Internal(format!("rng: {e}")))?; | 72 | getrandom::fill(&mut salt_bytes).map_err(|e| AppError::Internal(format!("rng: {e}")))?; |
| 71 | let salt = SaltString::encode_b64(&salt_bytes) | 73 | let salt = SaltString::encode_b64(&salt_bytes) |
| @@ -75,6 +77,17 @@ impl Password { | |||
| 75 | .to_string(); | 77 | .to_string(); |
| 76 | Ok(PasswordHash(hash)) | 78 | Ok(PasswordHash(hash)) |
| 77 | } | 79 | } |
| 80 | + | ||
| 81 | + /// [`Password::hash`] moved onto the blocking pool. argon2 is deliberately | ||
| 82 | + /// CPU-expensive, so hashing on an async worker starves the runtime: under | ||
| 83 | + /// load a registration burst pushes requests past `REQUEST_TIMEOUT_SECS` | ||
| 84 | + /// and they come back as 503. Every request path must use this, not `hash`. | ||
| 85 | + pub async fn hash_async(&self) -> Result<PasswordHash, AppError> { | ||
| 86 | + let plain = self.0.clone(); | ||
| 87 | + tokio::task::spawn_blocking(move || Password(plain).hash()) | ||
| 88 | + .await | ||
| 89 | + .map_err(|e| AppError::Internal(format!("hash task: {e}")))? | ||
| 90 | + } | ||
| 78 | } | 91 | } |
| 79 | 92 | ||
| 80 | /// An argon2 PHC hash, safe to persist. | 93 | /// An argon2 PHC hash, safe to persist. |
| @@ -102,7 +115,8 @@ impl PasswordHash { | |||
| 102 | &self.0 | 115 | &self.0 |
| 103 | } | 116 | } |
| 104 | 117 | ||
| 105 | - pub fn verify(&self, password: &Password) -> bool { | 118 | + /// Private on purpose — see [`Password::hash`]. Use [`PasswordHash::verify_async`]. |
| 119 | + fn verify(&self, password: &Password) -> bool { | ||
| 106 | match argon2::password_hash::PasswordHash::new(&self.0) { | 120 | match argon2::password_hash::PasswordHash::new(&self.0) { |
| 107 | Ok(parsed) => Argon2::default() | 121 | Ok(parsed) => Argon2::default() |
| 108 | .verify_password(password.0.as_bytes(), &parsed) | 122 | .verify_password(password.0.as_bytes(), &parsed) |
| @@ -111,12 +125,23 @@ impl PasswordHash { | |||
| 111 | } | 125 | } |
| 112 | } | 126 | } |
| 113 | 127 | ||
| 114 | - /// Run a throwaway verification against the decoy hash. Login calls this when | 128 | + /// [`PasswordHash::verify`] on the blocking pool — see [`Password::hash_async`]. |
| 115 | - /// the username is unknown, so a missing user costs the same argon2 time as a | 129 | + pub async fn verify_async(&self, password: &Password) -> bool { |
| 116 | - /// real (wrong-password) check — otherwise the faster reply would let an | 130 | + let hash = self.0.clone(); |
| 117 | - /// attacker enumerate valid usernames by timing. | 131 | + let plain = password.0.clone(); |
| 118 | - pub fn verify_decoy(password: &Password) { | 132 | + tokio::task::spawn_blocking(move || PasswordHash(hash).verify(&Password(plain))) |
| 119 | - let _ = decoy_hash().verify(password); | 133 | + .await |
| 134 | + .unwrap_or(false) | ||
| 135 | + } | ||
| 136 | + | ||
| 137 | + /// Run a throwaway verification against the decoy hash, on the blocking pool | ||
| 138 | + /// (see [`Password::hash_async`]; the one-time decoy hash happens there too). | ||
| 139 | + /// Login calls this when the username is unknown, so a missing user costs the | ||
| 140 | + /// same argon2 time as a real (wrong-password) check — otherwise the faster | ||
| 141 | + /// reply would let an attacker enumerate valid usernames by timing. | ||
| 142 | + pub async fn verify_decoy_async(password: &Password) { | ||
| 143 | + let plain = password.0.clone(); | ||
| 144 | + let _ = tokio::task::spawn_blocking(move || decoy_hash().verify(&Password(plain))).await; | ||
| 120 | } | 145 | } |
| 121 | } | 146 | } |
| 122 | 147 | ||
| @@ -255,7 +280,7 @@ impl User { | |||
| 255 | Ok(()) | 280 | Ok(()) |
| 256 | } | 281 | } |
| 257 | None => { | 282 | None => { |
| 258 | - let created = Self::create(username, password.hash()?, db).await?; | 283 | + let created = Self::create(username, password.hash_async().await?, db).await?; |
| 259 | let admin = created.set_role(Role::Admin, db).await?; | 284 | let admin = created.set_role(Role::Admin, db).await?; |
| 260 | tracing::info!(username = admin.username.as_str(), "seeded admin account"); | 285 | tracing::info!(username = admin.username.as_str(), "seeded admin account"); |
| 261 | Ok(()) | 286 | Ok(()) |
src/web/auth.rsmodified+11 -4
| @@ -72,7 +72,7 @@ async fn register( | |||
| 72 | } | 72 | } |
| 73 | .into()); | 73 | .into()); |
| 74 | } | 74 | } |
| 75 | - let password_hash = Password::try_new(&req.password)?.hash()?; | 75 | + let password_hash = Password::try_new(&req.password)?.hash_async().await?; |
| 76 | let user = User::create(username, password_hash, &st.db).await?; | 76 | let user = User::create(username, password_hash, &st.db).await?; |
| 77 | Ok((StatusCode::CREATED, Json(UserResponse::new(&user)))) | 77 | Ok((StatusCode::CREATED, Json(UserResponse::new(&user)))) |
| 78 | } | 78 | } |
| @@ -98,13 +98,20 @@ async fn login( | |||
| 98 | // Usernames are stored trimmed (see `Username::try_new`); trim the lookup | 98 | // Usernames are stored trimmed (see `Username::try_new`); trim the lookup |
| 99 | // the same way so a padded login attempt matches the canonical name. | 99 | // the same way so a padded login attempt matches the canonical name. |
| 100 | let user = match User::find_by_username(req.username.trim(), &st.db).await? { | 100 | let user = match User::find_by_username(req.username.trim(), &st.db).await? { |
| 101 | - Some(user) if user.get_password_hash().verify(&password) => user, | 101 | + // Verification is `.await`ed so argon2 runs on the blocking pool instead |
| 102 | - Some(_) => return Err(AppError::Unauthorized), | 102 | + // of stalling an async worker; that rules out a match guard, which |
| 103 | + // cannot await. | ||
| 104 | + Some(user) => { | ||
| 105 | + if !user.get_password_hash().verify_async(&password).await { | ||
| 106 | + return Err(AppError::Unauthorized); | ||
| 107 | + } | ||
| 108 | + user | ||
| 109 | + } | ||
| 103 | None => { | 110 | None => { |
| 104 | // No such user. Still do the argon2 work against a decoy so the reply | 111 | // No such user. Still do the argon2 work against a decoy so the reply |
| 105 | // takes as long as a real (wrong-password) check — otherwise the | 112 | // takes as long as a real (wrong-password) check — otherwise the |
| 106 | // timing difference leaks which usernames exist. | 113 | // timing difference leaks which usernames exist. |
| 107 | - PasswordHash::verify_decoy(&password); | 114 | + PasswordHash::verify_decoy_async(&password).await; |
| 108 | return Err(AppError::Unauthorized); | 115 | return Err(AppError::Unauthorized); |
| 109 | } | 116 | } |
| 110 | }; | 117 | }; |