footing 0.6.1

Feature-gated foundations for Rust backend services
Documentation
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
//! Password storage security built around PHC-formatted Argon2id hashes.
//!
//! `PasswordService` owns algorithm selection, parameter profile, password
//! input and resource limits, verification, and rehash assessment. It does not
//! enforce new-password admission rules. Applications should validate a new
//! password before hashing it; login and rehashing remain independent of those
//! rules and operate on the original password bytes.
//!
//! ```rust
//! use footing::auth::PasswordService;
//!
//! let service = PasswordService::new();
//! let stored_hash = service.hash_password("correct horse battery staple").unwrap();
//! let verification = service
//!     .verify_and_assess("correct horse battery staple", &stored_hash)
//!     .unwrap();
//!
//! assert!(verification.verified());
//! if verification.needs_rehash() {
//!     let upgraded_hash = service.hash_password("correct horse battery staple").unwrap();
//!     assert_ne!(stored_hash, upgraded_hash);
//! }
//! ```
//!
use argon2::{
    Algorithm, Argon2, Params, PasswordHash, PasswordHasher as Argon2PasswordHasher,
    PasswordVerifier as _, Version,
    password_hash::{Error as PasswordHashError, phc::Output},
};
use thiserror::Error;

use crate::result::{ClassifyError, ErrorKind};

/// Default maximum accepted password length in bytes.
pub const DEFAULT_MAX_PASSWORD_BYTES: usize = 1024;
/// Default Argon2id memory cost in KiB.
pub const DEFAULT_ARGON2ID_MEMORY_COST_KIB: u32 = 19 * 1024;
/// Default Argon2id iteration count.
pub const DEFAULT_ARGON2ID_TIME_COST: u32 = 2;
/// Default Argon2id degree of parallelism.
pub const DEFAULT_ARGON2ID_PARALLELISM: u32 = 1;
/// Default Argon2id output length in bytes.
pub const DEFAULT_ARGON2ID_OUTPUT_BYTES: usize = 32;
/// Numeric representation of Argon2 version 1.3.
pub const ARGON2_VERSION_13: u32 = 0x13;

// This stable, non-secret value makes the dummy hash reusable across service
// instances without coupling the library to any consuming application.
const DUMMY_PASSWORD_SALT: &[u8] = b"password-enumeration-timing-guard";

#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
/// Errors from password storage limits, hashing, and verification.
pub enum PasswordError {
    #[error("password must not exceed {max} bytes")]
    /// The password exceeds the supported length.
    PasswordTooLong {
        #[doc = "The configured upper bound."]
        max: usize,
    },
    #[error("password limits are invalid")]
    /// The password input or verification resource limits are invalid.
    InvalidPasswordLimits,
    #[error("password hash profile is invalid")]
    /// The password hash profile is invalid.
    InvalidPasswordHashProfile,
    #[error("password hash failed")]
    /// Computing a password hash failed.
    HashFailed,
    #[error("password hash is invalid")]
    /// The password hash is invalid.
    InvalidPasswordHash,
    #[error("password hash algorithm or version is unsupported")]
    /// The password hash algorithm or version is unsupported.
    UnsupportedPasswordHash,
    #[error("password verification failed")]
    /// Password verification failed unexpectedly.
    VerificationFailed,
    #[error("password verification {parameter} {actual} exceeds the configured limit {max}")]
    /// The stored hash requires more resources than the verification limits permit.
    VerificationCostExceeded {
        /// Cost name: `memory_cost_kib`, `time_cost`, or `parallelism`.
        parameter: &'static str,
        /// Cost requested by the stored hash.
        actual: u32,
        /// Configured inclusive upper bound.
        max: u32,
    },
}

impl ClassifyError for PasswordError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::PasswordTooLong { .. }
            | Self::InvalidPasswordLimits
            | Self::InvalidPasswordHashProfile
            | Self::InvalidPasswordHash
            | Self::UnsupportedPasswordHash
            | Self::VerificationCostExceeded { .. } => ErrorKind::Validation,
            Self::HashFailed | Self::VerificationFailed => ErrorKind::Internal,
        }
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::PasswordTooLong { .. } => "password_too_long",
            Self::InvalidPasswordLimits => "invalid_password_limits",
            Self::InvalidPasswordHashProfile => "invalid_password_hash_profile",
            Self::HashFailed => "password_hash_failed",
            Self::InvalidPasswordHash => "invalid_password_hash",
            Self::UnsupportedPasswordHash => "unsupported_password_hash",
            Self::VerificationFailed => "password_verification_failed",
            Self::VerificationCostExceeded { .. } => "password_verification_cost_exceeded",
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Input byte and optional verification resource limits for password storage.
///
/// These limits apply to hashing and verification. They do not determine
/// whether a new password is acceptable: configure admission rules separately
/// and apply them only when setting, changing, or resetting a password.
pub struct PasswordLimits {
    max_password_bytes: usize,
    verification_limits: Option<PasswordVerificationLimits>,
}

