ironauth_hash_scheme/lib.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3// The README is included as crate documentation so its Rust examples are COMPILED and RUN
4// by `cargo test`. The first draft of that README invented an API (a `Verdict` enum and a
5// `verify` returning `Result`) that this crate has never had. A README example nobody
6// compiles is the unmeasured-sentence defect in its most public form: it is the first thing
7// a crates.io reader tries.
8#![doc = include_str!("../README.md")]
9
10//! The algorithm-tagged foreign password-hash scheme layer (issue #55).
11//!
12//! This is the passwap-style reusable core: a stored foreign hash is PARSED into a
13//! recognized [`Scheme`], VERIFIED against a candidate password by dispatching on
14//! that scheme, and (at import) BOUNDS-CHECKED so an attacker-supplied cost
15//! parameter cannot turn a later login verification into a denial-of-service vector
16//! (the Kratos lesson: out-of-bounds imported costs are rejected at import, never
17//! silently accepted). The module has NO database or store dependency, so it is
18//! self-contained and the login path (`ironauth-oidc`) can consume it directly.
19//!
20//! # Storage contract
21//!
22//! A foreign hash is stored AS-IS: the canonical, self-describing string is the
23//! verifier and the [`Scheme::tag`] is the non-secret algorithm label. There is no
24//! function here that recovers a plaintext password; every scheme is a one-way
25//! verifier.
26//!
27//! # Recognized schemes and their string forms
28//!
29//! | Scheme | Detected prefix |
30//! |----------------------------|------------------------------------------|
31//! | [`Scheme::Bcrypt`] | `$2a$` / `$2b$` / `$2x$` / `$2y$` |
32//! | [`Scheme::Scrypt`] | `$scrypt$` (PHC) |
33//! | [`Scheme::Pbkdf2`] | `$pbkdf2-sha256$` / `$pbkdf2-sha512$` |
34//! | [`Scheme::Argon2`] | `$argon2i$` / `$argon2d$` / `$argon2id$` |
35//! | [`Scheme::FirebaseScrypt`] | `$fbscrypt$` (canonical, see below) |
36//! | [`Scheme::ShaCrypt`] | `$5$` (SHA-256) / `$6$` (SHA-512) |
37//! | [`Scheme::Ldap`] | `{SHA}` / `{SSHA}` / `{SHA256}` / ... |
38//!
39//! # Two schemes with no cost to bound, and why that is the dangerous case
40//!
41//! Every bound in this crate exists because an attacker-supplied cost turns a later
42//! login into a denial-of-service vector. The LDAP schemes invert that: `{SHA}` and
43//! its relatives are a SINGLE unsalted or lightly salted digest pass, so they verify
44//! in microseconds and there is no cost parameter to reject. The hazard is not that
45//! verification is slow, it is that the stored hash is nearly free to attack offline.
46//! So this crate recognizes them (a user who cannot be verified cannot be migrated at
47//! all) and [`Scheme::rehash_is_urgent`] reports which schemes must not survive a
48//! first successful login. `{MD5}` and `{SMD5}` are deliberately NOT recognized: MD5
49//! is not in the issue's list and accepting it would be adding a scheme nothing asked
50//! for on the strength of it being easy.
51//!
52//! Firebase's modified scrypt is not self-describing in the wild (its
53//! account-wide signer key, salt separator, and cost live outside the per-user
54//! hash), so this crate defines a canonical, self-contained serialization that
55//! round-trips through [`firebase_stored`]:
56//!
57//! ```text
58//! $fbscrypt$n=<mem_cost>,r=<rounds>,p=1$<salt_sep_b64>$<signer_key_b64>$<salt_b64>$<hash_b64>
59//! ```
60
61use aes::Aes256;
62use aes::cipher::{KeyIvInit, StreamCipher};
63use base64::Engine as _;
64use base64::engine::general_purpose::STANDARD as B64;
65use ctr::Ctr128BE;
66use password_hash::{PasswordHash, PasswordVerifier};
67use subtle::ConstantTimeEq;
68
69/// AES-256 in big-endian 128-bit-counter CTR mode: the cipher Firebase's modified
70/// scrypt runs over the account signer key after scrypt key derivation.
71type Aes256Ctr = Ctr128BE<Aes256>;
72
73/// The documented maximum bcrypt cost accepted at import (a work factor of
74/// `2^cost`). Above this a single verification is a denial-of-service vector, so
75/// the record is rejected at import (the Kratos lesson).
76pub const MAX_BCRYPT_COST: u32 = 15;
77/// The minimum bcrypt cost bcrypt itself permits; below it the hash is malformed.
78pub const MIN_BCRYPT_COST: u32 = 4;
79/// The documented maximum scrypt `log2(N)` accepted at import (CPU/memory cost).
80pub const MAX_SCRYPT_LOG_N: u32 = 20;
81/// The documented maximum scrypt block-size parameter `r` accepted at import.
82pub const MAX_SCRYPT_R: u32 = 32;
83/// The documented maximum scrypt parallelism `p` accepted at import.
84pub const MAX_SCRYPT_P: u32 = 16;
85/// The documented maximum PBKDF2 iteration count accepted at import.
86pub const MAX_PBKDF2_ITERATIONS: u32 = 10_000_000;
87/// The documented maximum Argon2 memory cost, in KiB, accepted at import.
88pub const MAX_ARGON2_MEMORY_KIB: u32 = 4_194_304;
89/// The documented maximum Argon2 pass count accepted at import.
90pub const MAX_ARGON2_PASSES: u32 = 16;
91/// The documented maximum Argon2 parallelism accepted at import.
92pub const MAX_ARGON2_PARALLELISM: u32 = 16;
93/// The documented maximum Firebase modified-scrypt memory cost (`log2(N)`)
94/// accepted at import.
95pub const MAX_FIREBASE_MEM_COST: u32 = 20;
96/// The documented maximum Firebase modified-scrypt rounds (`r`) accepted at import.
97pub const MAX_FIREBASE_ROUNDS: u32 = 16;
98/// The documented maximum SHA-crypt `rounds=` accepted at import. glibc permits up to
99/// 999999999, which is minutes of CPU for ONE verification and therefore exactly the
100/// vector the bounds exist for. A million rounds is already far beyond any deployment
101/// that expects to serve logins.
102pub const MAX_SHA_CRYPT_ROUNDS: u32 = 1_000_000;
103/// The minimum SHA-crypt `rounds=` glibc itself accepts; below it the string is
104/// malformed rather than merely cheap.
105pub const MIN_SHA_CRYPT_ROUNDS: u32 = 1_000;
106
107/// The scrypt-derived-key length Firebase's modified scrypt uses; the first 32
108/// bytes key the AES-256-CTR pass.
109const FIREBASE_DERIVED_KEY_LEN: usize = 64;
110/// The all-zero 128-bit IV Firebase's modified scrypt runs AES-256-CTR under.
111const FIREBASE_IV: [u8; 16] = [0_u8; 16];
112
113/// A recognized foreign password-hash scheme (issue #55). The variant is the
114/// algorithm tag stored alongside the hash; verification dispatches on it.
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub enum Scheme {
117 /// bcrypt (Blowfish-based), any of the `$2a$` / `$2b$` / `$2x$` / `$2y$`
118 /// variants (they share one verify path).
119 Bcrypt,
120 /// scrypt (RFC 7914) in the PHC string form `$scrypt$ln=..,r=..,p=..$salt$hash`.
121 Scrypt,
122 /// PBKDF2 (RFC 8018 / PKCS#5 v2.1) over HMAC-SHA256 or HMAC-SHA512 in the PHC
123 /// string form `$pbkdf2-sha256$i=..$salt$hash`.
124 Pbkdf2,
125 /// The Argon2 family (Argon2i, Argon2d, Argon2id) in the RFC 9106 PHC form.
126 Argon2,
127 /// Firebase's modified scrypt (scrypt key derivation followed by AES-256-CTR
128 /// over the account signer key), in this crate's canonical `$fbscrypt$` form.
129 FirebaseScrypt,
130 /// SHA-crypt, the glibc modular-crypt scheme: `$5$` (SHA-256) and `$6$`
131 /// (SHA-512), with the optional `rounds=` parameter. One variant rather than two
132 /// because the two share a format, a bound and a verify path; the digest width is
133 /// carried in the string, which is where dispatch already reads it from.
134 ShaCrypt,
135 /// The LDAP/RFC 2307 digest schemes: `{SHA}`, `{SSHA}`, `{SHA256}`, `{SSHA256}`,
136 /// `{SHA512}`, `{SSHA512}`. Salted (`{S...}`) forms append the salt to the digest
137 /// inside the base64 payload. They carry NO cost parameter; see the module note.
138 Ldap,
139}
140
141impl Scheme {
142 /// Every variant, in declaration order.
143 ///
144 /// A slice rather than something each test writes out for itself. Two tests in
145 /// this file sweep every scheme, and a hand-written list beside an enum is the
146 /// shape where a variant added later is simply absent from the sweep and nothing
147 /// says so. Adding a variant without extending this array is a compile error,
148 /// because the length is declared.
149 pub const ALL: [Scheme; 7] = [
150 Scheme::Bcrypt,
151 Scheme::Scrypt,
152 Scheme::Pbkdf2,
153 Scheme::Argon2,
154 Scheme::FirebaseScrypt,
155 Scheme::ShaCrypt,
156 Scheme::Ldap,
157 ];
158
159 /// The stable, non-secret algorithm tag stored alongside the hash and used for
160 /// dispatch and metrics.
161 #[must_use]
162 pub fn tag(self) -> &'static str {
163 match self {
164 Scheme::Bcrypt => "bcrypt",
165 Scheme::Scrypt => "scrypt",
166 Scheme::Pbkdf2 => "pbkdf2",
167 Scheme::Argon2 => "argon2",
168 Scheme::FirebaseScrypt => "firebase-scrypt",
169 Scheme::ShaCrypt => "sha-crypt",
170 Scheme::Ldap => "ldap-digest",
171 }
172 }
173
174 /// Reconstruct a scheme from its [`Scheme::tag`], or [`None`] for an unknown
175 /// tag.
176 #[must_use]
177 pub fn from_tag(tag: &str) -> Option<Self> {
178 match tag {
179 "bcrypt" => Some(Scheme::Bcrypt),
180 "scrypt" => Some(Scheme::Scrypt),
181 "pbkdf2" => Some(Scheme::Pbkdf2),
182 "argon2" => Some(Scheme::Argon2),
183 "firebase-scrypt" => Some(Scheme::FirebaseScrypt),
184 "sha-crypt" => Some(Scheme::ShaCrypt),
185 "ldap-digest" => Some(Scheme::Ldap),
186 _ => None,
187 }
188 }
189
190 /// Whether a first successful login against this scheme must REPLACE the stored
191 /// hash rather than merely be allowed to succeed.
192 ///
193 /// Every scheme here is a foreign hash and every one of them is meant to be
194 /// rehashed to Argon2id eventually. This names the ones where leaving the old
195 /// hash in place is a standing exposure rather than a deferred cleanup: the LDAP
196 /// digests are one unsalted or lightly salted pass, so a stolen row is attacked
197 /// at the speed of a raw digest and no import bound can change that. A caller
198 /// that rehashes everything is correct and can ignore this; one that rehashes
199 /// lazily must not ignore it for these.
200 #[must_use]
201 pub fn rehash_is_urgent(self) -> bool {
202 matches!(self, Scheme::Ldap)
203 }
204}
205
206/// Why a foreign hash string could not be accepted at import (issue #55).
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub enum HashError {
209 /// The string matches no recognized scheme prefix.
210 Unrecognized,
211 /// The string matches a scheme prefix but is not a well-formed hash of that
212 /// scheme (a parse failure), so it could never verify.
213 Malformed,
214 /// A cost parameter exceeds this crate's documented denial-of-service bound (or
215 /// falls below the scheme minimum). The message names the offending parameter;
216 /// it is operator-safe and never echoes attacker-controlled bytes.
217 OutOfBounds(&'static str),
218}
219
220impl core::fmt::Display for HashError {
221 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
222 match self {
223 HashError::Unrecognized => f.write_str("unrecognized foreign hash scheme"),
224 HashError::Malformed => f.write_str("malformed foreign hash for its scheme"),
225 HashError::OutOfBounds(param) => {
226 write!(f, "foreign hash cost parameter out of bounds: {param}")
227 }
228 }
229 }
230}
231
232impl std::error::Error for HashError {}
233
234/// A parsed, bounds-checked foreign password hash (issue #55): the recognized
235/// [`Scheme`] and the canonical stored verifier string. Constructing one proves
236/// the string is a well-formed hash of a recognized scheme whose cost parameters
237/// are within the documented bounds, so a later [`ForeignHash::verify`] can never
238/// be a denial-of-service vector.
239#[derive(Debug, Clone, PartialEq, Eq)]
240pub struct ForeignHash {
241 scheme: Scheme,
242 stored: String,
243}
244
245impl ForeignHash {
246 /// Parse and bounds-check a stored foreign hash string.
247 ///
248 /// The scheme is detected from the leading marker, the string is validated as a
249 /// well-formed hash of that scheme, and its cost parameters are checked against
250 /// the documented maxima. The plaintext password is never involved.
251 ///
252 /// # Errors
253 ///
254 /// [`HashError::Unrecognized`] if no scheme prefix matches;
255 /// [`HashError::Malformed`] if the string is not a valid hash of its scheme;
256 /// [`HashError::OutOfBounds`] if a cost parameter is outside the documented
257 /// bounds.
258 pub fn parse(stored: &str) -> Result<Self, HashError> {
259 let scheme = detect(stored).ok_or(HashError::Unrecognized)?;
260 match scheme {
261 Scheme::Bcrypt => bounds_bcrypt(stored)?,
262 Scheme::Scrypt => bounds_scrypt(stored)?,
263 Scheme::Pbkdf2 => bounds_pbkdf2(stored)?,
264 Scheme::Argon2 => bounds_argon2(stored)?,
265 Scheme::FirebaseScrypt => {
266 parse_firebase(stored)?;
267 }
268 Scheme::ShaCrypt => bounds_sha_crypt(stored)?,
269 // No cost parameter to bound; what CAN fail is the payload, so the parse
270 // runs here and a malformed one is refused at import rather than at login.
271 Scheme::Ldap => {
272 parse_ldap(stored)?;
273 }
274 }
275 Ok(Self {
276 scheme,
277 stored: stored.to_owned(),
278 })
279 }
280
281 /// The recognized scheme.
282 #[must_use]
283 pub fn scheme(&self) -> Scheme {
284 self.scheme
285 }
286
287 /// The non-secret algorithm tag ([`Scheme::tag`]) for storage and metrics.
288 #[must_use]
289 pub fn tag(&self) -> &'static str {
290 self.scheme.tag()
291 }
292
293 /// The canonical stored verifier string, to persist AS-IS.
294 #[must_use]
295 pub fn stored(&self) -> &str {
296 &self.stored
297 }
298
299 /// Verify `password` against this foreign hash, dispatching on its scheme.
300 /// Returns `false` for a wrong password AND for any internal decode failure
301 /// (fail closed); a corrupt stored value can never authenticate. This never
302 /// panics.
303 #[must_use]
304 pub fn verify(&self, password: &[u8]) -> bool {
305 match self.scheme {
306 Scheme::Bcrypt => bcrypt::verify(password, &self.stored).unwrap_or(false),
307 Scheme::Scrypt => phc_verify(&scrypt::Scrypt, password, &self.stored),
308 Scheme::Pbkdf2 => phc_verify(&pbkdf2::Pbkdf2, password, &self.stored),
309 Scheme::Argon2 => phc_verify(&argon2::Argon2::default(), password, &self.stored),
310 Scheme::FirebaseScrypt => match parse_firebase(&self.stored) {
311 Ok(fb) => fb.verify(password),
312 Err(_) => false,
313 },
314 Scheme::ShaCrypt => sha_crypt_verify(password, &self.stored),
315 Scheme::Ldap => match parse_ldap(&self.stored) {
316 Ok(ldap) => ldap.verify(password),
317 Err(_) => false,
318 },
319 }
320 }
321}
322
323/// Verify a PHC-string hash with `verifier`, returning `false` on a wrong password
324/// or an unparsable string (fail closed).
325fn phc_verify(verifier: &dyn PasswordVerifier, password: &[u8], stored: &str) -> bool {
326 match PasswordHash::new(stored) {
327 Ok(parsed) => verifier.verify_password(password, &parsed).is_ok(),
328 Err(_) => false,
329 }
330}
331
332/// Detect the scheme from the leading marker of a stored hash string.
333fn detect(stored: &str) -> Option<Scheme> {
334 if stored.starts_with("$2a$")
335 || stored.starts_with("$2b$")
336 || stored.starts_with("$2x$")
337 || stored.starts_with("$2y$")
338 {
339 Some(Scheme::Bcrypt)
340 } else if stored.starts_with("$scrypt$") {
341 Some(Scheme::Scrypt)
342 } else if stored.starts_with("$pbkdf2-") {
343 Some(Scheme::Pbkdf2)
344 } else if stored.starts_with("$argon2") {
345 Some(Scheme::Argon2)
346 } else if stored.starts_with("$fbscrypt$") {
347 Some(Scheme::FirebaseScrypt)
348 } else if stored.starts_with("$5$") || stored.starts_with("$6$") {
349 Some(Scheme::ShaCrypt)
350 } else if ldap_variant(stored).is_some() {
351 Some(Scheme::Ldap)
352 } else {
353 None
354 }
355}
356
357/// Bounds-check a SHA-crypt string: the optional `rounds=` field must sit inside the
358/// documented window.
359///
360/// The parameter is OPTIONAL in the format (`$6$salt$hash` means the glibc default of
361/// 5000), so its ABSENCE is accepted rather than treated as a malformed string. Only a
362/// present-and-unparseable field is malformed; an omitted one is the common case and
363/// rejecting it would refuse most real `/etc/shadow` rows.
364fn bounds_sha_crypt(stored: &str) -> Result<(), HashError> {
365 // `$6$rounds=5000$salt$hash`: field 2 carries the parameter when present.
366 let Some(field) = stored.split('$').nth(2) else {
367 return Err(HashError::Malformed);
368 };
369 let Some(rounds) = field.strip_prefix("rounds=") else {
370 // No `rounds=`, so the scheme default applies and there is nothing to bound.
371 // The payload itself is validated by the verify path, which fails closed.
372 return Ok(());
373 };
374 let rounds: u32 = rounds.parse().map_err(|_| HashError::Malformed)?;
375 if rounds > MAX_SHA_CRYPT_ROUNDS {
376 return Err(HashError::OutOfBounds("sha-crypt rounds"));
377 }
378 if rounds < MIN_SHA_CRYPT_ROUNDS {
379 return Err(HashError::OutOfBounds("sha-crypt rounds"));
380 }
381 Ok(())
382}
383
384/// Verify a SHA-crypt string, failing closed on any decode failure.
385///
386/// SHA-crypt is Modular Crypt Format and not PHC, so this cannot go through the
387/// `phc_verify` helper the other schemes share: `sha-crypt` brings its own, newer
388/// `password_hash`, and its `PasswordVerifier` is implemented over MCF rather than
389/// over the PHC `PasswordHash` this file's other verifiers take. The `str` impl is
390/// used deliberately; it parses the MCF string with the same code the typed impls
391/// delegate to, and taking it avoids a second `password-hash` in the manifest whose
392/// only purpose would be to turn on a feature.
393///
394/// `ShaCrypt::default()` is not a choice of digest. The algorithm is read from the
395/// string's own `$5$`/`$6$` id inside `verify_password`, so a `$5$` hash is verified
396/// as SHA-256 whatever this receiver was built with.
397fn sha_crypt_verify(password: &[u8], stored: &str) -> bool {
398 use sha_crypt::password_hash::PasswordVerifier as _;
399
400 sha_crypt::ShaCrypt::default()
401 .verify_password(password, stored)
402 .is_ok()
403}
404
405/// One parsed LDAP/RFC 2307 digest: the digest bytes and, for a salted variant, the
406/// salt that was appended to the password before hashing.
407struct LdapHash {
408 variant: LdapVariant,
409 digest: Vec<u8>,
410 salt: Vec<u8>,
411}
412
413/// Which LDAP digest a string declares, and whether it is salted.
414#[derive(Clone, Copy, PartialEq, Eq)]
415enum LdapVariant {
416 Sha1 { salted: bool },
417 Sha256 { salted: bool },
418 Sha512 { salted: bool },
419}
420
421impl LdapVariant {
422 /// The digest width in bytes, which is also where the salt begins in a salted
423 /// payload. Read from the VARIANT and never from the payload length: taking it
424 /// from the payload would let a truncated blob redefine where the salt starts and
425 /// verify against a shorter digest than the scheme specifies.
426 fn digest_len(self) -> usize {
427 match self {
428 LdapVariant::Sha1 { .. } => 20,
429 LdapVariant::Sha256 { .. } => 32,
430 LdapVariant::Sha512 { .. } => 64,
431 }
432 }
433
434 fn salted(self) -> bool {
435 match self {
436 LdapVariant::Sha1 { salted }
437 | LdapVariant::Sha256 { salted }
438 | LdapVariant::Sha512 { salted } => salted,
439 }
440 }
441}
442
443/// The declared variant and the base64 payload, or [`None`] when the string carries no
444/// recognized LDAP prefix.
445///
446/// The order of this table is NOT load-bearing, and saying so is the point: the tags
447/// look like they overlap (`{SSHA}` and `{SSHA256}` share four characters) but the
448/// CLOSING BRACE terminates every one of them, so `{SSHA}` does not prefix
449/// `{SSHA256}...` and no ordering can confuse the two. A comment claiming the order
450/// protects against that would describe a hazard this format does not have, and the
451/// next author would preserve an ordering for a reason that was never true.
452fn ldap_variant(stored: &str) -> Option<(LdapVariant, &str)> {
453 const PREFIXES: &[(&str, LdapVariant)] = &[
454 ("{SSHA256}", LdapVariant::Sha256 { salted: true }),
455 ("{SSHA512}", LdapVariant::Sha512 { salted: true }),
456 ("{SHA256}", LdapVariant::Sha256 { salted: false }),
457 ("{SHA512}", LdapVariant::Sha512 { salted: false }),
458 ("{SSHA}", LdapVariant::Sha1 { salted: true }),
459 ("{SHA}", LdapVariant::Sha1 { salted: false }),
460 ];
461 PREFIXES
462 .iter()
463 .find_map(|(prefix, variant)| stored.strip_prefix(prefix).map(|rest| (*variant, rest)))
464}
465
466/// Parse an LDAP digest string into its digest and salt.
467fn parse_ldap(stored: &str) -> Result<LdapHash, HashError> {
468 let (variant, payload) = ldap_variant(stored).ok_or(HashError::Unrecognized)?;
469 let raw = B64.decode(payload).map_err(|_| HashError::Malformed)?;
470 let width = variant.digest_len();
471 if variant.salted() {
472 // A salted payload is digest || salt, so anything at or below the digest width
473 // carries no salt and is not the scheme it claims to be. Refused at import: a
474 // login-time failure would look like a wrong password.
475 if raw.len() <= width {
476 return Err(HashError::Malformed);
477 }
478 let (digest, salt) = raw.split_at(width);
479 Ok(LdapHash {
480 variant,
481 digest: digest.to_vec(),
482 salt: salt.to_vec(),
483 })
484 } else {
485 if raw.len() != width {
486 return Err(HashError::Malformed);
487 }
488 Ok(LdapHash {
489 variant,
490 digest: raw,
491 salt: Vec::new(),
492 })
493 }
494}
495
496impl LdapHash {
497 /// Recompute the digest over `password || salt` and compare in constant time.
498 fn verify(&self, password: &[u8]) -> bool {
499 use sha1::Digest as _;
500
501 let computed: Vec<u8> = match self.variant {
502 LdapVariant::Sha1 { .. } => {
503 let mut hasher = sha1::Sha1::new();
504 hasher.update(password);
505 hasher.update(&self.salt);
506 hasher.finalize().to_vec()
507 }
508 LdapVariant::Sha256 { .. } => {
509 let mut hasher = sha2::Sha256::new();
510 hasher.update(password);
511 hasher.update(&self.salt);
512 hasher.finalize().to_vec()
513 }
514 LdapVariant::Sha512 { .. } => {
515 let mut hasher = sha2::Sha512::new();
516 hasher.update(password);
517 hasher.update(&self.salt);
518 hasher.finalize().to_vec()
519 }
520 };
521 computed.ct_eq(&self.digest).into()
522 }
523}
524
525/// Read a decimal PHC parameter (for example `m`, `t`, `ln`, `i`) from a parsed
526/// hash, or [`None`] when it is absent or not a decimal.
527fn phc_param(parsed: &PasswordHash, name: &str) -> Option<u32> {
528 parsed
529 .params
530 .iter()
531 .find(|(ident, _)| ident.as_str() == name)
532 .and_then(|(_, value)| value.decimal().ok())
533}
534
535/// Bounds-check a bcrypt hash: the cost embedded at bytes 4..6 (`$2b$NN$...`) must
536/// be within `[MIN_BCRYPT_COST, MAX_BCRYPT_COST]`.
537fn bounds_bcrypt(stored: &str) -> Result<(), HashError> {
538 let cost_str = stored.get(4..6).ok_or(HashError::Malformed)?;
539 let cost: u32 = cost_str.parse().map_err(|_| HashError::Malformed)?;
540 if cost < MIN_BCRYPT_COST {
541 return Err(HashError::OutOfBounds("bcrypt cost below minimum"));
542 }
543 if cost > MAX_BCRYPT_COST {
544 return Err(HashError::OutOfBounds("bcrypt cost"));
545 }
546 Ok(())
547}
548
549/// Bounds-check a scrypt PHC hash: `ln`, `r`, and `p` within the documented maxima.
550fn bounds_scrypt(stored: &str) -> Result<(), HashError> {
551 let parsed = PasswordHash::new(stored).map_err(|_| HashError::Malformed)?;
552 let log_n = phc_param(&parsed, "ln").ok_or(HashError::Malformed)?;
553 let r = phc_param(&parsed, "r").ok_or(HashError::Malformed)?;
554 let p = phc_param(&parsed, "p").ok_or(HashError::Malformed)?;
555 if log_n > MAX_SCRYPT_LOG_N {
556 return Err(HashError::OutOfBounds("scrypt log2(N)"));
557 }
558 if r > MAX_SCRYPT_R {
559 return Err(HashError::OutOfBounds("scrypt r"));
560 }
561 if p > MAX_SCRYPT_P {
562 return Err(HashError::OutOfBounds("scrypt p"));
563 }
564 Ok(())
565}
566
567/// Bounds-check a PBKDF2 PHC hash: the iteration count `i` within the documented
568/// maximum.
569fn bounds_pbkdf2(stored: &str) -> Result<(), HashError> {
570 let parsed = PasswordHash::new(stored).map_err(|_| HashError::Malformed)?;
571 let iterations = phc_param(&parsed, "i").ok_or(HashError::Malformed)?;
572 if iterations > MAX_PBKDF2_ITERATIONS {
573 return Err(HashError::OutOfBounds("pbkdf2 iterations"));
574 }
575 Ok(())
576}
577
578/// Bounds-check an Argon2 PHC hash: memory `m`, passes `t`, and parallelism `p`
579/// within the documented maxima.
580fn bounds_argon2(stored: &str) -> Result<(), HashError> {
581 let parsed = PasswordHash::new(stored).map_err(|_| HashError::Malformed)?;
582 let m = phc_param(&parsed, "m").ok_or(HashError::Malformed)?;
583 let t = phc_param(&parsed, "t").ok_or(HashError::Malformed)?;
584 let p = phc_param(&parsed, "p").ok_or(HashError::Malformed)?;
585 if m > MAX_ARGON2_MEMORY_KIB {
586 return Err(HashError::OutOfBounds("argon2 memory"));
587 }
588 if t > MAX_ARGON2_PASSES {
589 return Err(HashError::OutOfBounds("argon2 passes"));
590 }
591 if p > MAX_ARGON2_PARALLELISM {
592 return Err(HashError::OutOfBounds("argon2 parallelism"));
593 }
594 Ok(())
595}
596
597/// The decoded operands of a canonical Firebase modified-scrypt hash.
598struct Firebase {
599 mem_cost: u8,
600 rounds: u32,
601 salt_separator: Vec<u8>,
602 signer_key: Vec<u8>,
603 salt: Vec<u8>,
604 expected: Vec<u8>,
605}
606
607impl Firebase {
608 /// Verify `password` against this Firebase hash: scrypt-derive a 64-byte key,
609 /// AES-256-CTR the signer key under its first 32 bytes, and constant-time
610 /// compare against the expected hash. Fail closed on any internal error.
611 fn verify(&self, password: &[u8]) -> bool {
612 let mut salt_input = self.salt.clone();
613 salt_input.extend_from_slice(&self.salt_separator);
614 let Ok(params) =
615 scrypt::Params::new(self.mem_cost, self.rounds, 1, FIREBASE_DERIVED_KEY_LEN)
616 else {
617 return false;
618 };
619 let mut derived = [0_u8; FIREBASE_DERIVED_KEY_LEN];
620 if scrypt::scrypt(password, &salt_input, ¶ms, &mut derived).is_err() {
621 return false;
622 }
623 let Ok(mut cipher) = Aes256Ctr::new_from_slices(&derived[..32], &FIREBASE_IV) else {
624 return false;
625 };
626 let mut block = self.signer_key.clone();
627 cipher.apply_keystream(&mut block);
628 block.ct_eq(&self.expected).into()
629 }
630}
631
632/// Serialize Firebase modified-scrypt operands into this crate's canonical
633/// `$fbscrypt$` storage string. The four byte operands are supplied already
634/// standard-base64-encoded exactly as a Firebase account export carries them.
635#[must_use]
636pub fn firebase_stored(
637 mem_cost: u32,
638 rounds: u32,
639 salt_separator_b64: &str,
640 signer_key_b64: &str,
641 salt_b64: &str,
642 hash_b64: &str,
643) -> String {
644 format!(
645 "$fbscrypt$n={mem_cost},r={rounds},p=1${salt_separator_b64}${signer_key_b64}${salt_b64}${hash_b64}"
646 )
647}
648
649/// Parse and bounds-check a canonical `$fbscrypt$` string.
650fn parse_firebase(stored: &str) -> Result<Firebase, HashError> {
651 // $fbscrypt$n=<mem>,r=<rounds>,p=1$<saltSep>$<signerKey>$<salt>$<hash>
652 let body = stored
653 .strip_prefix("$fbscrypt$")
654 .ok_or(HashError::Malformed)?;
655 let parts: Vec<&str> = body.split('$').collect();
656 if parts.len() != 5 {
657 return Err(HashError::Malformed);
658 }
659 let (mem_cost, rounds) = parse_firebase_params(parts[0])?;
660 if mem_cost > MAX_FIREBASE_MEM_COST {
661 return Err(HashError::OutOfBounds("firebase mem_cost"));
662 }
663 if rounds > MAX_FIREBASE_ROUNDS {
664 return Err(HashError::OutOfBounds("firebase rounds"));
665 }
666 let salt_separator = B64.decode(parts[1]).map_err(|_| HashError::Malformed)?;
667 let signer_key = B64.decode(parts[2]).map_err(|_| HashError::Malformed)?;
668 let salt = B64.decode(parts[3]).map_err(|_| HashError::Malformed)?;
669 let expected = B64.decode(parts[4]).map_err(|_| HashError::Malformed)?;
670 let mem_cost = u8::try_from(mem_cost).map_err(|_| HashError::Malformed)?;
671 Ok(Firebase {
672 mem_cost,
673 rounds,
674 salt_separator,
675 signer_key,
676 salt,
677 expected,
678 })
679}
680
681/// Parse the `n=<mem>,r=<rounds>,p=1` parameter segment of a `$fbscrypt$` string.
682fn parse_firebase_params(segment: &str) -> Result<(u32, u32), HashError> {
683 let mut mem_cost = None;
684 let mut rounds = None;
685 for field in segment.split(',') {
686 let (key, value) = field.split_once('=').ok_or(HashError::Malformed)?;
687 match key {
688 "n" => mem_cost = Some(value.parse().map_err(|_| HashError::Malformed)?),
689 "r" => rounds = Some(value.parse().map_err(|_| HashError::Malformed)?),
690 // p is pinned to 1 by the algorithm; accept and ignore its presence.
691 "p" => {}
692 _ => return Err(HashError::Malformed),
693 }
694 }
695 Ok((
696 mem_cost.ok_or(HashError::Malformed)?,
697 rounds.ok_or(HashError::Malformed)?,
698 ))
699}
700
701#[cfg(test)]
702mod tests {
703 use super::*;
704 use argon2::password_hash::{PasswordHasher, SaltString};
705
706 /// A known-answer vector for a scheme: a password and a hash produced by an
707 /// external implementation of that scheme.
708 fn assert_kat(stored: &str, password: &str, scheme: Scheme) {
709 let parsed = ForeignHash::parse(stored).expect("KAT parses");
710 assert_eq!(parsed.scheme(), scheme, "scheme detected");
711 assert!(
712 parsed.verify(password.as_bytes()),
713 "correct password verifies"
714 );
715 assert!(
716 !parsed.verify(b"definitely-the-wrong-password"),
717 "wrong password rejected"
718 );
719 }
720
721 #[test]
722 fn bcrypt_all_four_variants_verify() {
723 // One bcrypt hash produced by the library at cost 6, replayed under each of
724 // the four version prefixes (they share one verify path), proving the
725 // parser and verifier accept $2a$/$2b$/$2x$/$2y$.
726 let base = bcrypt::hash_with_result("hunter2", 6).expect("bcrypt hash");
727 let body = &base.to_string()[4..]; // strip the "$2b$" the crate emits
728 for prefix in ["$2a$", "$2b$", "$2x$", "$2y$"] {
729 let stored = format!("{prefix}{body}");
730 let parsed = ForeignHash::parse(&stored).unwrap_or_else(|e| panic!("{prefix}: {e}"));
731 assert_eq!(parsed.scheme(), Scheme::Bcrypt);
732 assert_eq!(parsed.tag(), "bcrypt");
733 assert!(parsed.verify(b"hunter2"), "{prefix} verifies");
734 assert!(!parsed.verify(b"wrong"), "{prefix} rejects wrong");
735 }
736 }
737
738 #[test]
739 fn scrypt_round_trip_kat() {
740 use scrypt::password_hash::PasswordHasher;
741 let salt = SaltString::encode_b64(b"scryptsalt00").expect("salt");
742 let hash = scrypt::Scrypt
743 .hash_password(b"correct horse", &salt)
744 .expect("scrypt hash")
745 .to_string();
746 assert_kat(&hash, "correct horse", Scheme::Scrypt);
747 }
748
749 #[test]
750 fn pbkdf2_round_trip_kat() {
751 use pbkdf2::password_hash::PasswordHasher;
752 let salt = SaltString::encode_b64(b"pbkdf2salt00").expect("salt");
753 let hash = pbkdf2::Pbkdf2
754 .hash_password(b"s3cret", &salt)
755 .expect("pbkdf2 hash")
756 .to_string();
757 assert!(hash.starts_with("$pbkdf2-"), "{hash}");
758 assert_kat(&hash, "s3cret", Scheme::Pbkdf2);
759 }
760
761 #[test]
762 fn argon2_round_trip_kat() {
763 let salt = SaltString::encode_b64(b"argon2salt000").expect("salt");
764 let hash = argon2::Argon2::default()
765 .hash_password(b"passw0rd", &salt)
766 .expect("argon2 hash")
767 .to_string();
768 assert!(hash.starts_with("$argon2id$"), "{hash}");
769 assert_kat(&hash, "passw0rd", Scheme::Argon2);
770 }
771
772 #[test]
773 fn firebase_published_known_answer_vector() {
774 // The canonical Firebase modified-scrypt test vector published by Firebase
775 // (github.com/firebase/scrypt): a real cross-implementation KAT.
776 let stored = firebase_stored(
777 14,
778 8,
779 "Bw==",
780 "jxspr8Ki0RYycVU8zykbdLGjFQ3McFUH0uiiTvC8pVMXAn210wjLNmdZJzxUECKbm0QsEmYUSDzZvpjeJ9WmXA==",
781 "42xEC+ixf3L2lw==",
782 "lSrfV15cpx95/sZS2W9c9Kp6i/LVgQNDNC/qzrCnh1SAyZvqmZqAjTdn3aoItz+VHjoZilo78198JAdRuid5lQ==",
783 );
784 let parsed = ForeignHash::parse(&stored).expect("firebase parses");
785 assert_eq!(parsed.scheme(), Scheme::FirebaseScrypt);
786 assert_eq!(parsed.tag(), "firebase-scrypt");
787 assert!(
788 parsed.verify(b"user1password"),
789 "the published Firebase vector verifies"
790 );
791 assert!(!parsed.verify(b"user1passwordX"), "wrong password rejected");
792 }
793
794 #[test]
795 fn unrecognized_and_malformed_are_rejected() {
796 assert_eq!(
797 ForeignHash::parse("not-a-hash").unwrap_err(),
798 HashError::Unrecognized
799 );
800 assert_eq!(
801 ForeignHash::parse("$scrypt$broken").unwrap_err(),
802 HashError::Malformed
803 );
804 assert_eq!(ForeignHash::parse("").unwrap_err(), HashError::Unrecognized);
805 }
806
807 #[test]
808 fn bcrypt_cost_out_of_bounds_is_rejected() {
809 // A cost of 31 (the bcrypt maximum) is far above the documented DoS bound,
810 // so it is rejected at parse with a per-parameter OutOfBounds error.
811 let stored = format!("$2b$31${}", "a".repeat(53));
812 assert_eq!(
813 ForeignHash::parse(&stored).unwrap_err(),
814 HashError::OutOfBounds("bcrypt cost")
815 );
816 }
817
818 #[test]
819 fn pbkdf2_iterations_out_of_bounds_is_rejected() {
820 use pbkdf2::password_hash::PasswordHasher;
821 // Hash at a cheap iteration count, then rewrite only the `i=` parameter to
822 // one above the documented bound: the bounds check parses the parameter and
823 // rejects it WITHOUT running the (expensive) KDF, so the test stays fast.
824 let salt = SaltString::encode_b64(b"pbkdf2salt00").expect("salt");
825 let params = pbkdf2::Params {
826 rounds: 1000,
827 output_length: 32,
828 };
829 let hash = pbkdf2::Pbkdf2
830 .hash_password_customized(
831 b"pw",
832 Some(pbkdf2::Algorithm::Pbkdf2Sha256.ident()),
833 None,
834 params,
835 &salt,
836 )
837 .expect("pbkdf2 hash")
838 .to_string();
839 let over = hash.replace("i=1000,", &format!("i={},", MAX_PBKDF2_ITERATIONS + 1));
840 assert_ne!(over, hash, "the iteration parameter was rewritten");
841 assert_eq!(
842 ForeignHash::parse(&over).unwrap_err(),
843 HashError::OutOfBounds("pbkdf2 iterations")
844 );
845 }
846
847 #[test]
848 fn firebase_mem_cost_out_of_bounds_is_rejected() {
849 let stored = firebase_stored(MAX_FIREBASE_MEM_COST + 1, 8, "Bw==", "AAAA", "AAAA", "AAAA");
850 assert_eq!(
851 ForeignHash::parse(&stored).unwrap_err(),
852 HashError::OutOfBounds("firebase mem_cost")
853 );
854 }
855
856 /// The published SHA-crypt specification vectors (Drepper), asserted as CONSTANTS
857 /// rather than round-tripped through this crate's own hasher.
858 ///
859 /// A round-trip would prove only that the implementation agrees with itself. These
860 /// strings come from the specification that defines the algorithm, so a passing
861 /// assertion is two independent sources agreeing about the same bytes.
862 #[test]
863 fn sha_crypt_published_known_answer_vectors() {
864 for (stored, password) in [
865 (
866 "$5$saltstring$5B8vYYiY.CVt1RlTTf8KbXBH3hsxY/GNooZaBBGWEc5",
867 "Hello world!",
868 ),
869 (
870 "$6$saltstring$svn8UoSVapNtMuq1ukKS4tPQd8iKwSMHWjl/O817G3uBnIFNjnQJue\
871 sI68u4OTLiBFdcbYEdFCoEOfaS35inz1",
872 "Hello world!",
873 ),
874 (
875 "$5$rounds=10000$saltstringsaltst$3xv.VbSHBb41AL9AvLeujZkZRBAwqFMz2.op\
876 qey6IcA",
877 "Hello world!",
878 ),
879 ] {
880 let stored: String = stored.split_whitespace().collect();
881 assert_kat(&stored, password, Scheme::ShaCrypt);
882 }
883 }
884
885 /// The `rounds=` bound, at both ends and in its absence.
886 ///
887 /// Absence is the case worth stating: `$6$salt$hash` is the common `/etc/shadow`
888 /// shape and means the scheme default, so treating a missing parameter as
889 /// malformed would refuse most real rows.
890 #[test]
891 fn sha_crypt_rounds_out_of_bounds_is_rejected_and_absence_is_not() {
892 let over = format!(
893 "$6$rounds={}$saltstring$x",
894 u64::from(MAX_SHA_CRYPT_ROUNDS) + 1
895 );
896 assert_eq!(
897 ForeignHash::parse(&over),
898 Err(HashError::OutOfBounds("sha-crypt rounds")),
899 "a rounds count above the documented bound is minutes of CPU per login"
900 );
901 let under = format!("$6$rounds={}$saltstring$x", MIN_SHA_CRYPT_ROUNDS - 1);
902 assert_eq!(
903 ForeignHash::parse(&under),
904 Err(HashError::OutOfBounds("sha-crypt rounds")),
905 "below the scheme minimum the string is not a SHA-crypt hash"
906 );
907 let at = format!("$6$rounds={MAX_SHA_CRYPT_ROUNDS}$saltstring$x");
908 assert!(
909 ForeignHash::parse(&at).is_ok(),
910 "the bound is inclusive, or an operator's documented maximum is off by one"
911 );
912 assert!(
913 ForeignHash::parse("$6$saltstring$svn8UoSVapNtMuq1ukKS4tPQd8iKwSMHWjl").is_ok(),
914 "an omitted rounds= means the scheme default and must not be malformed"
915 );
916 }
917
918 /// Every LDAP variant, salted and unsalted, against vectors computed OUTSIDE this
919 /// crate (Python `hashlib` and `base64`) so the assertion is not the implementation
920 /// checked against itself.
921 ///
922 /// Each salted variant uses a salt of a DIFFERENT length (2, 10 and 19 bytes), and
923 /// none of them is 8. That is not decoration. The first version of these fixtures
924 /// used one 8-byte salt everywhere, and 8 happens to equal `payload_len` minus the
925 /// SHA-1 digest width, so an implementation taking the width from the PAYLOAD
926 /// rather than from the variant passed every case. A mutation sweep found it. With
927 /// three different lengths no single arithmetic mistake is right for all of them.
928 #[test]
929 fn ldap_digest_known_answer_vectors() {
930 const PASSWORD: &str = "correct horse battery staple";
931 for stored in [
932 "{SHA}q/eq1kOINtvlJqojGr3i0O73TUI=",
933 "{SSHA}fg1cZ6fA9NAz+kgbHLCBGNDXIa5zMw==",
934 "{SHA256}xLvLH77JnWW/WdhcjLYu4tuWPw/hBvSD2a+nO9Tjmoo=",
935 "{SSHA256}rbpZpvJNNYAP5+B0oYnh/gRwFDNi7tgUQ5ydDWrE1vdzYWx0LTEzY2hy",
936 "{SHA512}vl73Z52Iq5qQRfYmflX15XhLS4zXZLXNhVpSRPkcYmlTzUbEPXZohz/W7707IhJJ\
937 MVWAAxljRyoHh4H+BG5irg==",
938 "{SSHA512}JodACNxpTAd0DIaHvcP5uCTsFi8Ofk8+LKZP7HPwd1qWYfjZOyY7mLbLRdPMXheo\
939 d9+qpNFl7/Jgi5pTlPu+dWEtbmluZXRlZW4tYnl0ZS1zbHQ=",
940 ] {
941 let stored: String = stored.split_whitespace().collect();
942 assert_kat(&stored, PASSWORD, Scheme::Ldap);
943 }
944 }
945
946 /// Each variant is read as ITSELF, and the digest boundary comes from the variant.
947 ///
948 /// The tags look like they overlap, and they do not: the closing brace terminates
949 /// each one, so `{SSHA}` cannot prefix `{SSHA256}`. What this pins is the property
950 /// that genuinely can break, which is where the SALT begins. The widths asserted
951 /// here are the scheme's digest widths and the three payloads exceed them by three
952 /// different amounts, so a boundary computed from the payload length is wrong for
953 /// at least two of the three.
954 #[test]
955 fn each_ldap_variant_is_read_as_itself_with_the_scheme_digest_width() {
956 for (stored, digest, salt) in [
957 ("{SSHA}fg1cZ6fA9NAz+kgbHLCBGNDXIa5zMw==", 20, 2),
958 (
959 "{SSHA256}rbpZpvJNNYAP5+B0oYnh/gRwFDNi7tgUQ5ydDWrE1vdzYWx0LTEzY2hy",
960 32,
961 10,
962 ),
963 (
964 "{SSHA512}JodACNxpTAd0DIaHvcP5uCTsFi8Ofk8+LKZP7HPwd1qWYfjZOyY7mLbLRdPM\
965 Xheod9+qpNFl7/Jgi5pTlPu+dWEtbmluZXRlZW4tYnl0ZS1zbHQ=",
966 64,
967 19,
968 ),
969 ] {
970 let stored: String = stored.split_whitespace().collect();
971 let parsed = parse_ldap(&stored).expect("the fixture parses");
972 assert_eq!(
973 (parsed.digest.len(), parsed.salt.len()),
974 (digest, salt),
975 "{stored} split at the wrong boundary"
976 );
977 }
978 }
979
980 /// A salted payload no longer than its digest carries no salt, and is refused at
981 /// IMPORT rather than failing at login where it would look like a wrong password.
982 #[test]
983 fn a_truncated_salted_ldap_payload_is_malformed_not_a_wrong_password() {
984 // A bare 20-byte SHA-1 digest labelled as SALTED SHA-1.
985 let bare = "{SSHA}q/eq1kOINtvlJqojGr3i0O73TUI=";
986 assert_eq!(ForeignHash::parse(bare), Err(HashError::Malformed));
987 // An unsalted variant whose payload is the wrong WIDTH is malformed too.
988 let wrong_width = "{SHA}q/eq1kOINtvlJqojGr3i0O73TUIAAA==";
989 assert_eq!(ForeignHash::parse(wrong_width), Err(HashError::Malformed));
990 }
991
992 /// The MD5 LDAP schemes are deliberately unrecognized, and this is the assertion
993 /// that says so rather than a comment claiming it.
994 #[test]
995 fn the_md5_ldap_schemes_are_not_recognized() {
996 for stored in [
997 "{MD5}X03MO1qnZdYdgyfeuILPmQ==",
998 "{SMD5}X03MO1qnZdYdgyfeuILPmXNhbHQ=",
999 ] {
1000 assert_eq!(
1001 ForeignHash::parse(stored),
1002 Err(HashError::Unrecognized),
1003 "{stored} is not in the issue's scheme list and is not accepted on the \
1004 strength of being easy to add"
1005 );
1006 }
1007 }
1008
1009 /// The LDAP digests, and only they, are reported as urgent to rehash.
1010 ///
1011 /// Asserted over EVERY variant rather than the two that make the point, so a
1012 /// scheme added later cannot inherit `false` by never being listed here.
1013 #[test]
1014 fn only_the_unsalted_digest_schemes_are_urgent_to_rehash() {
1015 let urgent: Vec<&str> = Scheme::ALL
1016 .iter()
1017 .filter(|scheme| scheme.rehash_is_urgent())
1018 .map(|scheme| scheme.tag())
1019 .collect();
1020 assert_eq!(
1021 urgent,
1022 vec!["ldap-digest"],
1023 "the urgent set is stated over EVERY scheme, so a variant added later \
1024 cannot inherit `false` by never being listed"
1025 );
1026 }
1027
1028 #[test]
1029 fn scheme_tag_round_trips() {
1030 for scheme in Scheme::ALL {
1031 assert_eq!(
1032 Scheme::from_tag(scheme.tag()),
1033 Some(scheme),
1034 "{} does not round-trip through its tag, so a stored row of that \
1035 scheme cannot be dispatched after a restart",
1036 scheme.tag()
1037 );
1038 }
1039 assert_eq!(Scheme::from_tag("md5"), None);
1040 // Every tag distinct: two schemes sharing one would round-trip individually
1041 // and still dispatch the second as the first.
1042 let mut tags: Vec<&str> = Scheme::ALL.iter().map(|s| s.tag()).collect();
1043 tags.sort_unstable();
1044 let count = tags.len();
1045 tags.dedup();
1046 assert_eq!(tags.len(), count, "two schemes share an algorithm tag");
1047 }
1048}
1049
1050#[cfg(test)]
1051mod independence {
1052 /// This crate's own manifest, read at COMPILE time so the assertion below cannot be
1053 /// fooled by a working tree that differs from what was built.
1054 const MANIFEST: &str = include_str!("../Cargo.toml");
1055
1056 /// This crate depends on NO ironauth crate, which is the property that lets it publish
1057 /// (issue #55).
1058 ///
1059 /// It is pinned rather than trusted because the failure is silent and one line long. A
1060 /// single `ironauth-store.workspace = true` added here for convenience compiles, tests,
1061 /// and passes every other gate, and the only symptom is that `cargo package` starts
1062 /// failing with `no matching package named ironauth-store found` at the moment somebody
1063 /// tries to release it, which is the worst time to discover it. That is exactly the
1064 /// failure `ironauth-import` has today and the reason this crate was split out of it.
1065 ///
1066 /// The scan is a TEXT scan and its ceiling is worth stating: it reads the `[dependencies]`
1067 /// section of this manifest only, so an ironauth crate reached through a renamed
1068 /// dependency (`foo = { package = "ironauth-store" }`) would slip past the prefix check.
1069 /// It catches the ordinary way this breaks, which is somebody adding the obvious line.
1070 #[test]
1071 fn this_crate_depends_on_no_ironauth_crate() {
1072 // Scoped to the dependency tables, which is what the doc above claims and what the
1073 // first version of this test did NOT do: it scanned the whole file and matched this
1074 // crate's own `name = "ironauth-hash-scheme"`, so it failed on a manifest that was
1075 // correct. A guard that cannot pass on a correct input teaches people to delete it.
1076 let offenders: Vec<&str> = MANIFEST
1077 .lines()
1078 .map(str::trim)
1079 .scan(false, |in_deps, line| {
1080 if line.starts_with('[') {
1081 *in_deps = line.contains("dependencies");
1082 return Some(("", false));
1083 }
1084 Some((line, *in_deps))
1085 })
1086 .filter(|(line, in_deps)| {
1087 *in_deps && !line.starts_with('#') && line.starts_with("ironauth-")
1088 })
1089 .map(|(line, _)| line)
1090 .collect();
1091 assert!(
1092 offenders.is_empty(),
1093 "this crate gained an ironauth dependency, which makes it unpublishable on its \
1094 own and undoes the split issue #55 asked for: {offenders:?}"
1095 );
1096 }
1097}
1098
1099#[cfg(test)]
1100mod publishability {
1101 /// This crate's own manifest, read at compile time.
1102 const MANIFEST: &str = include_str!("../Cargo.toml");
1103
1104 /// The crate depends on NO `ironauth-*` crate.
1105 ///
1106 /// The manifest carries a comment saying this absence is load-bearing and that adding
1107 /// such a dependency "would silently revoke" the crate's ability to be published on its
1108 /// own. Nothing enforced it, so the comment was a promise rather than a property: a
1109 /// single `ironauth-store = { path = ... }` would have made every future
1110 /// `cargo publish` fail, and the first person to find out would have been whoever ran
1111 /// the release.
1112 ///
1113 /// Scanned over the DEPENDENCY sections only, because the comment itself names
1114 /// `ironauth-*` and a scan of the whole file would match its own warning and pass for
1115 /// the wrong reason.
1116 #[test]
1117 fn the_crate_depends_on_no_ironauth_crate() {
1118 let mut in_dependencies = false;
1119 let mut offenders: Vec<&str> = Vec::new();
1120 for line in MANIFEST.lines() {
1121 let trimmed = line.trim();
1122 if trimmed.starts_with('[') {
1123 in_dependencies = trimmed.contains("dependencies");
1124 continue;
1125 }
1126 if !in_dependencies || trimmed.starts_with('#') || trimmed.is_empty() {
1127 continue;
1128 }
1129 if trimmed.starts_with("ironauth-") || trimmed.starts_with("ironauth_") {
1130 offenders.push(trimmed);
1131 }
1132 }
1133 assert!(
1134 offenders.is_empty(),
1135 "this crate gained an ironauth-* dependency, which is what makes it publishable \
1136 on its own. Publishing would now require publishing that crate too, and every \
1137 one below it. Offending entries: {offenders:?}"
1138 );
1139 }
1140
1141 /// The metadata crates.io requires of a published crate is present.
1142 ///
1143 /// Criterion 6 of issue #55 asks the crate to publish "with its own documentation". A
1144 /// missing `readme` is not a build failure and not a publish failure; it is a crate page
1145 /// with no body, discovered after the version is permanent and unyankable into
1146 /// correctness.
1147 #[test]
1148 fn the_publish_metadata_is_present() {
1149 for key in [
1150 "description",
1151 "readme",
1152 "documentation",
1153 "license",
1154 "repository",
1155 ] {
1156 assert!(
1157 MANIFEST
1158 .lines()
1159 .any(|line| line.trim_start().starts_with(key)),
1160 "the manifest is missing `{key}`, which a published crate needs"
1161 );
1162 }
1163 }
1164
1165 /// The description does not promise a capability the crate does not contain.
1166 ///
1167 /// It said "and rehash decisions". There is no rehash logic here and never was: the
1168 /// crate answers whether a password matches, and the policy that decides whether to
1169 /// replace a stored hash lives with the password policy, which this crate cannot see.
1170 /// That string is the single most-read sentence the crate ships, since it is what
1171 /// crates.io lists, and it was wrong.
1172 #[test]
1173 fn the_description_does_not_claim_rehash() {
1174 let description = MANIFEST
1175 .lines()
1176 .find(|line| line.trim_start().starts_with("description"))
1177 .expect("a description");
1178 assert!(
1179 !description.to_ascii_lowercase().contains("rehash"),
1180 "the published description claims rehash decisions this crate does not make: \
1181 {description}"
1182 );
1183 }
1184}