entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
//! Password hashing and verification using Argon2id.
//!
//! Provides a high-level API for securely hashing passwords, verifying them
//! against stored hashes, and serialising/deserialising hashes in the PHC
//! string format.
//!
//! # PHC String Format
//!
//! Hashes are serialised in the standard PHC string format:
//!
//! ```text
//! $argon2id$v=19$m=65536,t=3,p=4$<base64(salt)>$<base64(hash)>
//! ```
//!
//! This format is compatible with the PHC string format specification and
//! allows interoperability with other password hashing libraries.
//!
//! # Security
//!
//! - Passwords are hashed with Argon2id, a memory-hard algorithm resistant
//!   to GPU and ASIC attacks.
//! - Default parameters: 64 MB memory, 3 iterations, 4 parallelism lanes
//!   (per OWASP 2024 recommendations).
//! - Verification uses the constant-time comparison provided by the `argon2`
//!   crate to prevent timing attacks.
//! - Error messages never contain secret material.

use std::fmt;

use argon2::password_hash::{PasswordHasher, PasswordVerifier, SaltString};
use argon2::{Algorithm, Argon2, Params, Version};

use crate::crypto::fill_random;
use crate::util::log::{debug, trace};

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Minimum memory cost in kibibytes (16 MiB).
///
/// This is a safety floor — production deployments should use the default
/// of 64 MiB or higher.
pub const MIN_MEMORY_KIB: u32 = 16_384;

/// Maximum accepted memory cost in kibibytes (4 GiB).
///
/// An upper safety bound: Argon2 allocates this much memory per hash, so a
/// mis-set or untrusted configuration (e.g. `u32::MAX` ≈ 4 TiB) would
/// otherwise OOM the process. Far above any sane production parameter.
pub const MAX_MEMORY_KIB: u32 = 4 * 1024 * 1024;

/// Default memory cost in kibibytes (64 MiB, per OWASP 2024).
const DEFAULT_MEMORY_KIB: u32 = 65_536;

/// Default iteration count for Argon2id.
const DEFAULT_ITERATIONS: u32 = 3;

/// Default parallelism (number of lanes).
const DEFAULT_PARALLELISM: u32 = 4;

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

/// Configuration for Argon2id password hashing operations.
///
/// Controls the memory cost, iteration count, and parallelism. The defaults
/// follow OWASP 2024 recommendations for Argon2id.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PasswordConfig {
    /// Memory cost in kibibytes. Default: 65,536 (64 MiB).
    memory_kib: u32,
    /// Number of iterations (time cost). Default: 3.
    iterations: u32,
    /// Number of parallel lanes. Default: 4.
    parallelism: u32,
}

impl Default for PasswordConfig {
    fn default() -> Self {
        Self {
            memory_kib: DEFAULT_MEMORY_KIB,
            iterations: DEFAULT_ITERATIONS,
            parallelism: DEFAULT_PARALLELISM,
        }
    }
}

impl PasswordConfig {
    /// Creates a new `PasswordConfig` with OWASP-recommended defaults.
    ///
    /// Defaults: 64 MiB memory, 3 iterations, 4 parallelism lanes.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the memory cost in kibibytes.
    ///
    /// Must be between [`MIN_MEMORY_KIB`] (16 MiB) and [`MAX_MEMORY_KIB`]
    /// (4 GiB) inclusive. Out-of-range values are rejected at
    /// hash-generation time.
    #[must_use]
    pub fn with_memory_kib(mut self, memory_kib: u32) -> Self {
        self.memory_kib = memory_kib;
        self
    }

    /// Sets the iteration count (time cost).
    ///
    /// Must be at least 1. A value of 0 is rejected at hash-generation time.
    #[must_use]
    pub fn with_iterations(mut self, iterations: u32) -> Self {
        self.iterations = iterations;
        self
    }

    /// Sets the parallelism (number of lanes).
    ///
    /// Must be at least 1. A value of 0 is rejected at hash-generation time.
    #[must_use]
    pub fn with_parallelism(mut self, parallelism: u32) -> Self {
        self.parallelism = parallelism;
        self
    }

    /// Returns the configured memory cost in kibibytes.
    #[must_use]
    #[inline]
    pub fn memory_kib(&self) -> u32 {
        self.memory_kib
    }

    /// Returns the configured iteration count.
    #[must_use]
    #[inline]
    pub fn iterations(&self) -> u32 {
        self.iterations
    }

