//! Password hashing with argon2id, and the password policy. //! //! Hashes are PHC strings with a random salt. Hashing and verifying take hundreds of milliseconds //! by design, so the async wrappers move that work onto the blocking thread pool; a request task //! must never run argon2 inline. use argon2::Argon2; use argon2::password_hash::phc::PasswordHash; use argon2::password_hash::{PasswordHasher, PasswordVerifier}; use tokio::sync::{Semaphore, SemaphorePermit}; use crate::error::{Error, Result}; /// Shortest accepted password, in characters. Length is the main defence against guessing, so it /// is set well above what people choose by habit. pub const MIN_PASSWORD_CHARS: usize = 10; /// Longest accepted password, in characters. Bounds the work an attacker can force argon2 to do /// per request. pub const MAX_PASSWORD_CHARS: usize = 256; /// Most argon2 operations running at once. Each one takes tens of megabytes, so a burst of requests /// queues here instead of starting one blocking thread and one hash per request. const HASH_PERMITS: usize = 4; /// The gate of every async hash and verify. static HASHING: Semaphore = Semaphore::const_new(HASH_PERMITS); /// True for a password longer than [`MAX_PASSWORD_CHARS`]. Such a password is never hashed or verified. fn too_long(pw: &str) -> bool { pw.chars().count() > MAX_PASSWORD_CHARS } /// Shortest word of the name or email local part that a password may not contain, in characters. /// Shorter words are too common to forbid: a two-letter word would reject many good passwords. pub const MIN_FORBIDDEN_WORD_CHARS: usize = 4; /// Hashes `pw` with argon2id (default parameters) and a fresh random salt. Returns a PHC string. A /// password over [`MAX_PASSWORD_CHARS`] is refused before any hashing. pub fn hash_password(pw: &str) -> Result { if too_long(pw) { return Err(Error::Invalid("the password is too long".into())); } Argon2::default() .hash_password(pw.as_bytes()) .map(|h| h.to_string()) .map_err(|e| Error::Crypto(format!("argon2: {e}"))) } /// Returns true only if `pw` matches the PHC string `hash`. A malformed hash gives false, never /// a panic. A password over [`MAX_PASSWORD_CHARS`] gives false without any hashing. pub fn verify_password(pw: &str, hash: &str) -> bool { if too_long(pw) { return false; } let Ok(parsed) = PasswordHash::new(hash) else { return false; }; Argon2::default() .verify_password(pw.as_bytes(), &parsed) .is_ok() } /// Takes one of the [`HASH_PERMITS`] slots. Held until the blocking work ends. async fn gate() -> Result> { HASHING .acquire() .await .map_err(|e| Error::Crypto(format!("hashing gate closed: {e}"))) } /// [`hash_password`] on the blocking thread pool, behind the hashing gate. pub async fn hash_password_async(pw: String) -> Result { let _permit = gate().await?; tokio::task::spawn_blocking(move || hash_password(&pw)) .await .map_err(|e| Error::Crypto(format!("hashing task failed: {e}")))? } /// [`verify_password`] on the blocking thread pool, behind the hashing gate. An over-long password is /// answered without taking a slot. pub async fn verify_password_async(pw: String, hash: String) -> Result { if too_long(&pw) { return Ok(false); } let _permit = gate().await?; tokio::task::spawn_blocking(move || verify_password(&pw, &hash)) .await .map_err(|e| Error::Crypto(format!("verify task failed: {e}"))) } /// Why a new password is refused by [`check_policy`]. The web layer maps each reason to a /// translated message, so the reasons are kept apart from any text. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PolicyViolation { /// Fewer than [`MIN_PASSWORD_CHARS`] characters. TooShort, /// More than [`MAX_PASSWORD_CHARS`] characters. TooLong, /// Contains the email local part or a word of the name. ContainsIdentity, } /// Checks a new password against the policy. /// /// Rules: 10 to 256 characters; it must not contain the email local part (when that is at least /// [`MIN_FORBIDDEN_WORD_CHARS`] long) or any word of the name that is at least that long, compared /// case-insensitively. The rule that the password differs from the current one needs the stored /// hash and is checked by the caller. pub fn check_policy( password: &str, email: &str, name: &str, ) -> std::result::Result<(), PolicyViolation> { let chars = password.chars().count(); if chars < MIN_PASSWORD_CHARS { return Err(PolicyViolation::TooShort); } if chars > MAX_PASSWORD_CHARS { return Err(PolicyViolation::TooLong); } let lowered = password.to_lowercase(); let local_part = email.split('@').next().unwrap_or_default(); let forbidden = std::iter::once(local_part) .chain(name.split(|c: char| !c.is_alphanumeric())) .map(str::to_lowercase) .filter(|word| word.chars().count() >= MIN_FORBIDDEN_WORD_CHARS); for word in forbidden { if lowered.contains(&word) { return Err(PolicyViolation::ContainsIdentity); } } Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn hash_then_verify_accepts_only_the_same_password() { let hash = hash_password("correct horse").unwrap(); assert!(hash.starts_with("$argon2id$")); assert!(verify_password("correct horse", &hash)); assert!(!verify_password("wrong", &hash)); assert!(!verify_password("pw", "not a phc string")); } #[test] fn policy_enforces_length_bounds() { assert!(check_policy("short", "a@example.com", "Ada").is_err()); assert!(check_policy("nine-char", "a@example.com", "Ada").is_err()); assert!(check_policy("ten-chars!", "a@example.com", "Ada").is_ok()); let long = "x".repeat(MAX_PASSWORD_CHARS + 1); assert!(check_policy(&long, "a@example.com", "Ada").is_err()); } #[test] fn policy_rejects_email_local_part_and_name_words_case_insensitively() { let email = "tahinli@example.com"; assert!(check_policy("My-TAHINLI-pass", email, "Ada").is_err()); assert!(check_policy("correct Lovelace horse", email, "Ada Lovelace").is_err()); // Words under four characters do not count, so "Ada" alone does not block a password. assert!(check_policy("my ada horse 1", email, "Ada").is_ok()); } }