rainier-auth 1.0.0

Authentication guards, user providers, password hashing and authorization gates for Rainier.
Documentation
//! Password hashing — the [`Hasher`] port and its Argon2 implementation.

use argon2::{Algorithm, Argon2, Params, Version};
use password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
use rainier_support::{Error, Result};
use rand::rngs::OsRng;

/// Hashes and verifies passwords.
///
/// A port rather than a concrete choice, because the right algorithm changes
/// over time and an application that has to migrate should be able to run two
/// hashers side by side while it does.
pub trait Hasher: Send + Sync + 'static {
    /// Hash `plain`, returning an encoded hash that carries its own parameters
    /// and salt.
    fn hash(&self, plain: &str) -> Result<String>;

    /// Whether `plain` matches `hashed`.
    ///
    /// Returns `false` rather than an error for a malformed hash: to a caller
    /// deciding whether to let someone in, "this stored hash is corrupt" and
    /// "the password is wrong" must lead to the same outcome.
    fn verify(&self, plain: &str, hashed: &str) -> bool;

    /// Whether `hashed` was produced with weaker parameters than this hasher
    /// uses now, and should be re-hashed on the next successful login.
    fn needs_rehash(&self, hashed: &str) -> bool {
        let _ = hashed;
        false
    }
}

/// Argon2id, the current recommendation for password storage.
#[derive(Debug, Clone)]
pub struct Argon2Hasher {
    memory_kib: u32,
    iterations: u32,
    parallelism: u32,
}

impl Default for Argon2Hasher {
    fn default() -> Self {
        // OWASP's baseline: 19 MiB, 2 iterations, 1 lane. Comfortably above
        // the point where GPU cracking stops being cheap, and still fast
        // enough to run on every login.
        Self { memory_kib: 19 * 1024, iterations: 2, parallelism: 1 }
    }
}

impl Argon2Hasher {
    /// Argon2id with the default parameters.
    pub fn new() -> Self {
        Self::default()
    }

    /// Argon2id with explicit cost parameters.
    pub fn with_params(memory_kib: u32, iterations: u32, parallelism: u32) -> Self {
        Self { memory_kib, iterations, parallelism }
    }

    /// Deliberately weak parameters, for tests.
    ///
    /// Hashing at production cost turns a test suite that logs in a few dozen
    /// times into a slow one. Never use this outside tests — the whole point
    /// of the real parameters is that they are expensive.
    pub fn insecure_for_tests() -> Self {
        Self { memory_kib: 8, iterations: 1, parallelism: 1 }
    }

    fn argon2(&self) -> Result<Argon2<'static>> {
        let params = Params::new(self.memory_kib, self.iterations, self.parallelism, None)
            .map_err(|e| Error::internal(format!("invalid Argon2 parameters: {e}")))?;
        Ok(Argon2::new(Algorithm::Argon2id, Version::V0x13, params))
    }
}

impl Hasher for Argon2Hasher {
    fn hash(&self, plain: &str) -> Result<String> {
        let salt = SaltString::generate(&mut OsRng);
        let hash = self
            .argon2()?
            .hash_password(plain.as_bytes(), &salt)
            .map_err(|e| Error::internal(format!("could not hash the password: {e}")))?;
        Ok(hash.to_string())
    }

    fn verify(&self, plain: &str, hashed: &str) -> bool {
        // The parsed hash carries its own parameters, so a password hashed
        // with older settings still verifies — see `needs_rehash`.
        let Ok(parsed) = PasswordHash::new(hashed) else {
            return false;
        };
        Argon2::default().verify_password(plain.as_bytes(), &parsed).is_ok()
    }

    fn needs_rehash(&self, hashed: &str) -> bool {
        let Ok(parsed) = PasswordHash::new(hashed) else {
            // Unparseable: it certainly is not in the current format.
            return true;
        };
        let Ok(params) = Params::try_from(&parsed) else {
            return true;
        };
        params.m_cost() < self.memory_kib
            || params.t_cost() < self.iterations
            || params.p_cost() < self.parallelism
    }
}

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

    fn hasher() -> Argon2Hasher {
        Argon2Hasher::insecure_for_tests()
    }

    #[test]
    fn a_password_verifies_against_its_own_hash() {
        let hasher = hasher();
        let hashed = hasher.hash("correct horse").unwrap();
        assert!(hasher.verify("correct horse", &hashed));
    }

    #[test]
    fn a_wrong_password_does_not_verify() {
        let hasher = hasher();
        let hashed = hasher.hash("correct horse").unwrap();
        assert!(!hasher.verify("wrong horse", &hashed));
        assert!(!hasher.verify("", &hashed));
        assert!(!hasher.verify("Correct Horse", &hashed), "hashing is case-sensitive");
    }

    #[test]
    fn the_same_password_hashes_differently_each_time() {
        // A per-hash salt is what stops identical passwords being visibly
        // identical in the database.
        let hasher = hasher();
        assert_ne!(hasher.hash("same").unwrap(), hasher.hash("same").unwrap());
    }

    #[test]
    fn a_hash_carries_its_algorithm_and_parameters() {
        let hashed = hasher().hash("x").unwrap();
        assert!(hashed.starts_with("$argon2id$"), "{hashed}");
    }

    #[test]
    fn a_corrupt_hash_fails_closed_rather_than_erroring() {
        // A caller deciding whether to let someone in must not be able to
        // confuse "corrupt hash" with "correct password".
        let hasher = hasher();
        assert!(!hasher.verify("anything", "not-a-hash"));
        assert!(!hasher.verify("anything", ""));
        assert!(!hasher.verify("anything", "$argon2id$broken"));
    }

    #[test]
    fn a_hash_from_weaker_parameters_is_flagged_for_rehashing() {
        let weak = Argon2Hasher::with_params(8, 1, 1);
        let strong = Argon2Hasher::with_params(64, 3, 1);

        let old = weak.hash("password").unwrap();
        assert!(strong.needs_rehash(&old), "stronger settings should ask for a rehash");
        assert!(!weak.needs_rehash(&old), "the same settings should not");

        // And it must still verify in the meantime, or every user would be
        // locked out the moment the parameters changed.
        assert!(strong.verify("password", &old));
    }

    #[test]
    fn an_unparseable_hash_needs_rehashing() {
        assert!(hasher().needs_rehash("plaintext-from-some-legacy-system"));
    }

    #[test]
    fn unicode_passwords_round_trip() {
        let hasher = hasher();
        let hashed = hasher.hash("pässwörd-🔒").unwrap();
        assert!(hasher.verify("pässwörd-🔒", &hashed));
        assert!(!hasher.verify("passwörd-🔒", &hashed));
    }
}