3.5 KiB · text History de2cabc
use anyhow::{Context, Result};
use argon2::password_hash::SaltString;
use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier};

/// Hash a password using Argon2 with a fresh random per-password salt.
///
/// The salt is 16 cryptographically-random bytes pulled from a v4 UUID (which
/// is itself sourced from the OS CSPRNG), so two identical passwords hash to
/// different values.
pub fn hash_password(password: &str) -> Result<String> {
    let salt_bytes = uuid::Uuid::new_v4().into_bytes();
    let salt = SaltString::encode_b64(&salt_bytes)
        .map_err(|e| anyhow::anyhow!("Failed to generate salt: {}", e))?;
    let argon2 = Argon2::default();
    let password_hash = argon2
        .hash_password(password.as_bytes(), &salt)
        .context("Failed to hash password")?;
    Ok(password_hash.to_string())
}

/// Generate a strong random password (24 characters from a 56-symbol
/// alphabet without look-alikes, ~139 bits) from the OS CSPRNG. Used by
/// `manage user create` when no password is supplied.
pub fn generate_password() -> String {
    use argon2::password_hash::rand_core::{OsRng, RngCore};
    const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";
    let mut out = String::with_capacity(24);
    while out.len() < 24 {
        let b = (OsRng.next_u32() & 0xff) as usize;
        // Rejection sampling keeps the distribution uniform.
        if b < ALPHABET.len() * (256 / ALPHABET.len()) {
            out.push(ALPHABET[b % ALPHABET.len()] as char);
        }
    }
    out
}

/// The `password_hash` of an account created through OIDC: it has no
/// password. Anything starting with `!` is unusable by construction (a PHC
/// string starts with `$`).
pub const NO_PASSWORD: &str = "!oidc";

/// `true` for a sentinel hash such as [`NO_PASSWORD`].
pub fn is_unusable_hash(hash: &str) -> bool {
    hash.starts_with('!')
}

/// Verify a password against its hash. Returns `Ok(false)` for a wrong
/// password or an unusable (`!`-sentinel) hash.
pub fn verify_password(password: &str, hash: &str) -> Result<bool> {
    if is_unusable_hash(hash) {
        return Ok(false);
    }
    let parsed_hash = PasswordHash::new(hash).context("Failed to parse password hash")?;
    let argon2 = Argon2::default();

    match argon2.verify_password(password.as_bytes(), &parsed_hash) {
        Ok(()) => Ok(true),
        Err(argon2::password_hash::Error::Password) => Ok(false),
        Err(e) => Err(anyhow::anyhow!("Password verification error: {}", e)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_password_hashing() {
        let password = "test_password_123";
        let hash = hash_password(password).expect("Failed to hash password");
        assert!(verify_password(password, &hash).unwrap());
        assert!(!verify_password("wrong_password", &hash).unwrap());
    }

    #[test]
    fn sentinel_hashes_never_verify() {
        assert!(!verify_password("", NO_PASSWORD).unwrap());
        assert!(!verify_password("!oidc", NO_PASSWORD).unwrap());
    }

    #[test]
    fn generated_passwords_are_long_and_distinct() {
        let a = generate_password();
        assert_eq!(a.len(), 24);
        assert!(a.chars().all(|c| c.is_ascii_alphanumeric()));
        assert_ne!(a, generate_password());
    }

    #[test]
    fn test_salt_is_random() {
        let a = hash_password("same").unwrap();
        let b = hash_password("same").unwrap();
        assert_ne!(a, b, "identical passwords must hash to different values");
    }
}