impl PasswordLimits {
    /// Sets a nonzero maximum input length in UTF-8 bytes.
    ///
    /// Unlike a minimum character count for new passwords, this bounds input
    /// size for every hashing and verification operation.
    pub const fn new(max_password_bytes: usize) -> Result<Self, PasswordError> {
        if max_password_bytes == 0 {
            return Err(PasswordError::InvalidPasswordLimits);
        }

        Ok(Self {
            max_password_bytes,
            verification_limits: None,
        })
    }

    #[must_use]
    /// Returns the maximum password bytes.
    pub const fn max_password_bytes(&self) -> usize {
        self.max_password_bytes
    }

    /// Sets inclusive cost limits for verifying stored Argon2 hashes.
    ///
    /// `None` preserves unrestricted verification of supported legacy costs.
    /// Limits do not change hash generation, assessment, or the rehash policy.
    /// Configure them independently of the generation profile, allowing for
    /// legitimate historical hashes that use higher costs. Include the current
    /// profile if this service must also verify its newly generated hashes.
    #[must_use]
    pub const fn with_verification_limits(
        mut self,
        limits: Option<PasswordVerificationLimits>,
    ) -> Self {
        self.verification_limits = limits;
        self
    }

    /// Returns the verification cost limits, absent by default.
    #[must_use]
    pub const fn verification_limits(&self) -> Option<PasswordVerificationLimits> {
        self.verification_limits
    }

    pub(super) fn validate_password(self, password: &str) -> Result<(), PasswordError> {
        if password.len() > self.max_password_bytes {
            return Err(PasswordError::PasswordTooLong {
                max: self.max_password_bytes,
            });
        }

        Ok(())
    }
}

impl Default for PasswordLimits {
    fn default() -> Self {
        Self {
            max_password_bytes: DEFAULT_MAX_PASSWORD_BYTES,
            verification_limits: None,
        }
    }
}

/// Inclusive upper bounds on the costs encoded in a stored Argon2 hash.
///
/// These bound one verification's parameters, not elapsed time or concurrent
/// work. Choose them for the service's resource budget and accepted historical
/// hashes; no limits are enabled by default. They are independent maxima, so
/// they need not describe a valid hash profile when combined.
///
/// ```rust
/// use footing::auth::{PasswordLimits, PasswordService, PasswordVerificationLimits};
///
/// let verification = PasswordVerificationLimits::new(64 * 1024, 4, 4)?;
/// let limits = PasswordLimits::default().with_verification_limits(Some(verification));
/// let service = PasswordService::new().with_limits(limits);
/// # let _ = service;
/// # Ok::<(), footing::auth::PasswordError>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PasswordVerificationLimits {
    max_memory_cost_kib: u32,
    max_time_cost: u32,
    max_parallelism: u32,
}

impl PasswordVerificationLimits {
    /// Creates limits that permit at least the minimum valid Argon2 costs.
    pub const fn new(
        max_memory_cost_kib: u32,
        max_time_cost: u32,
        max_parallelism: u32,
    ) -> Result<Self, PasswordError> {
        if max_memory_cost_kib < Params::MIN_M_COST
            || max_time_cost < Params::MIN_T_COST
            || max_parallelism < Params::MIN_P_COST
        {
            return Err(PasswordError::InvalidPasswordLimits);
        }
        Ok(Self {
            max_memory_cost_kib,
            max_time_cost,
            max_parallelism,
        })
    }

    /// Maximum memory cost in KiB.
    #[must_use]
    pub const fn max_memory_cost_kib(&self) -> u32 {
        self.max_memory_cost_kib
    }

    /// Maximum number of passes over memory.
    #[must_use]
    pub const fn max_time_cost(&self) -> u32 {
        self.max_time_cost
    }

    /// Maximum number of Argon2 lanes.
    #[must_use]
    pub const fn max_parallelism(&self) -> u32 {
        self.max_parallelism
    }

