Skip to main content

coqui_access_kit/
hash.rs

1//! Keeping and checking secrets: bearer keys and passwords, as self-describing strings.
2//!
3//! These are plain functions and types for anyone writing a provider over their own data;
4//! nothing here knows about tables or files.
5//!
6//! | Kept as | Written | For |
7//! | --- | --- | --- |
8//! | SHA-256 | `sha256:<64 lowercase hex>` | bearer keys of 256 random bits, which need no slow hash |
9//! | Argon2id | `$argon2id$v=19$m=…,t=…,p=…$salt$hash` | passwords, or keys that must resist guessing |
10//!
11//! A stored string names its own algorithm, so one table may hold both.
12
13use argon2::password_hash::phc::PasswordHash;
14use argon2::password_hash::{PasswordHasher as _, PasswordVerifier as _};
15use argon2::{Algorithm, Argon2, Params, Version};
16use coqui_access::Limit;
17use coqui_builder::Describe;
18
19use crate::secret;
20
21/// The longest password hashed or verified unless [`PasswordHasher::max_password_bytes`] says
22/// otherwise: 4 096 bytes. It bounds the work one attempt costs.
23pub const DEFAULT_MAX_PASSWORD_BYTES: Limit = Limit::at(4096);
24
25const SHA256_PREFIX: &str = "sha256:";
26const ARGON2ID_PREFIX: &str = "$argon2id$";
27
28/// The cost of an Argon2id hash. The default is the Argon2 crate's: 19 MiB, 2 passes, 1 lane.
29///
30/// As configuration it is a map of `memory_kib`, `iterations` and `parallelism`, each
31/// defaulting to the library's value, so a config may give any of them or none. Reading it
32/// does not check the combination: [`Argon2Params::new`] does, and so does making a hash.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Describe)]
34pub struct Argon2Params {
35    /// Memory in KiB.
36    #[map(default = Params::DEFAULT_M_COST)]
37    memory_kib: u32,
38    /// Passes over the memory.
39    #[map(default = Params::DEFAULT_T_COST)]
40    iterations: u32,
41    /// Lanes.
42    #[map(default = Params::DEFAULT_P_COST)]
43    parallelism: u32,
44}
45
46impl Default for Argon2Params {
47    fn default() -> Self {
48        Self {
49            memory_kib: Params::DEFAULT_M_COST,
50            iterations: Params::DEFAULT_T_COST,
51            parallelism: Params::DEFAULT_P_COST,
52        }
53    }
54}
55
56const OUT_OF_RANGE: &str = "argon2 parameters are out of range";
57
58impl Argon2Params {
59    /// Memory in KiB, passes over it and lanes.
60    ///
61    /// # Errors
62    ///
63    /// Returns an error when Argon2 refuses the combination: memory under 8 KiB per lane, or
64    /// a zero count.
65    pub fn new(memory_kib: u32, iterations: u32, parallelism: u32) -> Result<Self, String> {
66        Params::new(memory_kib, iterations, parallelism, None)
67            .map_err(|_| OUT_OF_RANGE.to_owned())?;
68        Ok(Self {
69            memory_kib,
70            iterations,
71            parallelism,
72        })
73    }
74
75    /// Memory in KiB.
76    pub fn memory_kib(&self) -> u32 {
77        self.memory_kib
78    }
79
80    /// Passes over the memory.
81    pub fn iterations(&self) -> u32 {
82        self.iterations
83    }
84
85    /// Lanes.
86    pub fn parallelism(&self) -> u32 {
87        self.parallelism
88    }
89
90    fn hash(&self, secret: &[u8]) -> Result<String, String> {
91        let params = Params::new(self.memory_kib, self.iterations, self.parallelism, None)
92            .map_err(|_| OUT_OF_RANGE.to_owned())?;
93        Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
94            .hash_password(secret)
95            .map(|hash| hash.to_string())
96            .map_err(|_| "secret could not be hashed".to_owned())
97    }
98}
99
100/// How a bearer key is kept.
101///
102/// As configuration it is a map tagged by `algorithm`, the costs beside it under Argon2id:
103/// `{ "algorithm": "sha256" }` or `{ "algorithm": "argon2id", "memory_kib": 65536 }`.
104#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Describe)]
105#[map(tag = "algorithm", rename_all = "lowercase")]
106#[non_exhaustive]
107pub enum KeyHash {
108    /// `sha256:<hex>`: fast, and enough for a key of 256 random bits. The default.
109    #[default]
110    Sha256,
111    /// Argon2id with these costs: for a key a person might have chosen. Every presented key
112    /// then costs one Argon2id verification per Argon2id record it is checked against.
113    Argon2id(Argon2Params),
114}
115
116impl KeyHash {
117    /// Argon2id with the default costs.
118    pub fn argon2id() -> Self {
119        Self::Argon2id(Argon2Params::default())
120    }
121
122    /// What to keep of `secret`, in the form [`verify_key`] reads.
123    ///
124    /// # Errors
125    ///
126    /// Returns an error when the secret cannot be hashed (Argon2id only).
127    pub fn hash(&self, secret: &str) -> Result<String, String> {
128        match self {
129            Self::Sha256 => Ok(format!("{SHA256_PREFIX}{}", secret::hash(secret, None))),
130            Self::Argon2id(params) => params.hash(secret.as_bytes()),
131        }
132    }
133}
134
135/// Whether `presented` is the secret `stored` was made from, whatever algorithm `stored`
136/// names. A string that names no known algorithm is never a match.
137///
138/// The only branch is on the algorithm prefix of `stored`. Past it nothing returns early on
139/// where the values differ: SHA-256 digests are compared in constant time and Argon2id does
140/// its full work.
141pub fn verify_key(stored: &str, presented: &[u8]) -> bool {
142    if let Some(digest) = stored.strip_prefix(SHA256_PREFIX) {
143        secret::same(digest, &secret::hash_bytes(presented))
144    } else if stored.starts_with(ARGON2ID_PREFIX) {
145        verify_argon2id(stored, presented)
146    } else {
147        false
148    }
149}
150
151/// Whether `stored` is a string [`verify_key`] can check: a well-formed `sha256:` digest or
152/// an Argon2id hash.
153pub fn is_key_hash(stored: &str) -> bool {
154    match stored.strip_prefix(SHA256_PREFIX) {
155        Some(digest) => secret::is_hash(digest),
156        None => is_password_hash(stored),
157    }
158}
159
160/// Whether `stored` is a well-formed Argon2id hash, as [`PasswordHasher::hash`] writes it.
161pub fn is_password_hash(stored: &str) -> bool {
162    stored.starts_with(ARGON2ID_PREFIX) && PasswordHash::new(stored).is_ok()
163}
164
165/// Makes a key: `prefix` and 256 random bits. See [`secret::generate`].
166///
167/// # Errors
168///
169/// Returns an error when the operating system random source is unavailable.
170pub fn generate_key(prefix: &str) -> Result<String, String> {
171    secret::generate(prefix)
172}
173
174fn verify_argon2id(stored: &str, presented: &[u8]) -> bool {
175    PasswordHash::new(stored)
176        .ok()
177        .is_some_and(|hash| Argon2::default().verify_password(presented, &hash).is_ok())
178}
179
180/// Whether `presented` is the password `stored` (an Argon2id hash) was made from. A password
181/// over [`DEFAULT_MAX_PASSWORD_BYTES`] or a stored string that is not Argon2id never matches;
182/// [`PasswordHasher::verify`] applies the hasher's own bound instead.
183pub fn verify_password(stored: &str, presented: &str) -> bool {
184    verify_within(stored, presented, DEFAULT_MAX_PASSWORD_BYTES)
185}
186
187fn verify_within(stored: &str, presented: &str, most: Limit) -> bool {
188    most.allows(presented.len())
189        && stored.starts_with(ARGON2ID_PREFIX)
190        && verify_argon2id(stored, presented.as_bytes())
191}
192
193/// Hashes passwords with Argon2id and checks them, with a dummy hash for names nobody keeps.
194///
195/// ```
196/// use coqui_access_kit::{Argon2Params, PasswordHasher};
197///
198/// let hasher = PasswordHasher::new(Argon2Params::new(64, 1, 1).unwrap()).unwrap();
199/// let stored = hasher.hash("correct horse").unwrap();
200/// assert!(hasher.verify(Some(&stored), "correct horse"));
201/// assert!(!hasher.verify(Some(&stored), "wrong"));
202/// // No such account: the same work is done, and the answer is no.
203/// assert!(!hasher.verify(None, "correct horse"));
204/// ```
205#[derive(Debug, Clone)]
206pub struct PasswordHasher {
207    params: Argon2Params,
208    dummy: String,
209    max_password_bytes: Limit,
210}
211
212impl Default for PasswordHasher {
213    fn default() -> Self {
214        Self::new(Argon2Params::default()).expect("default parameters hash")
215    }
216}
217
218impl PasswordHasher {
219    /// A hasher with these costs.
220    ///
221    /// # Errors
222    ///
223    /// Returns an error when the dummy hash cannot be made.
224    pub fn new(params: Argon2Params) -> Result<Self, String> {
225        Ok(Self {
226            params,
227            dummy: params.hash(b"unknown account password")?,
228            max_password_bytes: DEFAULT_MAX_PASSWORD_BYTES,
229        })
230    }
231
232    /// This hasher refusing to hash, and never matching, a password longer than `most` bytes.
233    /// Default [`DEFAULT_MAX_PASSWORD_BYTES`].
234    #[must_use]
235    pub fn max_password_bytes(mut self, most: Limit) -> Self {
236        self.max_password_bytes = most;
237        self
238    }
239
240    /// The costs new hashes are made with.
241    pub fn params(&self) -> Argon2Params {
242        self.params
243    }
244
245    /// Hashes a password with a fresh random salt.
246    ///
247    /// # Errors
248    ///
249    /// Returns an error when the password is empty or longer than
250    /// [`max_password_bytes`](PasswordHasher::max_password_bytes), or hashing fails.
251    pub fn hash(&self, password: &str) -> Result<String, String> {
252        if password.is_empty() || !self.max_password_bytes.allows(password.len()) {
253            return Err(format!(
254                "password must not be empty, and {} bytes long",
255                self.max_password_bytes
256            ));
257        }
258        self.params.hash(password.as_bytes())
259    }
260
261    /// Checks `presented` against `stored`; with `None` (no such account) it checks against
262    /// the dummy hash, so an unknown name costs what a wrong password does, and answers no.
263    pub fn verify(&self, stored: Option<&str>, presented: &str) -> bool {
264        let matched = verify_within(
265            stored.unwrap_or(&self.dummy),
266            presented,
267            self.max_password_bytes,
268        );
269        stored.is_some() && matched
270    }
271}
272
273#[cfg(test)]
274mod tests {
275    use coqui_builder::{Partial, Segment};
276
277    use super::*;
278
279    fn cheap() -> Argon2Params {
280        Argon2Params::new(64, 1, 1).unwrap()
281    }
282
283    #[test]
284    fn both_algorithms_verify_their_own_secret_and_nothing_else() {
285        for how in [KeyHash::Sha256, KeyHash::Argon2id(cheap())] {
286            let key = generate_key("ck_").unwrap();
287            let stored = how.hash(&key).unwrap();
288            assert!(is_key_hash(&stored), "{stored}");
289            assert!(verify_key(&stored, key.as_bytes()));
290            assert!(!verify_key(
291                &stored,
292                generate_key("ck_").unwrap().as_bytes()
293            ));
294            assert!(!verify_key(&stored, b""));
295            assert!(!verify_key(&stored, &key.as_bytes()[1..]));
296        }
297    }
298
299    #[test]
300    fn a_table_can_mix_algorithms() {
301        let key = |n: &str| format!("ck_{n}");
302        let stored = [
303            KeyHash::Sha256.hash(&key("one")).unwrap(),
304            KeyHash::Argon2id(cheap()).hash(&key("two")).unwrap(),
305            KeyHash::Sha256.hash(&key("three")).unwrap(),
306        ];
307        for (at, name) in ["one", "two", "three"].into_iter().enumerate() {
308            let found: Vec<_> = stored
309                .iter()
310                .enumerate()
311                .filter(|(_, kept)| verify_key(kept, key(name).as_bytes()))
312                .map(|(index, _)| index)
313                .collect();
314            assert_eq!(found, [at]);
315        }
316        assert!(stored[0].starts_with("sha256:"));
317        assert!(stored[1].starts_with("$argon2id$"));
318    }
319
320    #[test]
321    fn an_unknown_or_malformed_stored_string_never_matches() {
322        let digest = secret::hash("k", None);
323        for stored in [
324            "",
325            "k",
326            // A bare digest has no algorithm.
327            digest.as_str(),
328            "sha256:",
329            "sha256:abc",
330            "SHA256:00",
331            "$argon2id$garbage",
332            "$argon2i$v=19$m=8,t=1,p=1$c2FsdHNhbHQ$aGFzaGhhc2g",
333            "$2b$12$abcdefghijklmnopqrstuv",
334        ] {
335            assert!(!verify_key(stored, b"k"), "{stored}");
336            assert!(!is_key_hash(stored), "{stored}");
337        }
338    }
339
340    #[test]
341    fn a_different_prefix_runs_the_whole_comparison_on_the_digest() {
342        // The same digest under another prefix is not a match, and a digest of the wrong
343        // length is compared (and refused) rather than skipped.
344        let stored = KeyHash::Sha256.hash("k").unwrap();
345        assert!(verify_key(&stored, b"k"));
346        let bare = stored.trim_start_matches("sha256:");
347        assert!(!verify_key(&format!("sha257:{bare}"), b"k"));
348        assert!(!verify_key(&format!("sha256:{}", &bare[..63]), b"k"));
349        assert!(!verify_key(&format!("sha256:{bare}00"), b"k"));
350    }
351
352    #[test]
353    fn argon2_costs_are_checked_and_exposed() {
354        assert_eq!(Argon2Params::default().memory_kib(), 19 * 1024);
355        assert_eq!(Argon2Params::default().iterations(), 2);
356        assert_eq!(Argon2Params::default().parallelism(), 1);
357        assert!(Argon2Params::new(4, 1, 1).is_err());
358        assert!(Argon2Params::new(64, 0, 1).is_err());
359        let stored = KeyHash::Argon2id(Argon2Params::new(64, 2, 1).unwrap())
360            .hash("k")
361            .unwrap();
362        assert!(stored.contains("m=64,t=2,p=1"));
363    }
364
365    fn costs_from(keys: &[(&str, &str)]) -> Result<Argon2Params, String> {
366        let mut partial = Partial::<Argon2Params>::new();
367        for (key, text) in keys {
368            partial.set(key, text).map_err(|error| error.to_string())?;
369        }
370        partial.build().map_err(|error| error.to_string())
371    }
372
373    #[test]
374    fn argon2_costs_read_from_configuration_default_each_field() {
375        assert_eq!(costs_from(&[]).unwrap(), Argon2Params::default());
376        let set = costs_from(&[("memory_kib", "64"), ("iterations", "1")]).unwrap();
377        assert_eq!(set, Argon2Params::new(64, 1, 1).unwrap());
378        // Reading does not check the combination; making a hash does.
379        let zero = costs_from(&[("iterations", "0")]).unwrap();
380        assert!(KeyHash::Argon2id(zero).hash("k").is_err());
381        assert!(costs_from(&[("iterations", "two")]).is_err());
382        assert!(costs_from(&[("lanes", "1")]).is_err());
383    }
384
385    #[test]
386    fn argon2_costs_describe_their_defaults() {
387        let description = Argon2Params::description();
388        let default = description.default_at(&[Segment::key("memory_kib")]);
389        assert_eq!(default.as_deref(), Some("19456"));
390    }
391
392    #[test]
393    fn a_key_hash_reads_from_configuration_tagged_by_algorithm() {
394        let read = |keys: &[(&str, &str)]| {
395            let mut partial = Partial::<KeyHash>::new();
396            for (key, text) in keys {
397                partial.set(key, text).map_err(|error| error.to_string())?;
398            }
399            partial.build().map_err(|error| error.to_string())
400        };
401        // The default applies to a field that holds a key hash, not to the tag by itself.
402        assert!(read(&[]).is_err());
403        assert_eq!(read(&[("algorithm", "sha256")]).unwrap(), KeyHash::Sha256);
404        assert_eq!(
405            read(&[("algorithm", "argon2id")]).unwrap(),
406            KeyHash::argon2id()
407        );
408        assert_eq!(
409            read(&[
410                ("algorithm", "argon2id"),
411                ("memory_kib", "64"),
412                ("iterations", "1")
413            ])
414            .unwrap(),
415            KeyHash::Argon2id(cheap())
416        );
417        assert!(read(&[("algorithm", "md5")]).is_err());
418    }
419
420    #[test]
421    fn passwords_are_hashed_bounded_and_checked_with_a_dummy_for_unknown_names() {
422        let hasher = PasswordHasher::new(cheap()).unwrap();
423        assert_eq!(hasher.params(), cheap());
424        let stored = hasher.hash("pw").unwrap();
425        assert_ne!(stored, hasher.hash("pw").unwrap(), "salted");
426        assert!(hasher.verify(Some(&stored), "pw"));
427        assert!(!hasher.verify(Some(&stored), "px"));
428        assert!(!hasher.verify(None, "pw"));
429        assert!(!hasher.verify(Some("not a hash"), "pw"));
430        assert!(hasher.hash("").is_err());
431        assert!(hasher.hash(&"x".repeat(4097)).is_err());
432        let longer = hasher.clone().max_password_bytes(Limit::UNBOUNDED);
433        let long = longer.hash(&"x".repeat(5000)).unwrap();
434        assert!(longer.verify(Some(&long), &"x".repeat(5000)));
435        assert!(
436            !hasher.verify(Some(&long), &"x".repeat(5000)),
437            "past this hasher's bound"
438        );
439        let shorter = hasher.clone().max_password_bytes(Limit::at(2));
440        assert!(shorter.hash("abc").is_err() && shorter.hash("ab").is_ok());
441        assert!(!verify_password(&stored, &"x".repeat(4097)));
442        // A key digest is not a password hash.
443        assert!(!verify_password(&KeyHash::Sha256.hash("pw").unwrap(), "pw"));
444    }
445}