Skip to main content

rustfs_iam/mfa/
record.rs

1// Copyright 2024 RustFS Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The persisted per-identity MFA record and the state machine over it.
16//!
17//! Everything here is pure: no storage, no clock, no I/O. The caller supplies
18//! `now`, which is what makes the replay, expiry and lockout rules testable at
19//! their edges instead of only in the happy case.
20//!
21//! Enrollment is deliberately two-phase. A started enrollment lands in
22//! `pending_secret` and only becomes the active secret once the user proves they
23//! can generate a code from it. Without that, a user who scanned the QR into the
24//! wrong app — or never scanned it — would be locked out of their own account
25//! the moment enrollment was recorded. The same two-phase shape is what makes
26//! re-configuring safe: the existing secret keeps working until the new one is
27//! confirmed.
28
29use super::recovery::{self, ConsumeOutcome, StoredRecoveryCode};
30use super::totp::{self, TOTP_ALGORITHM, TOTP_DIGITS, TOTP_PERIOD_SECONDS, TotpSecret};
31use serde::{Deserialize, Serialize};
32use time::OffsetDateTime;
33
34/// On-disk format version. A record written by a newer node is refused rather
35/// than misread.
36pub const MFA_RECORD_VERSION: u8 = 1;
37
38/// How long a started enrollment stays confirmable.
39///
40/// Long enough to install an authenticator app mid-flow, short enough that an
41/// abandoned enrollment does not leave a usable secret lying in the store.
42pub const PENDING_ENROLLMENT_TTL_SECONDS: i64 = 600;
43
44/// Consecutive failures before the identity is locked out.
45const MAX_FAILED_ATTEMPTS: u32 = 5;
46
47/// First lockout duration, doubling for each further run of failures.
48const LOCKOUT_BASE_SECONDS: i64 = 900;
49
50/// Ceiling on the lockout, so a sustained attack cannot lock a legitimate user
51/// out indefinitely — the point is to make guessing infeasible, not to hand an
52/// attacker a denial of service against the account owner.
53const LOCKOUT_MAX_SECONDS: i64 = 3600;
54
55/// A six-digit code has a million values. Bounding attempts is what turns that
56/// into an infeasible guess; without it, an unattended script clears the space
57/// in hours.
58const _: () = assert!(MAX_FAILED_ATTEMPTS > 0);
59
60#[derive(Debug, thiserror::Error, PartialEq, Eq)]
61pub enum MfaRecordError {
62    #[error("the stored MFA record has an unsupported version: {0}")]
63    UnsupportedVersion(u8),
64    #[error("the stored MFA secret is unusable")]
65    CorruptSecret,
66}
67
68/// Why a verification attempt failed.
69///
70/// The API surface collapses most of these into one opaque answer; the
71/// distinctions exist so the audit trail can tell an operator what actually
72/// happened.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum MfaVerifyError {
75    /// No active second factor for this identity.
76    NotEnabled,
77    /// Too many recent failures.
78    Locked { retry_after_seconds: u64 },
79    /// The code did not match anything.
80    InvalidCode,
81    /// A correct TOTP code for a time step that was already spent.
82    ReplayedTotpCode,
83    /// A recovery code that had already been used.
84    ReplayedRecoveryCode,
85}
86
87/// What satisfied a verification.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum MfaVerification {
90    Totp,
91    RecoveryCode { remaining: u32 },
92}
93
94/// The persisted MFA state for one identity.
95///
96/// Field-level notes:
97///
98/// * `secret_b32` present means the second factor is active.
99/// * `pending_secret_b32` present and unexpired means an enrollment awaits
100///   confirmation. Both may be present at once, which is a re-configuration.
101/// * `last_used_step` is the anti-replay high-water mark, not a timestamp.
102#[derive(Debug, Clone, Serialize, Deserialize)]
103pub struct MfaRecord {
104    pub version: u8,
105    pub access_key: String,
106    pub algorithm: String,
107    pub digits: u8,
108    pub period_seconds: u32,
109
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub secret_b32: Option<String>,
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub pending_secret_b32: Option<String>,
114    #[serde(with = "time::serde::rfc3339::option", default, skip_serializing_if = "Option::is_none")]
115    pub pending_expires_at: Option<OffsetDateTime>,
116
117    #[serde(with = "time::serde::rfc3339")]
118    pub created_at: OffsetDateTime,
119    #[serde(with = "time::serde::rfc3339::option", default, skip_serializing_if = "Option::is_none")]
120    pub activated_at: Option<OffsetDateTime>,
121    #[serde(with = "time::serde::rfc3339::option", default, skip_serializing_if = "Option::is_none")]
122    pub last_verified_at: Option<OffsetDateTime>,
123
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub last_used_step: Option<u64>,
126
127    #[serde(default)]
128    pub recovery_codes: Vec<StoredRecoveryCode>,
129    #[serde(with = "time::serde::rfc3339::option", default, skip_serializing_if = "Option::is_none")]
130    pub recovery_codes_generated_at: Option<OffsetDateTime>,
131
132    #[serde(default)]
133    pub failed_attempts: u32,
134    #[serde(with = "time::serde::rfc3339::option", default, skip_serializing_if = "Option::is_none")]
135    pub locked_until: Option<OffsetDateTime>,
136}
137
138impl MfaRecord {
139    /// A record with nothing enrolled.
140    pub fn new(access_key: &str, now: OffsetDateTime) -> Self {
141        Self {
142            version: MFA_RECORD_VERSION,
143            access_key: access_key.to_string(),
144            algorithm: TOTP_ALGORITHM.to_string(),
145            digits: TOTP_DIGITS,
146            period_seconds: TOTP_PERIOD_SECONDS,
147            secret_b32: None,
148            pending_secret_b32: None,
149            pending_expires_at: None,
150            created_at: now,
151            activated_at: None,
152            last_verified_at: None,
153            last_used_step: None,
154            recovery_codes: Vec::new(),
155            recovery_codes_generated_at: None,
156            failed_attempts: 0,
157            locked_until: None,
158        }
159    }
160
161    /// Reject a record this build cannot interpret.
162    pub fn validate_version(&self) -> Result<(), MfaRecordError> {
163        if self.version != MFA_RECORD_VERSION {
164            return Err(MfaRecordError::UnsupportedVersion(self.version));
165        }
166        Ok(())
167    }
168
169    /// Whether a second factor is active.
170    pub const fn is_enabled(&self) -> bool {
171        self.secret_b32.is_some()
172    }
173
174    /// Whether an enrollment is awaiting confirmation.
175    pub fn has_pending_enrollment(&self, now: OffsetDateTime) -> bool {
176        self.pending_secret_b32.is_some() && self.pending_expires_at.is_some_and(|expires| now < expires)
177    }
178
179    /// Recovery codes still usable.
180    pub fn recovery_codes_remaining(&self) -> u32 {
181        recovery::remaining(&self.recovery_codes)
182    }
183
184    /// Whether verification is currently refused because of prior failures.
185    pub fn lock_remaining_seconds(&self, now: OffsetDateTime) -> Option<u64> {
186        let locked_until = self.locked_until?;
187        if now >= locked_until {
188            return None;
189        }
190        Some((locked_until - now).whole_seconds().max(1) as u64)
191    }
192
193    /// Start (or restart) an enrollment.
194    ///
195    /// Overwrites any earlier pending secret: a user who reopened the setup
196    /// dialog expects a fresh QR, and the previous unconfirmed secret has no
197    /// standing. The active secret is untouched, so a re-configuration cannot
198    /// lock the user out if they abandon it.
199    pub fn begin_enrollment(&mut self, secret: &TotpSecret, now: OffsetDateTime) {
200        self.pending_secret_b32 = Some(secret.to_base32());
201        self.pending_expires_at = Some(now + time::Duration::seconds(PENDING_ENROLLMENT_TTL_SECONDS));
202    }
203
204    /// Confirm the pending enrollment with `code`.
205    ///
206    /// On success the pending secret becomes active, the replay high-water mark
207    /// is seeded with the step that was just proven, and the caller is expected
208    /// to install a fresh set of recovery codes.
209    pub fn activate_enrollment(&mut self, code: &str, now: OffsetDateTime) -> Result<(), MfaVerifyError> {
210        if let Some(retry_after_seconds) = self.lock_remaining_seconds(now) {
211            return Err(MfaVerifyError::Locked { retry_after_seconds });
212        }
213
214        let Some(pending) = self.pending_secret_b32.clone() else {
215            return Err(MfaVerifyError::NotEnabled);
216        };
217        if !self.has_pending_enrollment(now) {
218            // Treated as "nothing to confirm" rather than a code failure: the
219            // secret is gone, so no code could ever have matched.
220            self.clear_pending();
221            return Err(MfaVerifyError::NotEnabled);
222        }
223
224        let secret = TotpSecret::from_base32(&pending).map_err(|_| MfaVerifyError::NotEnabled)?;
225        let unix = now.unix_timestamp().max(0) as u64;
226
227        match secret.verify(code, unix, None) {
228            Ok(step) => {
229                self.secret_b32 = Some(pending);
230                self.activated_at = Some(now);
231                self.last_used_step = Some(step);
232                self.last_verified_at = Some(now);
233                self.clear_pending();
234                self.clear_failures();
235                Ok(())
236            }
237            Err(_) => {
238                self.register_failure(now);
239                Err(MfaVerifyError::InvalidCode)
240            }
241        }
242    }
243
244    /// Verify a second factor against the active enrollment.
245    ///
246    /// Accepts either a TOTP code or a recovery code and decides which by shape,
247    /// so a client never has to ask the user to declare what they typed.
248    pub fn verify(&mut self, code: &str, now: OffsetDateTime) -> Result<MfaVerification, MfaVerifyError> {
249        if let Some(retry_after_seconds) = self.lock_remaining_seconds(now) {
250            return Err(MfaVerifyError::Locked { retry_after_seconds });
251        }
252
253        let Some(secret_b32) = self.secret_b32.clone() else {
254            return Err(MfaVerifyError::NotEnabled);
255        };
256
257        // Shape routing happens before either verification so a recovery code is
258        // never fed to the TOTP path (where it would burn a failed attempt for
259        // the wrong reason) and vice versa.
260        if recovery::looks_like_recovery_code(code) {
261            return self.verify_recovery_code(code, now);
262        }
263
264        if !totp::looks_like_totp_code(code) {
265            self.register_failure(now);
266            return Err(MfaVerifyError::InvalidCode);
267        }
268
269        let secret = TotpSecret::from_base32(&secret_b32).map_err(|_| MfaVerifyError::NotEnabled)?;
270        let unix = now.unix_timestamp().max(0) as u64;
271
272        match secret.verify(code, unix, self.last_used_step) {
273            Ok(step) => {
274                self.last_used_step = Some(step);
275                self.last_verified_at = Some(now);
276                self.clear_failures();
277                Ok(MfaVerification::Totp)
278            }
279            Err(_) => {
280                self.register_failure(now);
281                // Re-check ignoring the high-water mark purely to classify the
282                // failure for the audit trail. The caller still gets a single
283                // opaque rejection, so this tells an attacker nothing while
284                // telling an operator whether they are seeing replays.
285                if secret.verify(code, unix, None).is_ok() {
286                    Err(MfaVerifyError::ReplayedTotpCode)
287                } else {
288                    Err(MfaVerifyError::InvalidCode)
289                }
290            }
291        }
292    }
293
294    fn verify_recovery_code(&mut self, code: &str, now: OffsetDateTime) -> Result<MfaVerification, MfaVerifyError> {
295        match recovery::consume(&mut self.recovery_codes, code, now) {
296            ConsumeOutcome::Consumed { remaining, .. } => {
297                self.last_verified_at = Some(now);
298                self.clear_failures();
299                Ok(MfaVerification::RecoveryCode { remaining })
300            }
301            ConsumeOutcome::AlreadyUsed => {
302                self.register_failure(now);
303                Err(MfaVerifyError::ReplayedRecoveryCode)
304            }
305            ConsumeOutcome::NoMatch => {
306                self.register_failure(now);
307                Err(MfaVerifyError::InvalidCode)
308            }
309        }
310    }
311
312    /// Replace the recovery code set.
313    pub fn set_recovery_codes(&mut self, codes: Vec<StoredRecoveryCode>, now: OffsetDateTime) {
314        self.recovery_codes = codes;
315        self.recovery_codes_generated_at = Some(now);
316    }
317
318    /// Turn the second factor off, clearing every trace of the enrollment.
319    ///
320    /// Recovery codes go too: keeping them would leave a live bypass for a
321    /// factor the user believes is gone.
322    pub fn disable(&mut self) {
323        self.secret_b32 = None;
324        self.activated_at = None;
325        self.last_used_step = None;
326        self.recovery_codes.clear();
327        self.recovery_codes_generated_at = None;
328        self.clear_pending();
329        self.clear_failures();
330    }
331
332    fn clear_pending(&mut self) {
333        self.pending_secret_b32 = None;
334        self.pending_expires_at = None;
335    }
336
337    fn clear_failures(&mut self) {
338        self.failed_attempts = 0;
339        self.locked_until = None;
340    }
341
342    /// Record a failed attempt, locking the identity once the threshold is hit.
343    ///
344    /// The lockout doubles for each further run of failures so a persistent
345    /// attacker faces a rapidly growing cost, capped so the account owner is
346    /// never locked out for longer than [`LOCKOUT_MAX_SECONDS`].
347    fn register_failure(&mut self, now: OffsetDateTime) {
348        self.failed_attempts = self.failed_attempts.saturating_add(1);
349
350        if !self.failed_attempts.is_multiple_of(MAX_FAILED_ATTEMPTS) {
351            return;
352        }
353
354        let runs = self.failed_attempts / MAX_FAILED_ATTEMPTS;
355        // `runs` is at least 1 here; shift is bounded so the doubling cannot
356        // overflow before the cap applies.
357        let scale = 1i64.checked_shl(runs.saturating_sub(1).min(16)).unwrap_or(i64::MAX);
358        let seconds = LOCKOUT_BASE_SECONDS.saturating_mul(scale).min(LOCKOUT_MAX_SECONDS);
359        self.locked_until = Some(now + time::Duration::seconds(seconds));
360    }
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366
367    fn at(unix: i64) -> OffsetDateTime {
368        OffsetDateTime::from_unix_timestamp(unix).expect("valid timestamp")
369    }
370
371    const T0: i64 = 1_700_000_000;
372
373    fn enrolled() -> (MfaRecord, TotpSecret) {
374        let secret = TotpSecret::generate();
375        let mut record = MfaRecord::new("sinan", at(T0));
376        record.begin_enrollment(&secret, at(T0));
377        let code = secret.code_at(T0 as u64);
378        record.activate_enrollment(&code, at(T0)).expect("activate");
379        (record, secret)
380    }
381
382    #[test]
383    fn a_new_record_has_nothing_enrolled() {
384        let record = MfaRecord::new("sinan", at(T0));
385
386        assert!(!record.is_enabled());
387        assert!(!record.has_pending_enrollment(at(T0)));
388        assert_eq!(record.recovery_codes_remaining(), 0);
389        assert_eq!(record.algorithm, "SHA1");
390        assert_eq!(record.digits, 6);
391        assert_eq!(record.period_seconds, 30);
392    }
393
394    #[test]
395    fn a_record_from_an_unknown_version_is_refused() {
396        let mut record = MfaRecord::new("sinan", at(T0));
397        record.version = 99;
398        assert_eq!(record.validate_version(), Err(MfaRecordError::UnsupportedVersion(99)));
399    }
400
401    #[test]
402    fn enrollment_is_only_active_after_confirmation() {
403        // The property that keeps a mis-scanned QR from locking the user out.
404        let secret = TotpSecret::generate();
405        let mut record = MfaRecord::new("sinan", at(T0));
406        record.begin_enrollment(&secret, at(T0));
407
408        assert!(record.has_pending_enrollment(at(T0)));
409        assert!(!record.is_enabled(), "a pending enrollment must not gate logins");
410
411        record
412            .activate_enrollment(&secret.code_at(T0 as u64), at(T0))
413            .expect("activate");
414
415        assert!(record.is_enabled());
416        assert!(!record.has_pending_enrollment(at(T0)));
417        assert_eq!(record.activated_at, Some(at(T0)));
418    }
419
420    #[test]
421    fn activation_with_a_wrong_code_leaves_the_enrollment_pending() {
422        let secret = TotpSecret::generate();
423        let mut record = MfaRecord::new("sinan", at(T0));
424        record.begin_enrollment(&secret, at(T0));
425
426        assert_eq!(record.activate_enrollment("000000", at(T0)), Err(MfaVerifyError::InvalidCode));
427        assert!(!record.is_enabled());
428        assert!(record.has_pending_enrollment(at(T0)), "the user must be able to retry");
429        assert_eq!(record.failed_attempts, 1);
430    }
431
432    #[test]
433    fn an_expired_enrollment_cannot_be_confirmed() {
434        let secret = TotpSecret::generate();
435        let mut record = MfaRecord::new("sinan", at(T0));
436        record.begin_enrollment(&secret, at(T0));
437
438        let late = T0 + PENDING_ENROLLMENT_TTL_SECONDS + 1;
439        assert_eq!(
440            record.activate_enrollment(&secret.code_at(late as u64), at(late)),
441            Err(MfaVerifyError::NotEnabled)
442        );
443        assert!(!record.is_enabled());
444        assert!(record.pending_secret_b32.is_none(), "an expired secret must not linger");
445    }
446
447    #[test]
448    fn re_enrolling_keeps_the_existing_factor_working_until_confirmed() {
449        // Re-configuration must not be a window with no second factor.
450        let (mut record, original) = enrolled();
451        let replacement = TotpSecret::generate();
452        record.begin_enrollment(&replacement, at(T0 + 60));
453
454        assert!(record.is_enabled());
455        assert_eq!(record.verify(&original.code_at((T0 + 60) as u64), at(T0 + 60)), Ok(MfaVerification::Totp));
456
457        record
458            .activate_enrollment(&replacement.code_at((T0 + 120) as u64), at(T0 + 120))
459            .expect("activate replacement");
460
461        // The old secret stops working only once the new one is confirmed.
462        assert_eq!(
463            record.verify(&original.code_at((T0 + 180) as u64), at(T0 + 180)),
464            Err(MfaVerifyError::InvalidCode)
465        );
466        assert_eq!(
467            record.verify(&replacement.code_at((T0 + 180) as u64), at(T0 + 180)),
468            Ok(MfaVerification::Totp)
469        );
470    }
471
472    #[test]
473    fn a_current_totp_code_verifies() {
474        let (mut record, secret) = enrolled();
475        let later = T0 + 60;
476
477        assert_eq!(record.verify(&secret.code_at(later as u64), at(later)), Ok(MfaVerification::Totp));
478        assert_eq!(record.last_verified_at, Some(at(later)));
479    }
480
481    #[test]
482    fn a_replayed_totp_code_is_rejected_and_classified() {
483        let (mut record, secret) = enrolled();
484        let later = T0 + 60;
485        let code = secret.code_at(later as u64);
486
487        assert_eq!(record.verify(&code, at(later)), Ok(MfaVerification::Totp));
488        // Same code, same window: correct by the clock, refused by the step.
489        assert_eq!(record.verify(&code, at(later)), Err(MfaVerifyError::ReplayedTotpCode));
490    }
491
492    #[test]
493    fn activation_seeds_the_replay_high_water_mark() {
494        // Without this, the code used to confirm enrollment would still be
495        // valid for its remaining window.
496        let secret = TotpSecret::generate();
497        let mut record = MfaRecord::new("sinan", at(T0));
498        record.begin_enrollment(&secret, at(T0));
499        let code = secret.code_at(T0 as u64);
500        record.activate_enrollment(&code, at(T0)).expect("activate");
501
502        assert_eq!(record.verify(&code, at(T0)), Err(MfaVerifyError::ReplayedTotpCode));
503    }
504
505    #[test]
506    fn a_wrong_code_is_rejected_as_invalid() {
507        let (mut record, secret) = enrolled();
508        let later = T0 + 60;
509        let correct: u32 = secret.code_at(later as u64).parse().expect("digits");
510        let wrong = format!("{:06}", (correct + 1) % 1_000_000);
511
512        assert_eq!(record.verify(&wrong, at(later)), Err(MfaVerifyError::InvalidCode));
513    }
514
515    #[test]
516    fn verification_fails_when_nothing_is_enrolled() {
517        let mut record = MfaRecord::new("sinan", at(T0));
518        assert_eq!(record.verify("123456", at(T0)), Err(MfaVerifyError::NotEnabled));
519    }
520
521    #[test]
522    fn a_recovery_code_verifies_and_is_consumed() {
523        let (mut record, _) = enrolled();
524        let generated = recovery::generate();
525        record.set_recovery_codes(generated.stored, at(T0));
526
527        let outcome = record.verify(&generated.plaintext[0], at(T0 + 60));
528        assert_eq!(outcome, Ok(MfaVerification::RecoveryCode { remaining: 9 }));
529        assert_eq!(record.recovery_codes_remaining(), 9);
530    }
531
532    #[test]
533    fn a_reused_recovery_code_is_rejected_and_classified() {
534        let (mut record, _) = enrolled();
535        let generated = recovery::generate();
536        record.set_recovery_codes(generated.stored, at(T0));
537
538        record.verify(&generated.plaintext[0], at(T0 + 60)).expect("first use");
539        assert_eq!(
540            record.verify(&generated.plaintext[0], at(T0 + 90)),
541            Err(MfaVerifyError::ReplayedRecoveryCode)
542        );
543    }
544
545    #[test]
546    fn a_recovery_code_is_not_charged_against_the_totp_path() {
547        // Shape routing: a recovery code must not be tried as a TOTP code, or a
548        // legitimate recovery attempt would also register a TOTP failure.
549        let (mut record, _) = enrolled();
550        let generated = recovery::generate();
551        record.set_recovery_codes(generated.stored, at(T0));
552
553        record.verify(&generated.plaintext[0], at(T0 + 60)).expect("recovery code");
554        assert_eq!(record.failed_attempts, 0);
555    }
556
557    #[test]
558    fn repeated_failures_lock_the_identity() {
559        let (mut record, secret) = enrolled();
560        let later = T0 + 60;
561
562        for attempt in 1..MAX_FAILED_ATTEMPTS {
563            assert_eq!(record.verify("000000", at(later)), Err(MfaVerifyError::InvalidCode));
564            assert!(record.lock_remaining_seconds(at(later)).is_none(), "locked too early at {attempt}");
565        }
566
567        assert_eq!(record.verify("000000", at(later)), Err(MfaVerifyError::InvalidCode));
568        let remaining = record.lock_remaining_seconds(at(later)).expect("must be locked");
569        assert_eq!(remaining, LOCKOUT_BASE_SECONDS as u64);
570
571        // A correct code is refused while locked: that is the whole point.
572        assert_eq!(
573            record.verify(&secret.code_at(later as u64), at(later)),
574            Err(MfaVerifyError::Locked {
575                retry_after_seconds: LOCKOUT_BASE_SECONDS as u64
576            })
577        );
578    }
579
580    #[test]
581    fn the_lock_expires_and_a_correct_code_then_works() {
582        let (mut record, secret) = enrolled();
583        let later = T0 + 60;
584        for _ in 0..MAX_FAILED_ATTEMPTS {
585            let _ = record.verify("000000", at(later));
586        }
587
588        let after_lock = later + LOCKOUT_BASE_SECONDS + 1;
589        assert!(record.lock_remaining_seconds(at(after_lock)).is_none());
590        assert_eq!(
591            record.verify(&secret.code_at(after_lock as u64), at(after_lock)),
592            Ok(MfaVerification::Totp)
593        );
594    }
595
596    #[test]
597    fn a_successful_verification_clears_the_failure_count() {
598        let (mut record, secret) = enrolled();
599        let later = T0 + 60;
600
601        let _ = record.verify("000000", at(later));
602        let _ = record.verify("000000", at(later));
603        assert_eq!(record.failed_attempts, 2);
604
605        record.verify(&secret.code_at(later as u64), at(later)).expect("correct code");
606        assert_eq!(record.failed_attempts, 0);
607        assert!(record.locked_until.is_none());
608    }
609
610    #[test]
611    fn successive_lockouts_lengthen_and_then_stop_growing() {
612        let (mut record, _) = enrolled();
613        let mut clock = T0 + 60;
614        let mut previous = 0u64;
615
616        for round in 1..=8 {
617            for _ in 0..MAX_FAILED_ATTEMPTS {
618                let _ = record.verify("000000", at(clock));
619            }
620            let locked_for = record.lock_remaining_seconds(at(clock)).expect("must be locked");
621
622            assert!(locked_for <= LOCKOUT_MAX_SECONDS as u64, "round {round} exceeded the cap");
623            assert!(locked_for >= previous, "round {round} went backwards");
624            previous = locked_for;
625
626            // Step past the lock without succeeding, so the failure run continues.
627            clock += locked_for as i64 + 1;
628        }
629
630        assert_eq!(previous, LOCKOUT_MAX_SECONDS as u64, "the lockout should reach its cap");
631    }
632
633    #[test]
634    fn disabling_clears_the_secret_and_the_recovery_codes() {
635        // A user who turns the factor off must not be left with codes that
636        // still bypass a factor they believe is gone.
637        let (mut record, secret) = enrolled();
638        record.set_recovery_codes(recovery::generate().stored, at(T0));
639
640        record.disable();
641
642        assert!(!record.is_enabled());
643        assert!(record.secret_b32.is_none());
644        assert_eq!(record.recovery_codes_remaining(), 0);
645        assert!(record.recovery_codes.is_empty());
646        assert!(record.activated_at.is_none());
647        assert_eq!(record.verify(&secret.code_at(T0 as u64), at(T0)), Err(MfaVerifyError::NotEnabled));
648    }
649
650    #[test]
651    fn malformed_input_is_rejected_without_matching_anything() {
652        let (mut record, _) = enrolled();
653        for bad in ["", "abc", "12345", "1234567", "!!!!"] {
654            assert_eq!(record.verify(bad, at(T0 + 60)), Err(MfaVerifyError::InvalidCode), "input {bad:?}");
655        }
656    }
657
658    #[test]
659    fn the_record_round_trips_through_serde_without_leaking_plaintext_codes() {
660        let (mut record, _) = enrolled();
661        let generated = recovery::generate();
662        record.set_recovery_codes(generated.stored, at(T0));
663
664        let encoded = serde_json::to_string(&record).expect("serialize");
665        let decoded: MfaRecord = serde_json::from_str(&encoded).expect("deserialize");
666
667        assert_eq!(decoded.access_key, "sinan");
668        assert!(decoded.is_enabled());
669        assert_eq!(decoded.recovery_codes_remaining(), 10);
670        assert_eq!(decoded.last_used_step, record.last_used_step);
671
672        for plaintext in &generated.plaintext {
673            assert!(!encoded.contains(plaintext), "serialized record leaked a recovery code");
674        }
675    }
676
677    #[test]
678    fn a_record_written_by_an_older_node_decodes_without_the_optional_fields() {
679        // Forward/backward tolerance: the optional fields are skipped when
680        // absent, so a minimal record from a rolling upgrade still loads.
681        let minimal = serde_json::json!({
682            "version": 1,
683            "access_key": "sinan",
684            "algorithm": "SHA1",
685            "digits": 6,
686            "period_seconds": 30,
687            "created_at": "2026-08-25T00:00:00Z",
688        });
689        let decoded: MfaRecord = serde_json::from_value(minimal).expect("deserialize");
690
691        assert!(!decoded.is_enabled());
692        assert_eq!(decoded.failed_attempts, 0);
693        assert!(decoded.recovery_codes.is_empty());
694        decoded.validate_version().expect("version 1 is supported");
695    }
696}