    fn validate(self, metadata: PasswordHashMetadata) -> Result<(), PasswordError> {
        // Metadata uses the verifier's own Params parser. Invalid parameters
        // have no costs here and are rejected by the verifier.
        for (parameter, actual, max) in [
            (
                "memory_cost_kib",
                metadata.memory_cost_kib,
                self.max_memory_cost_kib,
            ),
            ("time_cost", metadata.time_cost, self.max_time_cost),
            ("parallelism", metadata.parallelism, self.max_parallelism),
        ] {
            if let Some(actual) = actual
                && actual > max
            {
                return Err(PasswordError::VerificationCostExceeded {
                    parameter,
                    actual,
                    max,
                });
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Represents Argon2id profile.
pub struct Argon2idProfile {
    memory_cost_kib: u32,
    time_cost: u32,
    parallelism: u32,
    output_bytes: usize,
}

impl Argon2idProfile {
    /// Validates Argon2 costs and the PHC format's supported output length.
    pub const fn new(
        memory_cost_kib: u32,
        time_cost: u32,
        parallelism: u32,
        output_bytes: usize,
    ) -> Result<Self, PasswordError> {
        if output_bytes < Output::MIN_LENGTH
            || output_bytes > Output::MAX_LENGTH
            || Params::new(memory_cost_kib, time_cost, parallelism, Some(output_bytes)).is_err()
        {
            return Err(PasswordError::InvalidPasswordHashProfile);
        }

        Ok(Self {
            memory_cost_kib,
            time_cost,
            parallelism,
            output_bytes,
        })
    }

    #[must_use]
    /// Returns the OWASP minimum Argon2id cost profile.
    pub const fn owasp_minimum() -> Self {
        Self {
            memory_cost_kib: DEFAULT_ARGON2ID_MEMORY_COST_KIB,
            time_cost: DEFAULT_ARGON2ID_TIME_COST,
            parallelism: DEFAULT_ARGON2ID_PARALLELISM,
            output_bytes: DEFAULT_ARGON2ID_OUTPUT_BYTES,
        }
    }

    #[must_use]
    /// Returns the memory cost KiB.
    pub const fn memory_cost_kib(&self) -> u32 {
        self.memory_cost_kib
    }

    #[must_use]
    /// Returns the time cost.
    pub const fn time_cost(&self) -> u32 {
        self.time_cost
    }

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

    #[must_use]
    /// Returns the output bytes.
    pub const fn output_bytes(&self) -> usize {
        self.output_bytes
    }

    fn params(self) -> Result<Params, PasswordError> {
        Params::new(
            self.memory_cost_kib,
            self.time_cost,
            self.parallelism,
            Some(self.output_bytes),
        )
        .map_err(|_| PasswordError::InvalidPasswordHashProfile)
    }
}

impl Default for Argon2idProfile {
    fn default() -> Self {
        Self::owasp_minimum()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// Enumerates the supported password hash algorithm values.
pub enum PasswordHashAlgorithm {
    /// Indicates Argon2d.
    Argon2d,
    /// Indicates Argon2i.
    Argon2i,
    /// Indicates Argon2id.
    Argon2id,
    /// The value is unknown.
    Unknown,
}

impl PasswordHashAlgorithm {
    #[must_use]
    /// Returns whether this value is Argon2id.
    pub const fn is_argon2id(self) -> bool {
        matches!(self, Self::Argon2id)
    }

    fn from_identifier(identifier: &str) -> Self {
        match identifier {
            "argon2d" => Self::Argon2d,
            "argon2i" => Self::Argon2i,
            "argon2id" => Self::Argon2id,
            _ => Self::Unknown,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Represents password hash metadata.
pub struct PasswordHashMetadata {
    algorithm: PasswordHashAlgorithm,
    version: Option<u32>,
    memory_cost_kib: Option<u32>,
    time_cost: Option<u32>,
    parallelism: Option<u32>,
    output_bytes: Option<usize>,
}

impl PasswordHashMetadata {
    #[must_use]
    /// Returns the algorithm.
    pub const fn algorithm(&self) -> PasswordHashAlgorithm {
        self.algorithm
    }

    #[must_use]
    /// Returns the version.
    pub const fn version(&self) -> Option<u32> {
        self.version
    }

    #[must_use]
    /// Returns the memory cost KiB.
    pub const fn memory_cost_kib(&self) -> Option<u32> {
        self.memory_cost_kib
    }

    #[must_use]
    /// Returns the time cost.
    pub const fn time_cost(&self) -> Option<u32> {
        self.time_cost
    }

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

    #[must_use]
    /// Returns the output bytes.
    pub const fn output_bytes(&self) -> Option<usize> {
        self.output_bytes
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Represents password hash assessment.
pub struct PasswordHashAssessment {
    metadata: PasswordHashMetadata,
    needs_rehash: bool,
}

impl PasswordHashAssessment {
    #[must_use]
    /// Returns the metadata.
    pub const fn metadata(&self) -> PasswordHashMetadata {
        self.metadata
    }

    #[must_use]
    /// Returns the needs rehash.
    pub const fn needs_rehash(&self) -> bool {
        self.needs_rehash
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Represents password verification.
pub struct PasswordVerification {
    assessment: PasswordHashAssessment,
    verified: bool,
}

impl PasswordVerification {
    #[must_use]
    /// Returns the verified.
    pub const fn verified(&self) -> bool {
        self.verified
    }

    #[must_use]
    /// Returns the needs rehash.
    pub const fn needs_rehash(&self) -> bool {
        self.verified && self.assessment.needs_rehash
    }

    #[must_use]
    /// Returns the assessment.
    pub const fn assessment(&self) -> PasswordHashAssessment {
        self.assessment
    }
}

#[derive(Debug, Clone, Default)]
/// Synchronous password hashing, verification, and rehash assessment.
///
/// This service enforces [`PasswordLimits`] and hashes the original UTF-8 bytes.
/// It does not check password strength or blocklists. Apply admission rules
/// before setting, changing, or resetting a password; do not apply them during
/// login or rehashing, so rule changes cannot invalidate existing credentials.
///
/// For Tokio servers, enable `password-tokio` and use
/// `footing::auth::TokioPasswordService` to share bounded blocking execution,
/// queued admission, rehashing and dummy verification across handlers.
/// The `password` feature itself does not depend on an async runtime.
///
/// Other executors should run these CPU- and memory-intensive operations on a
/// blocking pool. Acquire a shared concurrency permit before submission and
/// retain it until the computation finishes, including after caller cancellation.
/// Bound waiting callers separately. Verification and rehashing should share
/// one permit; persist a replacement only after successful verification, using a
/// conditional update against the verified hash. Do not hold a database
/// transaction or application lock while waiting or hashing.
pub struct PasswordService {
    profile: Argon2idProfile,
    limits: PasswordLimits,
}

impl PasswordService {
    #[must_use]
    /// Creates a new instance.
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    /// Sets the input byte and verification resource limits.
    pub fn with_limits(mut self, limits: PasswordLimits) -> Self {
        self.limits = limits;
        self
    }

    #[must_use]
    /// Configures profile and returns the updated value.
    pub fn with_profile(mut self, profile: Argon2idProfile) -> Self {
        self.profile = profile;
        self
    }

    #[must_use]
    /// Returns the input byte and verification resource limits.
    pub const fn limits(&self) -> PasswordLimits {
        self.limits
    }

    #[must_use]
    /// Returns the profile.
    pub const fn profile(&self) -> Argon2idProfile {
        self.profile
    }

    /// Hashes the original password bytes, subject to the input byte limit.
    ///
    /// This does not evaluate new-password admission rules.
    pub fn hash_password(&self, password: &str) -> Result<String, PasswordError> {
        self.limits.validate_password(password)?;

        self.argon2()?
            .hash_password(password.as_bytes())
            .map(|hash| hash.to_string())
            .map_err(|_| PasswordError::HashFailed)
    }

    /// Builds a reusable hash for authentication timing equalization.
    ///
    /// The fixed salt is intentional: this hash is never persisted or used as
    /// a credential. Reusing it avoids generating a new Argon2 hash for every
    /// unknown login identifier while retaining this service's exact cost
    /// profile during verification.
    pub fn dummy_password_hash(&self) -> Result<String, PasswordError> {
        self.argon2()?
            .hash_password_with_salt(b"", DUMMY_PASSWORD_SALT)
            .map(|hash| hash.to_string())
            .map_err(|_| PasswordError::HashFailed)
    }

    /// Verifies a password against a complete, supported stored hash.
    ///
    /// Returns `false` only when the password does not match. Malformed hashes,
    /// unsupported algorithms or versions, and verification failures are errors.
    pub fn verify_password(
        &self,
        password: &str,
        password_hash: &str,
    ) -> Result<bool, PasswordError> {
        self.verify_and_assess(password, password_hash)
            .map(|verification| verification.verified())
    }

    /// Verifies a stored hash and assesses whether it needs rehashing.
    ///
    /// If configured, verification cost limits are checked before Argon2 runs.
    /// Exceeding them returns a resource-limit error, not a password mismatch.
    /// The generation profile does not constrain the supported costs of
    /// historical hashes. A successful result with `verified() == false` means
    /// only a password mismatch; invalid or unsupported stored hashes are errors.
    pub fn verify_and_assess(
        &self,
        password: &str,
        password_hash: &str,
    ) -> Result<PasswordVerification, PasswordError> {
        self.limits.validate_password(password)?;

        let parsed =
            PasswordHash::new(password_hash).map_err(|_| PasswordError::InvalidPasswordHash)?;
        if parsed.salt.is_none() || parsed.hash.is_none() {
            return Err(PasswordError::InvalidPasswordHash);
        }
        let assessment = self.assess_parsed_hash(&parsed);
        if let Some(limits) = self.limits.verification_limits {
            limits.validate(assessment.metadata)?;
        }

        match self.argon2()?.verify_password(password.as_bytes(), &parsed) {
            Ok(()) => Ok(PasswordVerification {
                assessment,
                verified: true,
            }),
            Err(PasswordHashError::PasswordInvalid) => Ok(PasswordVerification {
                assessment,
                verified: false,
            }),
            Err(PasswordHashError::Algorithm | PasswordHashError::Version) => {
                Err(PasswordError::UnsupportedPasswordHash)
            }
            Err(
                PasswordHashError::EncodingInvalid
                | PasswordHashError::OutputSize
                | PasswordHashError::ParamInvalid { .. }
                | PasswordHashError::ParamsInvalid
                | PasswordHashError::SaltInvalid,
            ) => Err(PasswordError::InvalidPasswordHash),
            Err(_) => Err(PasswordError::VerificationFailed),
        }
    }

    /// Reads PHC metadata and assesses whether a hash needs rehashing.
    ///
    /// This does not establish that the hash can be verified. Syntactically valid
    /// PHC strings may be incomplete or use unsupported algorithms or versions.
    pub fn assess_password_hash(
        &self,
        password_hash: &str,
    ) -> Result<PasswordHashAssessment, PasswordError> {
        let parsed =
            PasswordHash::new(password_hash).map_err(|_| PasswordError::InvalidPasswordHash)?;
        Ok(self.assess_parsed_hash(&parsed))
    }

    fn assess_parsed_hash(&self, parsed: &PasswordHash) -> PasswordHashAssessment {
        let metadata = password_hash_metadata(parsed);
        PasswordHashAssessment {
            metadata,
            needs_rehash: self.hash_needs_rehash(metadata),
        }
    }

    fn hash_needs_rehash(&self, metadata: PasswordHashMetadata) -> bool {
        let profile = self.profile;
        !metadata.algorithm.is_argon2id()
            || metadata.version != Some(ARGON2_VERSION_13)
            || metadata
                .memory_cost_kib
                .is_none_or(|value| value < profile.memory_cost_kib())
            || metadata
                .time_cost
                .is_none_or(|value| value < profile.time_cost())
            || metadata
                .parallelism
                .is_none_or(|value| value < profile.parallelism())
            || metadata
                .output_bytes
                .is_none_or(|value| value < profile.output_bytes())
    }

    fn argon2(&self) -> Result<Argon2<'_>, PasswordError> {
        Ok(Argon2::new(
            Algorithm::Argon2id,
            Version::V0x13,
            self.profile.params()?,
        ))
    }
}

fn password_hash_metadata(parsed: &PasswordHash) -> PasswordHashMetadata {
    let params = Params::try_from(parsed).ok();
    PasswordHashMetadata {
        algorithm: PasswordHashAlgorithm::from_identifier(parsed.algorithm.as_str()),
        version: parsed.version,
        memory_cost_kib: params.as_ref().map(Params::m_cost),
        time_cost: params.as_ref().map(Params::t_cost),
        parallelism: params.as_ref().map(Params::p_cost),
        output_bytes: params.and_then(|params| params.output_len()),
    }
}

#[cfg(test)]
mod tests {
    use super::{
        Argon2idProfile, PasswordError, PasswordHashAlgorithm, PasswordLimits, PasswordService,
        PasswordVerificationLimits,
    };

    #[test]
    fn verification_limits_are_optional_and_independent_cost_ceilings() {
        assert_eq!(PasswordLimits::default().verification_limits(), None);
        assert_eq!(PasswordLimits::new(32).unwrap().verification_limits(), None);
        for (memory, time, parallelism) in [(0, 1, 1), (7, 1, 1), (8, 0, 1), (8, 1, 0)] {
            assert_eq!(
                PasswordVerificationLimits::new(memory, time, parallelism),
                Err(PasswordError::InvalidPasswordLimits)
            );
        }
        // A cap of two lanes must not forbid an 8 KiB, one-lane hash.
        let verification = PasswordVerificationLimits::new(8, 1, 2).unwrap();
        assert_eq!(verification.max_memory_cost_kib(), 8);
        assert_eq!(verification.max_time_cost(), 1);
        assert_eq!(verification.max_parallelism(), 2);
        let limits = PasswordLimits::new(32)
            .unwrap()
            .with_verification_limits(Some(verification));
        assert_eq!(limits.max_password_bytes(), 32);
        assert_eq!(limits.verification_limits(), Some(verification));
        assert_eq!(
            limits.with_verification_limits(None).verification_limits(),
            None
        );
    }

    #[test]
    fn verification_limits_accept_boundaries_and_report_each_exceeded_cost() {
        use crate::result::{ClassifyError, ErrorKind};

        let hash = PasswordService::new()
            .with_profile(Argon2idProfile::new(32, 2, 2, 16).unwrap())
            .hash_password("test password")
            .unwrap();
        let verifier =
            PasswordService::new().with_profile(Argon2idProfile::new(8, 1, 1, 16).unwrap());
        for (memory, time, parallelism, exceeded) in [
            (32, 2, 2, None),
            (16, 2, 2, Some(("memory_cost_kib", 32, 16))),
            (32, 1, 2, Some(("time_cost", 2, 1))),
            (32, 2, 1, Some(("parallelism", 2, 1))),
        ] {
            let limits = PasswordVerificationLimits::new(memory, time, parallelism).unwrap();
            let service = verifier
                .clone()
                .with_limits(PasswordLimits::default().with_verification_limits(Some(limits)));
            let result = service.verify_and_assess("test password", &hash);
            if let Some((parameter, actual, max)) = exceeded {
                let error = result.unwrap_err();
                assert_eq!(
                    error,
                    PasswordError::VerificationCostExceeded {
                        parameter,
                        actual,
                        max
                    }
                );
                assert_eq!(error.error_kind(), ErrorKind::Validation);
                assert_eq!(error.error_code(), "password_verification_cost_exceeded");
            } else {
                let verification = result.unwrap();
                assert!(verification.verified());
                assert!(!verification.needs_rehash());
                assert!(!service.verify_password("wrong password", &hash).unwrap());
            }
        }
    }

    #[test]
    fn excessive_phc_parameters_are_checked_without_computing_a_hash() {
        for (costs, limits, parameter, actual, max) in [
            (
                format!("m={},t=1,p=1", u32::MAX),
                PasswordVerificationLimits::new(32, 2, 2).unwrap(),
                "memory_cost_kib",
                u32::MAX,
                32,
            ),
            (
                format!("m=8,t={},p=1", u32::MAX),
                PasswordVerificationLimits::new(32, 2, 2).unwrap(),
                "time_cost",
                u32::MAX,
                2,
            ),
            (
                format!(
                    "m={},t=1,p={}",
                    8 * argon2::Params::MAX_P_COST,
                    argon2::Params::MAX_P_COST
                ),
                PasswordVerificationLimits::new(u32::MAX, 2, 2).unwrap(),
                "parallelism",
                argon2::Params::MAX_P_COST,
                2,
            ),
        ] {
            let hash = format!(
                "$argon2id$v=19${costs}$Zm9vdGluZy11cGdyYWRlIQ$HeOmHGQWjqcYomRPMGL9XOICZdk+hUcvgRJdEyVgsj0"
            );
            let metadata = PasswordService::new()
                .assess_password_hash(&hash)
                .unwrap()
                .metadata();
            // Exercise only parsing and the guard for extreme inputs. Even if
            // the guard regresses, this test must never allocate their memory
            // or perform their requested number of passes.
            assert_eq!(
                limits.validate(metadata),
                Err(PasswordError::VerificationCostExceeded {
                    parameter,
                    actual,
                    max
                })
            );
        }
    }

    #[test]
    fn old_algorithms_and_higher_historical_costs_remain_verifiable() {
        use argon2::{Algorithm, Argon2, Params, PasswordHasher as _, Version};

        let hash = Argon2::new(
            Algorithm::Argon2i,
            Version::V0x10,
            Params::new(16, 2, 2, Some(16)).unwrap(),
        )
        .hash_password(b"legacy password")
        .unwrap()
        .to_string();
        for limits in [
            None,
            Some(PasswordVerificationLimits::new(16, 2, 2).unwrap()),
        ] {
            let service = PasswordService::new()
                .with_profile(Argon2idProfile::new(8, 1, 1, 16).unwrap())
                .with_limits(PasswordLimits::default().with_verification_limits(limits));
            let verification = service.verify_and_assess("legacy password", &hash).unwrap();
            assert!(verification.verified());
            assert!(verification.needs_rehash());
        }
    }

    #[test]
    fn verification_limits_leave_generation_assessment_and_rehash_independent() {
        let weak = PasswordService::new().with_profile(Argon2idProfile::new(8, 1, 1, 16).unwrap());
        let old_hash = weak.hash_password("test password").unwrap();
        let service =
            PasswordService::new()
                .with_profile(Argon2idProfile::new(16, 1, 1, 16).unwrap())
                .with_limits(PasswordLimits::default().with_verification_limits(Some(
                    PasswordVerificationLimits::new(8, 1, 1).unwrap(),
                )));
        let verification = service
            .verify_and_assess("test password", &old_hash)
            .unwrap();
        assert!(verification.verified());
        assert!(verification.needs_rehash());
        for hash in [
            service.hash_password("test password").unwrap(),
            service.dummy_password_hash().unwrap(),
        ] {
            let assessment = service.assess_password_hash(&hash).unwrap();
            assert_eq!(assessment.metadata().memory_cost_kib(), Some(16));
            assert!(!assessment.needs_rehash());
            assert!(matches!(
                service.verify_password("test password", &hash),
                Err(PasswordError::VerificationCostExceeded { .. })
            ));
        }
    }

    #[test]
    fn malformed_or_unsupported_phc_is_rejected_with_and_without_cost_limits() {
        use crate::result::{ClassifyError, ErrorKind};

        let service =
            PasswordService::new().with_profile(Argon2idProfile::new(8, 1, 1, 16).unwrap());
        let bounded = service.clone().with_limits(
            PasswordLimits::default()
                .with_verification_limits(Some(PasswordVerificationLimits::new(8, 1, 1).unwrap())),
        );
        for (hash, expected) in [
            ("invalid PHC", PasswordError::InvalidPasswordHash),
            (
                "$argon2id$v=19$m=8,t=1,p=1",
                PasswordError::InvalidPasswordHash,
            ),
            (
                "$argon2id$v=19$m=8,t=1,p=1$Zm9vdGluZy11cGdyYWRlIQ",
                PasswordError::InvalidPasswordHash,
            ),
            (
                "$argon2id$v=19$m=0,t=1,p=1$Zm9vdGluZy11cGdyYWRlIQ$HeOmHGQWjqcYomRPMGL9XOICZdk+hUcvgRJdEyVgsj0",
                PasswordError::InvalidPasswordHash,
            ),
            (
                "$argon2id$v=99$m=8,t=1,p=1$Zm9vdGluZy11cGdyYWRlIQ$HeOmHGQWjqcYomRPMGL9XOICZdk+hUcvgRJdEyVgsj0",
                PasswordError::UnsupportedPasswordHash,
            ),
            (
                "$unknown$v=19$m=8,t=1,p=1$Zm9vdGluZy11cGdyYWRlIQ$HeOmHGQWjqcYomRPMGL9XOICZdk+hUcvgRJdEyVgsj0",
                PasswordError::UnsupportedPasswordHash,
            ),
        ] {
            for verifier in [&service, &bounded] {
                let error = verifier.verify_password("password", hash).unwrap_err();
                assert_eq!(error, expected);
                assert_eq!(error.error_kind(), ErrorKind::Validation);
            }
        }
    }

    #[test]
    fn hashes_with_explicit_argon2id_profile() {
        let service = PasswordService::new();
        let password_hash = service
            .hash_password("correct horse battery staple")
            .expect("test password should hash");
        let assessment = service
            .assess_password_hash(&password_hash)
            .expect("test password hash should parse");
        let metadata = assessment.metadata();

        assert_eq!(metadata.algorithm(), PasswordHashAlgorithm::Argon2id);
        assert_eq!(metadata.version(), Some(super::ARGON2_VERSION_13));
        assert_eq!(
            metadata.memory_cost_kib(),
            Some(super::DEFAULT_ARGON2ID_MEMORY_COST_KIB)
        );
        assert_eq!(
            metadata.time_cost(),
            Some(super::DEFAULT_ARGON2ID_TIME_COST)
        );
        assert_eq!(
            metadata.parallelism(),
            Some(super::DEFAULT_ARGON2ID_PARALLELISM)
        );
        assert_eq!(
            metadata.output_bytes(),
            Some(super::DEFAULT_ARGON2ID_OUTPUT_BYTES)
        );
        assert!(!assessment.needs_rehash());
    }

    #[test]
    fn verifies_hashes_created_before_the_argon2_upgrade() {
        // Generated with argon2 0.5.3 and this service's original cost profile.
        let legacy_hash = "$argon2id$v=19$m=19456,t=2,p=1$Zm9vdGluZy11cGdyYWRlIQ$HeOmHGQWjqcYomRPMGL9XOICZdk+hUcvgRJdEyVgsj0";
        let service = PasswordService::new();
        let verification = service
            .verify_and_assess("legacy test password", legacy_hash)
            .expect("existing PHC hashes must remain readable");
        assert!(verification.verified());
        assert!(!verification.needs_rehash());
        assert!(
            !service
                .verify_password("wrong password", legacy_hash)
                .unwrap()
        );
    }

    #[test]
    fn verifies_matching_password() {
        let service = PasswordService::new();
        let password_hash = service
            .hash_password("correct horse battery staple")
            .expect("test password should hash");

        let verification = service
            .verify_and_assess("correct horse battery staple", &password_hash)
            .expect("test password hash should parse");

        assert!(verification.verified());
        assert!(!verification.needs_rehash());
    }

    #[test]
    fn dummy_hash_reuses_the_configured_argon2_cost_profile() {
        let service = PasswordService::new();
        let dummy_hash = service
            .dummy_password_hash()
            .expect("dummy password hash should build");

        let assessment = service
            .assess_password_hash(&dummy_hash)
            .expect("dummy password hash should parse");
        assert!(!assessment.needs_rehash());
        assert!(!service.verify_password("not-empty", &dummy_hash).unwrap());
    }

    #[test]
    fn rejects_non_matching_password() {
        let service = PasswordService::new();
        let password_hash = service
            .hash_password("correct horse battery staple")
            .expect("test password should hash");

        let verification = service
            .verify_and_assess("wrong password", &password_hash)
            .expect("test password hash should parse");

        assert!(!verification.verified());
        assert!(!verification.needs_rehash());
    }

    #[test]
    fn rejects_invalid_hash_format() {
        let service = PasswordService::new();
        let result = service.verify_password("password", "not-a-password-hash");

        assert!(matches!(result, Err(PasswordError::InvalidPasswordHash)));
    }

    #[test]
    fn marks_weaker_hashes_for_rehash_after_successful_verification() {
        let weak_profile = Argon2idProfile::new(8, 1, 1, 16).unwrap();
        let weak_service = PasswordService::new().with_profile(weak_profile);
        let password_hash = weak_service
            .hash_password("correct horse battery staple")
            .expect("test password should hash");

        let verification = PasswordService::new()
            .verify_and_assess("correct horse battery staple", &password_hash)
            .expect("test password hash should parse");

        assert!(verification.verified());
        assert!(verification.needs_rehash());
    }

    #[tokio::test]
    async fn cancelled_waiter_keeps_password_capacity_until_blocking_work_finishes() {
        use std::sync::Arc;

        use tokio::sync::{Semaphore, TryAcquireError, oneshot};

        let weak_service =
            PasswordService::new().with_profile(Argon2idProfile::new(8, 1, 1, 16).unwrap());
        let stored_hash = weak_service.hash_password("test password").unwrap();
        let service =
            PasswordService::new().with_profile(Argon2idProfile::new(8, 1, 1, 32).unwrap());
        let slots = Arc::new(Semaphore::new(1));
        let (started_tx, started_rx) = oneshot::channel();
        let (resume_tx, resume_rx) = oneshot::channel();
        let (finished_tx, finished_rx) = oneshot::channel();

        let worker_slots = Arc::clone(&slots);
        let worker_service = service.clone();
        let waiter = tokio::spawn(async move {
            let permit = worker_slots.acquire_owned().await.unwrap();
            tokio::task::spawn_blocking(move || {
                let _permit = permit;
                started_tx.send(()).unwrap();
                resume_rx.blocking_recv().unwrap();
                let verification = worker_service
                    .verify_and_assess("test password", &stored_hash)
                    .unwrap();
                let replacement_hash = verification
                    .needs_rehash()
                    .then(|| worker_service.hash_password("test password").unwrap());
                finished_tx.send((verification, replacement_hash)).unwrap();
            })
            .await
            .unwrap();
        });

        started_rx.await.unwrap();
        waiter.abort();
        assert!(waiter.await.unwrap_err().is_cancelled());
        assert!(matches!(
            slots.try_acquire(),
            Err(TryAcquireError::NoPermits)
        ));

        resume_tx.send(()).unwrap();
        let (verification, replacement_hash) = finished_rx.await.unwrap();
        let _released_capacity = slots.acquire().await.unwrap();
        assert!(verification.verified());
        assert!(verification.needs_rehash());
        assert!(
            !service
                .assess_password_hash(&replacement_hash.unwrap())
                .unwrap()
                .needs_rehash()
        );
    }

    #[test]
    fn rejects_oversized_passwords() {
        let service = PasswordService::new()
            .with_limits(PasswordLimits::new(4).expect("limits should be valid"));

        assert!(matches!(
            service.hash_password("12345"),
            Err(PasswordError::PasswordTooLong { max: 4 })
        ));
        assert!(matches!(
            service.verify_password("12345", "not-a-password-hash"),
            Err(PasswordError::PasswordTooLong { max: 4 })
        ));
    }

    #[test]
    fn rejects_invalid_password_limits() {
        assert!(matches!(
            PasswordLimits::new(0),
            Err(PasswordError::InvalidPasswordLimits)
        ));
    }

    #[test]
    fn rejects_invalid_argon2id_profile() {
        for (memory_cost_kib, time_cost, parallelism) in [
            (0, 2, 1),
            (8, 0, 1),
            (8, 1, 0),
            (8, 1, 2),
            (u32::MAX, 1, u32::MAX),
        ] {
            assert!(matches!(
                Argon2idProfile::new(memory_cost_kib, time_cost, parallelism, 32),
                Err(PasswordError::InvalidPasswordHashProfile)
            ));
        }
        for output_bytes in [0, 4, 9, 65, usize::MAX] {
            assert!(matches!(
                Argon2idProfile::new(8, 1, 1, output_bytes),
                Err(PasswordError::InvalidPasswordHashProfile)
            ));
        }
    }

    #[test]
    fn phc_output_boundaries_hash_and_verify_successfully() {
        for output_bytes in [10, 64] {
            let profile = Argon2idProfile::new(8, 1, 1, output_bytes)
                .expect("PHC output boundary should be supported");
            let service = PasswordService::new().with_profile(profile);
            let hash = service
                .hash_password("test password")
                .expect("valid profile should produce a PHC hash");
            let verification = service
                .verify_and_assess("test password", &hash)
                .expect("PHC hash should verify");

            assert!(verification.verified());
            assert!(!verification.needs_rehash());
            assert_eq!(
                service
                    .assess_password_hash(&hash)
                    .expect("PHC hash should parse")
                    .metadata()
                    .output_bytes(),
                Some(output_bytes)
            );
        }
    }
}