    /// Returns the configured parallelism.
    #[must_use]
    #[inline]
    pub fn parallelism(&self) -> u32 {
        self.parallelism
    }
}

// ---------------------------------------------------------------------------
// Password Hash
// ---------------------------------------------------------------------------

/// A password hash in PHC string format.
///
/// Wraps an Argon2id password hash. Supports verification, serialisation to
/// and parsing from the PHC string format:
///
/// ```text
/// $argon2id$v=19$m=65536,t=3,p=4$<base64(salt)>$<base64(hash)>
/// ```
#[derive(Clone)]
pub struct PasswordHash {
    phc_string: String,
}

impl PasswordHash {
    /// Hashes a password with the given configuration.
    ///
    /// Generates a cryptographically random salt and derives a hash using
    /// Argon2id with the configured parameters.
    ///
    /// # Errors
    ///
    /// Returns [`PasswordError`] if the configuration is invalid or the
    /// platform CSPRNG is unavailable.
    pub fn generate(password: &[u8], config: &PasswordConfig) -> Result<Self, PasswordError> {
        if config.memory_kib < MIN_MEMORY_KIB {
            return Err(PasswordError::new(PasswordErrorKind::MemoryTooLow));
        }
        if config.memory_kib > MAX_MEMORY_KIB {
            return Err(PasswordError::new(PasswordErrorKind::MemoryTooHigh));
        }
        if config.iterations == 0 {
            return Err(PasswordError::new(PasswordErrorKind::IterationsTooLow));
        }
        if config.parallelism == 0 {
            return Err(PasswordError::new(PasswordErrorKind::ParallelismTooLow));
        }

        let params = Params::new(
            config.memory_kib,
            config.iterations,
            config.parallelism,
            None,
        )
        .map_err(|_| PasswordError::new(PasswordErrorKind::InvalidParams))?;

        let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);

        // Generate a random salt using our own CSPRNG (avoids needing the
        // `getrandom` feature on `rand_core`). 16 bytes is the standard
        // salt length for Argon2.
        let mut salt_bytes = [0u8; 16];
        fill_random(&mut salt_bytes)
            .map_err(|_| PasswordError::new(PasswordErrorKind::RandomFailure))?;

        // SaltString::encode_b64 converts raw bytes to the PHC b64 encoding
        // expected by the password-hash crate (no padding, standard alphabet).
        let salt = SaltString::encode_b64(&salt_bytes)
            .map_err(|_| PasswordError::new(PasswordErrorKind::RandomFailure))?;

        // SECURITY: Log only non-secret metadata — never the password, salt, or hash.
        trace!(
            memory_kib = config.memory_kib,
            iterations = config.iterations,
            parallelism = config.parallelism,
            "password: starting Argon2id hash"
        );

        let hash = argon2
            .hash_password(password, &salt)
            .map_err(|_| PasswordError::new(PasswordErrorKind::HashingFailed))?;

        debug!(
            memory_kib = config.memory_kib,
            iterations = config.iterations,
            parallelism = config.parallelism,
            "password: hash generated"
        );

