use argon2::{Algorithm, Argon2, Params, Version};
use password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
use rainier_support::{Error, Result};
use rand::rngs::OsRng;
pub trait Hasher: Send + Sync + 'static {
fn hash(&self, plain: &str) -> Result<String>;
fn verify(&self, plain: &str, hashed: &str) -> bool;
fn needs_rehash(&self, hashed: &str) -> bool {
let _ = hashed;
false
}
}
#[derive(Debug, Clone)]
pub struct Argon2Hasher {
memory_kib: u32,
iterations: u32,
parallelism: u32,
}
impl Default for Argon2Hasher {
fn default() -> Self {
Self { memory_kib: 19 * 1024, iterations: 2, parallelism: 1 }
}
}
impl Argon2Hasher {
pub fn new() -> Self {
Self::default()
}
pub fn with_params(memory_kib: u32, iterations: u32, parallelism: u32) -> Self {
Self { memory_kib, iterations, parallelism }
}
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 {
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 {
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() {
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() {
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");
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));
}
}