Skip to main content

rustlavel_auth/
hashing.rs

1//! Password hashing with argon2id.
2//!
3//! `hash_password` produces a PHC string — `$argon2id$v=19$m=...,t=...,p=...$salt$hash` —
4//! which carries the algorithm, the version, the cost and the salt alongside
5//! the digest. That is what lets [`verify_password`] keep working after the
6//! cost is raised, and what lets [`needs_rehash`] notice that an old hash is
7//! now under-provisioned.
8
9use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
10use argon2::{Algorithm, Argon2, Params, Version};
11use rustlavel_core::{Error, Result};
12
13/// How much work one password hash costs.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct Cost {
16    /// Memory used per hash, in kibibytes.
17    pub memory_kib: u32,
18    /// Passes over that memory.
19    pub iterations: u32,
20    /// Lanes hashed in parallel.
21    pub parallelism: u32,
22}
23
24impl Cost {
25    /// The default: 19 MiB of memory, two passes, one lane.
26    ///
27    /// This is OWASP's first recommended argon2id configuration. Memory is the
28    /// parameter that actually defends against attackers: a GPU or ASIC can
29    /// pipeline iterations cheaply but has to buy 19 MiB of fast memory per
30    /// guess, which is what collapses their parallelism advantage. Two passes
31    /// is the minimum argon2id allows at this memory size, and one lane keeps
32    /// the cost predictable on a busy web server that is already running one
33    /// request per core.
34    ///
35    /// On a modern server this lands around 40 ms per hash — slow enough to
36    /// make offline cracking expensive, fast enough that a login request does
37    /// not feel it.
38    pub const DEFAULT: Cost = Cost { memory_kib: 19_456, iterations: 2, parallelism: 1 };
39
40    /// The cheapest configuration argon2 accepts.
41    ///
42    /// Deliberately far too weak for real passwords. It exists because a test
43    /// suite that hashes a dozen passwords at the real cost spends its whole
44    /// runtime inside argon2, and a slow suite is a suite that stops being run.
45    /// Never use this to store a password.
46    pub const FAST: Cost = Cost { memory_kib: 8, iterations: 1, parallelism: 1 };
47
48    fn params(self) -> Result<Params> {
49        Params::new(self.memory_kib, self.iterations, self.parallelism, None)
50            .map_err(|e| Error::msg(format!("invalid argon2 parameters: {e}")))
51    }
52}
53
54impl Default for Cost {
55    fn default() -> Self {
56        Cost::DEFAULT
57    }
58}
59
60/// Hash a password at the default cost.
61pub fn hash_password(password: &str) -> Result<String> {
62    hash_password_with(password, Cost::DEFAULT)
63}
64
65/// Hash a password at an explicit cost.
66///
67/// Every hash gets its own 16 bytes of salt from the OS CSPRNG, so two users
68/// who chose the same password still get different digests and a precomputed
69/// table buys an attacker nothing.
70pub fn hash_password_with(password: &str, cost: Cost) -> Result<String> {
71    let salt = SaltString::encode_b64(&crate::random::bytes(16))
72        .map_err(|e| Error::msg(format!("could not encode a password salt: {e}")))?;
73
74    let hasher = Argon2::new(Algorithm::Argon2id, Version::V0x13, cost.params()?);
75    let hash = hasher
76        .hash_password(password.as_bytes(), &salt)
77        .map_err(|e| Error::msg(format!("could not hash the password: {e}")))?;
78
79    Ok(hash.to_string())
80}
81
82/// Check a password against a stored hash.
83///
84/// Constant-time by construction: argon2 re-derives the digest using the
85/// parameters recorded in `hash` and compares the two with a branch-free
86/// equality check, so a wrong password takes the same time whether it differs
87/// in the first byte or the last. A malformed or unrecognised hash is simply
88/// `false` — an unparseable value in the database must never authenticate
89/// anybody.
90pub fn verify_password(password: &str, hash: &str) -> bool {
91    let Ok(parsed) = PasswordHash::new(hash) else {
92        return false;
93    };
94
95    Argon2::default().verify_password(password.as_bytes(), &parsed).is_ok()
96}
97
98/// Whether a stored hash was produced below the cost we now want.
99///
100/// Call it after a successful login: the plaintext password is in hand exactly
101/// once per session, which is the only moment an old hash can be upgraded.
102pub fn needs_rehash(hash: &str, cost: Cost) -> bool {
103    let Ok(parsed) = PasswordHash::new(hash) else {
104        // Unreadable, or hashed by some other algorithm entirely: rehash it.
105        return true;
106    };
107    if parsed.algorithm != Algorithm::Argon2id.ident() {
108        return true;
109    }
110
111    match Params::try_from(&parsed) {
112        Ok(params) => {
113            params.m_cost() < cost.memory_kib
114                || params.t_cost() < cost.iterations
115                || params.p_cost() != cost.parallelism
116        }
117        Err(_) => true,
118    }
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    #[test]
126    fn a_hashed_password_verifies_against_itself() {
127        let hash = hash_password_with("correct horse battery staple", Cost::FAST).unwrap();
128
129        assert!(verify_password("correct horse battery staple", &hash));
130    }
131
132    #[test]
133    fn the_wrong_password_is_rejected() {
134        let hash = hash_password_with("s3cret", Cost::FAST).unwrap();
135
136        assert!(!verify_password("s3cre", &hash));
137        assert!(!verify_password("s3cret ", &hash));
138        assert!(!verify_password("", &hash));
139        assert!(!verify_password("S3cret", &hash));
140    }
141
142    #[test]
143    fn the_same_password_hashes_differently_every_time() {
144        let first = hash_password_with("repeated", Cost::FAST).unwrap();
145        let second = hash_password_with("repeated", Cost::FAST).unwrap();
146
147        assert_ne!(first, second, "each hash must carry its own salt");
148        assert!(verify_password("repeated", &first));
149        assert!(verify_password("repeated", &second));
150    }
151
152    #[test]
153    fn hashes_are_phc_strings_naming_argon2id() {
154        let hash = hash_password_with("x", Cost::FAST).unwrap();
155
156        assert!(hash.starts_with("$argon2id$v=19$"), "unexpected hash format: {hash}");
157        assert!(hash.contains("m=8,t=1,p=1"), "cost should be recorded in the hash: {hash}");
158    }
159
160    #[test]
161    fn a_corrupt_or_foreign_hash_never_authenticates() {
162        assert!(!verify_password("anything", ""));
163        assert!(!verify_password("anything", "not-a-hash"));
164        assert!(!verify_password("anything", "$argon2id$v=19$m=8,t=1,p=1$c2FsdA$"));
165        // A bcrypt hash from some other system must not be treated as a match.
166        assert!(!verify_password("anything", "$2y$10$abcdefghijklmnopqrstuv"));
167    }
168
169    #[test]
170    fn a_hash_verifies_even_though_the_default_cost_is_higher() {
171        // Verification uses the parameters stored in the hash, not the current
172        // defaults, so raising the cost does not lock existing users out.
173        let cheap = hash_password_with("legacy", Cost::FAST).unwrap();
174
175        assert!(verify_password("legacy", &cheap));
176        assert!(needs_rehash(&cheap, Cost::DEFAULT));
177        assert!(!needs_rehash(&cheap, Cost::FAST));
178    }
179
180    #[test]
181    fn unreadable_hashes_are_reported_as_needing_a_rehash() {
182        assert!(needs_rehash("", Cost::DEFAULT));
183        assert!(needs_rehash("$2y$10$abcdefghijklmnopqrstuv", Cost::DEFAULT));
184    }
185
186    #[test]
187    fn the_default_cost_produces_a_working_hash() {
188        // The one test that pays the real cost, so the shipped parameters are
189        // proven to be accepted by argon2 rather than merely plausible.
190        let hash = hash_password("default cost").unwrap();
191
192        assert!(verify_password("default cost", &hash));
193        assert!(!verify_password("wrong", &hash));
194        assert!(!needs_rehash(&hash, Cost::DEFAULT));
195    }
196}