        Ok(Self {
            phc_string: hash.to_string(),
        })
    }

    /// Verifies a password against this hash.
    ///
    /// Returns `true` if the password matches, `false` otherwise. The
    /// comparison is performed in constant time by the `argon2` crate.
    // SECURITY: The argon2 crate extracts parameters from the stored PHC
    // string and uses constant-time comparison internally.
    #[must_use]
    pub fn verify(&self, password: &[u8]) -> bool {
        let Ok(parsed) = argon2::PasswordHash::new(&self.phc_string) else {
            debug!("password: verification failed (invalid stored hash)");
            return false;
        };

        // Argon2::default() is fine here — verification extracts params from
        // the stored hash, not from this instance's configuration.
        let result = Argon2::default().verify_password(password, &parsed).is_ok();

        // SECURITY: Log only the outcome — never the password or hash values.
        if result {
            debug!("password: verification succeeded");
        } else {
            debug!("password: verification failed");
        }

        result
    }

    /// Returns the PHC string representation of this hash.
    #[must_use]
    pub fn to_phc_string(&self) -> &str {
        &self.phc_string
    }

    /// Parses a PHC string into a `PasswordHash`.
    ///
    /// # Errors
    ///
    /// Returns [`PasswordError`] if the string format is invalid or the
    /// algorithm identifier is not `argon2id`.
    pub fn parse(s: &str) -> Result<Self, PasswordError> {
        let parsed = argon2::PasswordHash::new(s)
            .map_err(|_| PasswordError::new(PasswordErrorKind::InvalidPhcFormat))?;

        // SECURITY: Only accept Argon2id — reject Argon2d (vulnerable to
        // side-channel attacks) and Argon2i (weaker against GPU attacks).
        if parsed.algorithm != argon2::ARGON2ID_IDENT {
            return Err(PasswordError::new(PasswordErrorKind::UnsupportedAlgorithm));
        }

        Ok(Self {
            phc_string: s.to_owned(),
        })
    }

    /// Returns `true` if this hash should be re-derived with the given config.
    ///
    /// A rehash is needed when any stored parameter (memory, iterations, or
    /// parallelism) is weaker than the current configuration requires.
    #[must_use]
    pub fn needs_rehash(&self, config: &PasswordConfig) -> bool {
        let Ok(parsed) = argon2::PasswordHash::new(&self.phc_string) else {
            return true;
        };

        let Ok(params) = Params::try_from(&parsed) else {
            return true;
        };

        // A hash produced by an older Argon2 version (V0x10) must be upgraded
        // to the one we hash with today (V0x13), independent of cost params.
        // A missing version field is treated as stale.
        let latest_version = Version::V0x13 as u32;
        if parsed.version.is_none_or(|v| v < latest_version) {
            return true;
        }

        params.m_cost() < config.memory_kib
            || params.t_cost() < config.iterations
            || params.p_cost() < config.parallelism
    }
}

// SECURITY: Debug output redacts the hash value to prevent accidental
// exposure in logs or error messages.
impl fmt::Debug for PasswordHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PasswordHash")
            .field("phc_string", &"[HASH]")
            .finish()
    }
}

// ---------------------------------------------------------------------------
// Error Type
// ---------------------------------------------------------------------------

/// Kinds of password errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PasswordErrorKind {
    /// The memory cost is below the minimum.
    MemoryTooLow,
    /// The memory cost exceeds the maximum safety bound.
    MemoryTooHigh,
    /// The iteration count is zero.
    IterationsTooLow,
    /// The parallelism is zero.
    ParallelismTooLow,
    /// The parameter combination is invalid.
    InvalidParams,
    /// The platform CSPRNG is unavailable.
    RandomFailure,
    /// The hashing operation failed.
    HashingFailed,
    /// The PHC string format is invalid.
    InvalidPhcFormat,
    /// The algorithm identifier is not supported.
    UnsupportedAlgorithm,
}

/// Error returned by password hashing operations.
///
/// Error messages never contain secret material (passwords, hashes, salts).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PasswordError {
    kind: PasswordErrorKind,
}

impl PasswordError {
    const fn new(kind: PasswordErrorKind) -> Self {
        Self { kind }
    }
}

impl fmt::Display for PasswordError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.kind {
            PasswordErrorKind::MemoryTooLow => {
                write!(
                    f,
                    "password: memory cost below minimum ({MIN_MEMORY_KIB} KiB)"
                )
            }
            PasswordErrorKind::MemoryTooHigh => {
                write!(
                    f,
                    "password: memory cost above maximum ({MAX_MEMORY_KIB} KiB)"
                )
            }
            PasswordErrorKind::IterationsTooLow => {
                write!(f, "password: iteration count must be at least 1")
            }
            PasswordErrorKind::ParallelismTooLow => {
                write!(f, "password: parallelism must be at least 1")
            }
            PasswordErrorKind::InvalidParams => {
                write!(f, "password: invalid parameter combination")
            }
            PasswordErrorKind::RandomFailure => {
                write!(f, "password: random number generation failed")
            }
            PasswordErrorKind::HashingFailed => {
                write!(f, "password: hashing operation failed")
            }
            PasswordErrorKind::InvalidPhcFormat => {
                write!(f, "password: invalid PHC string format")
            }
            PasswordErrorKind::UnsupportedAlgorithm => {
                write!(f, "password: unsupported algorithm (expected argon2id)")
            }
        }
    }
}

impl std::error::Error for PasswordError {}

// ---------------------------------------------------------------------------
// Enumeration-resistant verification
// ---------------------------------------------------------------------------

/// Returns a process-wide dummy Argon2id hash (default parameters) used to
/// equalize verification timing when a user does not exist. Built once and
/// reused; the value is never compared for equality.
///
/// Returns `None` if generation fails — its only fallible step is drawing a
/// random salt, so this happens only when the platform CSPRNG is unavailable.
/// Rather than panic on the authentication hot path, the caller degrades to
/// returning `false` without the timing-equalization work.
fn dummy_password_hash() -> Option<&'static PasswordHash> {
    static DUMMY: std::sync::OnceLock<Option<PasswordHash>> = std::sync::OnceLock::new();
    DUMMY
        .get_or_init(|| {
            PasswordHash::generate(
                b"entropy-auth-enumeration-guard",
                &PasswordConfig::default(),
            )
            .ok()
        })
        .as_ref()
}

/// Verifies `password` against an optional stored hash without revealing,
/// through timing, whether the hash exists.
///
/// Returns `true` only when `stored` is `Some` and the password matches. When
/// `stored` is `None` (no such user) this still performs one Argon2id
/// verification — against an internal dummy hash — before returning `false`,
/// so a "user not found" response costs the same as a "wrong password" one.
/// This is the timing complement to [`AuthError::is_invalid_credentials`](crate::provider::AuthError::is_invalid_credentials),
/// which hides the *reason* in the error value; use this for the verification
/// step itself rather than a naive `match`/early-return that returns instantly
/// for an absent user and leaks username existence.
///
/// # Security
///
/// The timing equalization is exact only when stored hashes use the same
/// Argon2 parameters as [`PasswordConfig::default`] (the dummy's cost). A
/// deployment using heavier custom parameters narrows but does not fully close
/// the gap; such deployments should keep their parameters at or near the
/// defaults, or verify against their own equally-costed dummy.
///
/// # Examples
///
/// ```
/// use entropy_auth::{verify_credential, PasswordHash, PasswordConfig};
///
/// let stored = PasswordHash::generate(b"correct horse", &PasswordConfig::default()).unwrap();
///
/// assert!(verify_credential(Some(&stored), b"correct horse"));
/// assert!(!verify_credential(Some(&stored), b"wrong"));
/// // Absent user: still spends one Argon2id verification, returns false.
/// assert!(!verify_credential(None, b"anything"));
/// ```
#[must_use]
pub fn verify_credential(stored: Option<&PasswordHash>, password: &[u8]) -> bool {
    if let Some(hash) = stored {
        hash.verify(password)
    } else {
        // SECURITY: spend the same Argon2id work as the user-found path and
        // discard the result, so the absent-user branch is timing-
        // indistinguishable from a wrong-password branch. If the dummy hash
        // could not be built (CSPRNG unavailable), skip the work rather than
        // panic — a degraded timing signal beats crashing the auth path.
        if let Some(dummy) = dummy_password_hash() {
            let _ = dummy.verify(password);
        }
        false
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    /// Test-only configuration with minimum parameters for speed.
    fn test_config() -> PasswordConfig {
        PasswordConfig::new()
            .with_memory_kib(MIN_MEMORY_KIB)
            .with_iterations(1)
            .with_parallelism(1)
    }

    // --- Generate and Verify ---

    #[test]
    fn generate_and_verify_round_trip() {
        let config = test_config();
        let hash = PasswordHash::generate(b"correct-password", &config).unwrap();
        assert!(hash.verify(b"correct-password"));
    }

    #[test]
    fn verify_rejects_wrong_password() {
        let config = test_config();
        let hash = PasswordHash::generate(b"correct-password", &config).unwrap();
        assert!(!hash.verify(b"wrong-password"));
    }

    #[test]
    fn verify_rejects_empty_password_when_original_not_empty() {
        let config = test_config();
        let hash = PasswordHash::generate(b"some-password", &config).unwrap();
        assert!(!hash.verify(b""));
    }

    #[test]
    fn generate_empty_password_accepted() {
        let config = test_config();
        let hash = PasswordHash::generate(b"", &config).unwrap();
        assert!(hash.verify(b""));
        assert!(!hash.verify(b"not-empty"));
    }

    // --- PHC String Round-Trip ---

    #[test]
    fn phc_string_round_trip() {
        let config = test_config();
        let hash = PasswordHash::generate(b"my-password", &config).unwrap();
        let phc = hash.to_phc_string();
        let parsed = PasswordHash::parse(phc).unwrap();
        assert_eq!(hash.to_phc_string(), parsed.to_phc_string());
    }

    #[test]
    fn phc_string_format() {
        let config = test_config();
        let hash = PasswordHash::generate(b"test", &config).unwrap();
        let phc = hash.to_phc_string();
        assert!(
            phc.starts_with("$argon2id$"),
            "PHC should start with algorithm: {phc}"
        );
    }

    #[test]
    fn parsed_hash_verifies_password() {
        let config = test_config();
        let hash = PasswordHash::generate(b"round-trip-verify", &config).unwrap();
        let phc = hash.to_phc_string();
        let parsed = PasswordHash::parse(phc).unwrap();
        assert!(parsed.verify(b"round-trip-verify"));
        assert!(!parsed.verify(b"wrong"));
    }

    // --- Parse Errors ---

    #[test]
    fn parse_rejects_empty_string() {
        assert_eq!(
            PasswordHash::parse("").unwrap_err(),
            PasswordError::new(PasswordErrorKind::InvalidPhcFormat),
        );
    }

    #[test]
    fn parse_rejects_unparseable_non_argon2_phc() {
        // A PHC string whose algorithm ident the argon2 parser does not
        // recognise (e.g. `pbkdf2-sha512`) fails to parse outright, before
        // the argon2id-only algorithm check — yielding `InvalidPhcFormat`.
        // (The parseable-but-wrong-algorithm path is covered by
        // `parse_rejects_argon2d`/`parse_rejects_argon2i`.)
        assert_eq!(
            PasswordHash::parse("$pbkdf2-sha512$100000$c2FsdA==$aGFzaA==").unwrap_err(),
            PasswordError::new(PasswordErrorKind::InvalidPhcFormat),
        );
    }

    #[test]
    fn parse_rejects_argon2d() {
        // Argon2d is vulnerable to side-channel attacks — only Argon2id is accepted.
        let config = test_config();
        let hash = PasswordHash::generate(b"test", &config).unwrap();
        let phc = hash.to_phc_string().replace("argon2id", "argon2d");
        assert_eq!(
            PasswordHash::parse(&phc).unwrap_err(),
            PasswordError::new(PasswordErrorKind::UnsupportedAlgorithm),
        );
    }

    #[test]
    fn parse_rejects_argon2i() {
        // Argon2i (data-independent) is weaker against GPU attacks than the
        // hybrid Argon2id — it parses as a valid argon2 ident but must be
        // rejected by the algorithm check, not the format check.
        let config = test_config();
        let hash = PasswordHash::generate(b"test", &config).unwrap();
        let phc = hash.to_phc_string().replace("argon2id", "argon2i");
        assert_eq!(
            PasswordHash::parse(&phc).unwrap_err(),
            PasswordError::new(PasswordErrorKind::UnsupportedAlgorithm),
        );
    }

    #[test]
    fn parse_rejects_garbage() {
        assert_eq!(
            PasswordHash::parse("not-a-hash").unwrap_err(),
            PasswordError::new(PasswordErrorKind::InvalidPhcFormat),
        );
    }

    // --- Needs Rehash ---

    #[test]
    fn needs_rehash_detects_weak_memory() {
        let weak_config = test_config();
        let hash = PasswordHash::generate(b"test", &weak_config).unwrap();

        let strong_config = PasswordConfig::new()
            .with_memory_kib(DEFAULT_MEMORY_KIB)
            .with_iterations(1)
            .with_parallelism(1);
        assert!(hash.needs_rehash(&strong_config));
    }

    #[test]
    fn needs_rehash_detects_weak_iterations() {
        let config = test_config();
        let hash = PasswordHash::generate(b"test", &config).unwrap();

        let stronger = PasswordConfig::new()
            .with_memory_kib(MIN_MEMORY_KIB)
            .with_iterations(3)
            .with_parallelism(1);
        assert!(hash.needs_rehash(&stronger));
    }

    #[test]
    fn needs_rehash_detects_weak_parallelism() {
        let config = test_config();
        let hash = PasswordHash::generate(b"test", &config).unwrap();

        let stronger = PasswordConfig::new()
            .with_memory_kib(MIN_MEMORY_KIB)
            .with_iterations(1)
            .with_parallelism(4);
        assert!(hash.needs_rehash(&stronger));
    }

    #[test]
    fn needs_rehash_false_when_current() {
        let config = test_config();
        let hash = PasswordHash::generate(b"test", &config).unwrap();
        assert!(!hash.needs_rehash(&config));
    }

    // --- Configuration Errors ---

    #[test]
    fn generate_rejects_low_memory() {
        let config = PasswordConfig::new()
            .with_memory_kib(MIN_MEMORY_KIB - 1)
            .with_iterations(1)
            .with_parallelism(1);
        assert_eq!(
            PasswordHash::generate(b"test", &config).unwrap_err(),
            PasswordError::new(PasswordErrorKind::MemoryTooLow),
        );
    }

    #[test]
    fn generate_rejects_excessive_memory() {
        let config = PasswordConfig::new().with_memory_kib(MAX_MEMORY_KIB + 1);
        assert_eq!(
            PasswordHash::generate(b"test", &config).unwrap_err(),
            PasswordError::new(PasswordErrorKind::MemoryTooHigh),
        );
    }

    #[test]
    fn verify_credential_equalizes_absent_user() {
        let stored = PasswordHash::generate(b"correct", &PasswordConfig::default()).unwrap();
        // Present user: correct/incorrect password resolve as expected.
        assert!(verify_credential(Some(&stored), b"correct"));
        assert!(!verify_credential(Some(&stored), b"wrong"));
        // Absent user: returns false but still ran a (discarded) verification.
        assert!(!verify_credential(None, b"anything"));
    }

    #[test]
    fn generate_rejects_zero_iterations() {
        let config = PasswordConfig::new()
            .with_memory_kib(MIN_MEMORY_KIB)
            .with_iterations(0)
            .with_parallelism(1);
        assert_eq!(
            PasswordHash::generate(b"test", &config).unwrap_err(),
            PasswordError::new(PasswordErrorKind::IterationsTooLow),
        );
    }

    #[test]
    fn generate_rejects_zero_parallelism() {
        let config = PasswordConfig::new()
            .with_memory_kib(MIN_MEMORY_KIB)
            .with_iterations(1)
            .with_parallelism(0);
        assert_eq!(
            PasswordHash::generate(b"test", &config).unwrap_err(),
            PasswordError::new(PasswordErrorKind::ParallelismTooLow),
        );
    }

    // --- Error Display ---

    #[test]
    fn error_display_no_secrets() {
        let errors = [
            PasswordError::new(PasswordErrorKind::MemoryTooLow),
            PasswordError::new(PasswordErrorKind::IterationsTooLow),
            PasswordError::new(PasswordErrorKind::ParallelismTooLow),
            PasswordError::new(PasswordErrorKind::InvalidParams),
            PasswordError::new(PasswordErrorKind::RandomFailure),
            PasswordError::new(PasswordErrorKind::HashingFailed),
            PasswordError::new(PasswordErrorKind::InvalidPhcFormat),
            PasswordError::new(PasswordErrorKind::UnsupportedAlgorithm),
        ];
        for err in &errors {
            let msg = err.to_string();
            assert!(
                msg.starts_with("password:"),
                "error should be prefixed: {msg}"
            );
            // SECURITY: Verify no secret material leaks into error messages.
            assert!(
                !msg.contains("secret") && !msg.contains("token"),
                "error must not leak secret material: {msg}",
            );
        }
    }

    #[test]
    fn error_implements_std_error() {
        let err: Box<dyn std::error::Error> =
            Box::new(PasswordError::new(PasswordErrorKind::InvalidPhcFormat));
        let _ = err.to_string();
    }

    // --- Default Config ---

    #[test]
    fn default_config_uses_recommended_values() {
        let config = PasswordConfig::default();
        assert_eq!(config.memory_kib(), DEFAULT_MEMORY_KIB);
        assert_eq!(config.iterations(), DEFAULT_ITERATIONS);
        assert_eq!(config.parallelism(), DEFAULT_PARALLELISM);
    }

    // --- Config Builder ---

    #[test]
    fn config_builder_pattern() {
        let config = PasswordConfig::new()
            .with_memory_kib(32_768)
            .with_iterations(2)
            .with_parallelism(8);
        assert_eq!(config.memory_kib(), 32_768);
        assert_eq!(config.iterations(), 2);
        assert_eq!(config.parallelism(), 8);
    }

    // --- Debug Redaction ---

    #[test]
    fn debug_redacts_hash() {
        let config = test_config();
        let hash = PasswordHash::generate(b"test", &config).unwrap();
        let debug = format!("{hash:?}");
        assert!(debug.contains("[HASH]"), "debug should redact: {debug}");
        assert!(
            !debug.contains("argon2id"),
            "debug should not contain hash value: {debug}"
        );
    }
}