ch-auth 0.3.2

Authentication and session primitives with explicit security policies
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
use ch_parsing::error::{ParseError, ParseErrorCode};
use ch_parsing::input::strings::{enforce_max_len, parse_optional_trimmed, require_trimmed};
use serde::{Deserialize, Serialize};
use std::fmt;
use time::{Duration, OffsetDateTime};
use uuid::Uuid;

use crate::auth::login::forms::parse_password;
use crate::messages::AuthMessage;

/// Server-side TOTP, backup-code, and QR-code helpers.
pub mod api;

/// Number of alphanumeric characters in each generated backup code.
pub const BACKUP_CODE_LENGTH: usize = 8;
/// Number of one-time backup codes generated as a set.
pub const BACKUP_CODE_COUNT: usize = 8;
/// Lifetime of a pending two-factor login challenge.
pub const TWO_FACTOR_TTL: Duration = Duration::minutes(5);
/// Standard time step used by generated and verified TOTP codes.
pub const TOTP_PERIOD_SECONDS: u64 = 30;
const MAX_TWO_FACTOR_TOKEN_CHARS: usize = 256;
const MAX_TWO_FACTOR_CODE_CHARS: usize = 64;
const _: () = {
    assert!(BACKUP_CODE_LENGTH > 4);
};

#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
/// Raw challenge token and verification code submitted during login.
///
/// Its custom [`fmt::Debug`] implementation redacts both values.
pub struct TwoFactorLoginForm {
    #[serde(alias = "form[token]")]
    token: String,
    #[serde(alias = "form[code]")]
    code: String,
}

impl TwoFactorLoginForm {
    /// Creates a two-factor login form from its raw values.
    pub fn new(token: String, code: String) -> Self {
        Self { token, code }
    }
}

#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
/// Provisioning material returned when two-factor authentication is set up.
///
/// Its custom [`fmt::Debug`] implementation redacts all secret material.
pub struct TwoFactorSetup {
    success: bool,
    secret: String,
    otpauth_uri: String,
    qr_svg: String,
    qr_png_data_uri: String,
}

impl TwoFactorSetup {
    /// Creates a provisioning result and its rendered QR artifacts.
    pub fn new(
        success: bool,
        secret: String,
        otpauth_uri: String,
        qr_svg: String,
        qr_png_data_uri: String,
    ) -> Self {
        Self {
            success,
            secret,
            otpauth_uri,
            qr_svg,
            qr_png_data_uri,
        }
    }
    /// Reports whether provisioning succeeded.
    pub fn success(&self) -> bool {
        self.success
    }
    /// Returns the Base32-encoded TOTP secret.
    pub fn secret(&self) -> &str {
        self.secret.as_str()
    }
    /// Returns the OTPAUTH URI suitable for authenticator applications.
    pub fn otpauth_uri(&self) -> &str {
        self.otpauth_uri.as_str()
    }
    /// Returns the provisioning QR code as SVG markup.
    pub fn qr_svg(&self) -> &str {
        self.qr_svg.as_str()
    }
    /// Returns the QR artifact as the crate's encoded image data URI.
    pub fn qr_png_data_uri(&self) -> &str {
        self.qr_png_data_uri.as_str()
    }
}

#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
/// Raw six-digit TOTP code submitted for account verification.
///
/// Its custom [`fmt::Debug`] implementation redacts the code.
pub struct TwoFactorVerificationForm {
    #[serde(alias = "form[code]")]
    code: String,
}

impl TwoFactorVerificationForm {
    /// Creates a verification form from a raw code.
    pub fn new(code: String) -> Self {
        Self { code }
    }
    /// Parses an exactly six-digit ASCII TOTP code.
    pub fn parse(self) -> Result<u32, ParseError> {
        enforce_max_len(&self.code, MAX_TWO_FACTOR_CODE_CHARS, "code")?;
        let trimmed = require_trimmed(&self.code, "code")?;
        if trimmed.len() != 6 || !trimmed.chars().all(|char| char.is_ascii_digit()) {
            return Err(ParseError::for_field("code", ParseErrorCode::InvalidFormat)
                .with_parameter("expected", "six_ascii_digits"));
        }
        trimmed.parse::<u32>().map_err(|_| {
            ParseError::for_field("code", ParseErrorCode::InvalidFormat)
                .with_parameter("expected", "six_ascii_digits")
        })
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
/// Result returned after verifying a two-factor setup code.
pub struct TwoFactorVerificationOutcome {
    success: bool,
    message: Option<AuthMessage>,
}

impl TwoFactorVerificationOutcome {
    /// Creates a verification outcome with optional translatable feedback.
    pub fn new(success: bool, message: Option<AuthMessage>) -> Self {
        Self { success, message }
    }
    /// Reports whether verification succeeded.
    pub fn success(&self) -> bool {
        self.success
    }
    /// Returns optional translatable feedback.
    pub fn message(&self) -> Option<&AuthMessage> {
        self.message.as_ref()
    }
}

#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
/// Raw credentials accepted when disabling two-factor authentication.
///
/// At least one of the verification code or password must be present. Its
/// custom [`fmt::Debug`] implementation exposes only whether values exist.
pub struct DisableTwoFactorForm {
    #[serde(alias = "form[code]")]
    code: Option<String>,
    #[serde(alias = "form[password]")]
    password: Option<String>,
}

impl DisableTwoFactorForm {
    /// Creates a disable form from optional verification credentials.
    pub fn new(code: Option<String>, password: Option<String>) -> Self {
        Self { code, password }
    }
}

#[derive(Clone, PartialEq, Eq)]
/// Validated credentials for disabling two-factor authentication.
///
/// Its custom [`fmt::Debug`] implementation exposes only whether values exist.
pub struct ParsedDisableTwoFactor {
    code: Option<u32>,
    password: Option<String>,
}

impl ParsedDisableTwoFactor {
    /// Returns the optional parsed six-digit TOTP code.
    pub fn code(&self) -> Option<u32> {
        self.code
    }
    /// Returns the optional non-empty password.
    pub fn password(&self) -> Option<&str> {
        self.password.as_deref()
    }
    /// Validates a disable form and requires at least one credential.
    pub fn parse(form: DisableTwoFactorForm) -> Result<Self, ParseError> {
        if let Some(code) = form.code.as_deref() {
            enforce_max_len(code, MAX_TWO_FACTOR_CODE_CHARS, "code")?;
        }
        let code = match parse_optional_trimmed(form.code) {
            Some(value) => {
                let trimmed = value.trim();
                if trimmed.len() != 6 || !trimmed.chars().all(|char| char.is_ascii_digit()) {
                    return Err(ParseError::for_field("code", ParseErrorCode::InvalidFormat)
                        .with_parameter("expected", "six_ascii_digits"));
                }
                Some(trimmed.parse::<u32>().map_err(|_| {
                    ParseError::for_field("code", ParseErrorCode::InvalidFormat)
                        .with_parameter("expected", "six_ascii_digits")
                })?)
            }
            None => None,
        };
        let password = match form.password {
            Some(password) => Some(parse_password(password, "password")?),
            None => None,
        };
        if code.is_none() && password.is_none() {
            return Err(ParseError::for_field("code", ParseErrorCode::Required)
                .with_parameter("alternative", "password"));
        }
        Ok(Self { code, password })
    }
}

impl TryFrom<DisableTwoFactorForm> for ParsedDisableTwoFactor {
    type Error = ParseError;
    fn try_from(form: DisableTwoFactorForm) -> Result<Self, ParseError> {
        Self::parse(form)
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
/// Result returned after attempting to disable two-factor authentication.
pub struct TwoFactorDisableOutcome {
    success: bool,
    message: Option<AuthMessage>,
}

impl TwoFactorDisableOutcome {
    /// Creates a disable outcome with optional translatable feedback.
    pub fn new(success: bool, message: Option<AuthMessage>) -> Self {
        Self { success, message }
    }
    /// Reports whether two-factor authentication was disabled.
    pub fn success(&self) -> bool {
        self.success
    }
    /// Returns optional translatable feedback.
    pub fn message(&self) -> Option<&AuthMessage> {
        self.message.as_ref()
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
/// Current two-factor authentication state for an account.
pub struct TwoFactorStatus {
    enabled: bool,
    has_secret: bool,
}

impl TwoFactorStatus {
    /// Creates an account status from the effective and persisted states.
    pub fn new(enabled: bool, has_secret: bool) -> Self {
        Self {
            enabled,
            has_secret,
        }
    }
    /// Reports whether two-factor authentication is enabled.
    pub fn enabled(&self) -> bool {
        self.enabled
    }
    /// Reports whether the account has stored TOTP secret material.
    pub fn has_secret(&self) -> bool {
        self.has_secret
    }
}

#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
/// Generated one-time backup codes and their operation outcome.
///
/// Its custom [`fmt::Debug`] implementation does not expose the codes.
pub struct TwoFactorBackupCodes {
    success: bool,
    codes: Vec<String>,
    message: Option<AuthMessage>,
}

impl TwoFactorBackupCodes {
    /// Creates a backup-code generation outcome.
    pub fn new(success: bool, codes: Vec<String>, message: Option<AuthMessage>) -> Self {
        Self {
            success,
            codes,
            message,
        }
    }
    /// Reports whether backup-code generation succeeded.
    pub fn success(&self) -> bool {
        self.success
    }
    /// Returns the generated one-time codes.
    pub fn codes(&self) -> &[String] {
        &self.codes
    }
    /// Returns optional translatable feedback.
    pub fn message(&self) -> Option<&AuthMessage> {
        self.message.as_ref()
    }
}

#[derive(Clone, PartialEq, Eq)]
/// Validated opaque token for a pending two-factor login challenge.
///
/// Its custom [`fmt::Debug`] implementation redacts the token.
pub struct TwoFactorToken(String);

impl TwoFactorToken {
    /// Validates a non-empty challenge token without changing its bytes.
    pub fn parse(raw: String) -> Result<Self, ParseError> {
        enforce_max_len(&raw, MAX_TWO_FACTOR_TOKEN_CHARS, "token")?;
        if raw.trim().is_empty() {
            return Err(ParseError::for_field("token", ParseErrorCode::Required));
        }
        Ok(Self(raw))
    }
    /// Returns the validated token.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[derive(Clone, PartialEq, Eq)]
/// Validated second-factor code supplied during login.
///
/// Its custom [`fmt::Debug`] implementation redacts the code.
pub enum TwoFactorCode {
    /// Six-digit time-based one-time password.
    Totp(String),
    /// Normalized one-time recovery code.
    Backup(String),
}

impl TwoFactorCode {
    /// Parses either a six-digit TOTP or an alphanumeric backup code.
    pub fn parse(raw: String) -> Result<Self, ParseError> {
        enforce_max_len(&raw, MAX_TWO_FACTOR_CODE_CHARS, "code")?;
        let trimmed = require_trimmed(&raw, "code")?;
        if trimmed.len() == 6 && trimmed.chars().all(|char| char.is_ascii_digit()) {
            return Ok(Self::Totp(trimmed));
        }
        if let Some(normalized) = normalize_backup_code(trimmed.as_str()) {
            return Ok(Self::Backup(normalized));
        }
        Err(ParseError::for_field("code", ParseErrorCode::InvalidFormat)
            .with_parameter("expected", "totp_or_backup_code"))
    }
    /// Returns the numeric TOTP value when this is a TOTP code.
    pub fn totp_value(&self) -> Option<u32> {
        match self {
            Self::Totp(code) => Some(code.parse::<u32>().unwrap_or(0)),
            Self::Backup(_) => None,
        }
    }
    /// Returns the normalized recovery value when this is a backup code.
    pub fn backup_code(&self) -> Option<&str> {
        match self {
            Self::Totp(_) => None,
            Self::Backup(code) => Some(code.as_str()),
        }
    }
}

fn normalize_backup_code(raw: &str) -> Option<String> {
    let mut normalized = String::with_capacity(BACKUP_CODE_LENGTH);
    for ch in raw.chars() {
        if ch.is_ascii_alphanumeric() {
            normalized.push(ch.to_ascii_uppercase());
        } else if ch == '-' || ch.is_whitespace() {
            continue;
        } else {
            return None;
        }
    }
    if normalized.len() == BACKUP_CODE_LENGTH {
        Some(normalized)
    } else {
        None
    }
}

#[derive(Clone, PartialEq, Eq)]
/// Validated token and code for completing a two-factor login.
///
/// Its custom [`fmt::Debug`] implementation redacts the token and code.
pub struct TwoFactorLoginPayload {
    token: TwoFactorToken,
    code: TwoFactorCode,
}

impl TwoFactorLoginPayload {
    /// Validates a raw two-factor login form.
    pub fn parse(form: TwoFactorLoginForm) -> Result<Self, ParseError> {
        Ok(Self {
            token: TwoFactorToken::parse(form.token)?,
            code: TwoFactorCode::parse(form.code)?,
        })
    }
    /// Returns the validated pending-challenge token.
    pub fn token(&self) -> &TwoFactorToken {
        &self.token
    }
    /// Returns the validated second-factor code.
    pub fn code(&self) -> &TwoFactorCode {
        &self.code
    }
}

#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
/// Server-issued pending two-factor login challenge.
///
/// Its custom [`fmt::Debug`] implementation redacts the challenge token.
pub struct TwoFactorChallenge {
    account_id: String,
    token: String,
    issued_at: OffsetDateTime,
}

impl TwoFactorChallenge {
    /// Issues a fresh challenge for an account at the current UTC time.
    pub fn new(account_id: String) -> Self {
        Self {
            account_id,
            token: Uuid::new_v4().to_string(),
            issued_at: OffsetDateTime::now_utc(),
        }
    }
    /// Returns the account associated with this challenge.
    pub fn account_id(&self) -> &str {
        self.account_id.as_str()
    }
    /// Returns the opaque challenge token.
    pub fn token(&self) -> &str {
        self.token.as_str()
    }
    /// Reports whether the challenge is older than [`TWO_FACTOR_TTL`] at `now`.
    pub fn is_expired(&self, now: OffsetDateTime) -> bool {
        now > self.issued_at + TWO_FACTOR_TTL
    }
}

impl fmt::Debug for TwoFactorLoginForm {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TwoFactorLoginForm")
            .field("token", &"[REDACTED]")
            .field("code", &"[REDACTED]")
            .finish()
    }
}

impl fmt::Debug for TwoFactorSetup {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TwoFactorSetup")
            .field("success", &self.success)
            .field("secret", &"[REDACTED]")
            .field("otpauth_uri", &"[REDACTED]")
            .field("has_qr_svg", &!self.qr_svg.is_empty())
            .field("has_qr_data_uri", &!self.qr_png_data_uri.is_empty())
            .finish()
    }
}

impl fmt::Debug for TwoFactorVerificationForm {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TwoFactorVerificationForm")
            .field("code", &"[REDACTED]")
            .finish()
    }
}

impl fmt::Debug for DisableTwoFactorForm {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DisableTwoFactorForm")
            .field("has_code", &self.code.is_some())
            .field("has_password", &self.password.is_some())
            .finish()
    }
}

impl fmt::Debug for ParsedDisableTwoFactor {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ParsedDisableTwoFactor")
            .field("has_code", &self.code.is_some())
            .field("has_password", &self.password.is_some())
            .finish()
    }
}

impl fmt::Debug for TwoFactorBackupCodes {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TwoFactorBackupCodes")
            .field("success", &self.success)
            .field("code_count", &self.codes.len())
            .field("message", &self.message)
            .finish()
    }
}

impl fmt::Debug for TwoFactorToken {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_tuple("TwoFactorToken")
            .field(&"[REDACTED]")
            .finish()
    }
}

impl fmt::Debug for TwoFactorCode {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Totp(_) => "TwoFactorCode::Totp([REDACTED])",
            Self::Backup(_) => "TwoFactorCode::Backup([REDACTED])",
        })
    }
}

impl fmt::Debug for TwoFactorLoginPayload {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TwoFactorLoginPayload")
            .field("token", &"[REDACTED]")
            .field("code", &self.code)
            .finish()
    }
}

impl fmt::Debug for TwoFactorChallenge {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TwoFactorChallenge")
            .field("account_id", &self.account_id)
            .field("token", &"[REDACTED]")
            .field("issued_at", &self.issued_at)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::{
        DisableTwoFactorForm, ParsedDisableTwoFactor, TWO_FACTOR_TTL, TwoFactorChallenge,
        TwoFactorCode, TwoFactorLoginForm, TwoFactorLoginPayload, TwoFactorVerificationForm,
    };
    use ch_parsing::error::ParseErrorCode;
    use time::{Duration, OffsetDateTime};

    #[test]
    fn accepts_totp_two_factor_codes() {
        let code = TwoFactorCode::parse("654321".to_string()).expect("totp codes should parse");
        assert_eq!(code.totp_value(), Some(654_321));
        assert!(code.backup_code().is_none());
    }

    #[test]
    fn accepts_backup_two_factor_codes() {
        let code =
            TwoFactorCode::parse("ab12-cd34".to_string()).expect("backup codes should parse");
        assert_eq!(code.backup_code(), Some("AB12CD34"));
        assert!(code.totp_value().is_none());
    }

    #[test]
    fn rejects_invalid_two_factor_codes() {
        let error = TwoFactorCode::parse("12ab34!".to_string())
            .expect_err("invalid codes must be rejected");
        assert_eq!(error.code(), ParseErrorCode::InvalidFormat);
        assert_eq!(error.field(), Some("code"));
    }

    #[test]
    fn two_factor_challenges_expire_after_ttl() {
        let challenge = TwoFactorChallenge::new("account-1".to_string());
        let before_expiry = challenge.is_expired(challenge.issued_at + TWO_FACTOR_TTL);
        let after_expiry =
            challenge.is_expired(challenge.issued_at + TWO_FACTOR_TTL + Duration::seconds(1));
        assert!(!before_expiry);
        assert!(after_expiry);
    }

    #[test]
    fn parses_complete_two_factor_payload() {
        let payload = TwoFactorLoginPayload::parse(TwoFactorLoginForm::new(
            "token-1".to_string(),
            "123456".to_string(),
        ))
        .expect("payload should parse");
        assert_eq!(payload.token().as_str(), "token-1");
        assert_eq!(payload.code().totp_value(), Some(123_456));
    }

    #[test]
    fn rejects_short_backup_codes() {
        let error =
            TwoFactorCode::parse("abcd".to_string()).expect_err("short codes should be rejected");
        assert_eq!(error.code(), ParseErrorCode::InvalidFormat);
    }

    #[test]
    fn invalidates_expired_challenge_relative_to_now() {
        let issued_at = OffsetDateTime::now_utc() - TWO_FACTOR_TTL - Duration::seconds(5);
        let challenge = TwoFactorChallenge {
            account_id: "account-2".to_string(),
            token: "token-2".to_string(),
            issued_at,
        };
        assert!(challenge.is_expired(OffsetDateTime::now_utc()));
    }

    #[test]
    fn parses_verification_code() {
        let value = TwoFactorVerificationForm::new("123456".to_string())
            .parse()
            .expect("verification code should parse");
        assert_eq!(value, 123_456);
    }

    #[test]
    fn rejects_invalid_verification_code() {
        let error = TwoFactorVerificationForm::new("12ab".to_string())
            .parse()
            .expect_err("invalid code should be rejected");
        assert_eq!(error.code(), ParseErrorCode::InvalidFormat);
    }

    #[test]
    fn parses_disable_form_with_code() {
        let parsed = ParsedDisableTwoFactor::parse(DisableTwoFactorForm::new(
            Some("654321".to_string()),
            None,
        ))
        .expect("disable form with code should parse");
        assert_eq!(parsed.code(), Some(654_321));
        assert!(parsed.password().is_none());
    }

    #[test]
    fn parses_disable_form_with_password() {
        let password = " secret ".to_owned();
        let parsed =
            ParsedDisableTwoFactor::parse(DisableTwoFactorForm::new(None, Some(password.clone())))
                .expect("disable form with password should parse");
        assert!(parsed.code().is_none());
        assert_eq!(parsed.password(), Some(password.as_str()));
    }

    #[test]
    fn challenge_tokens_preserve_bytes_and_enforce_limits() {
        let raw = " token-with-significant-space ".to_owned();
        let token = super::TwoFactorToken::parse(raw.clone()).expect("token should parse");
        assert_eq!(token.as_str(), raw);

        let error = super::TwoFactorToken::parse("x".repeat(super::MAX_TWO_FACTOR_TOKEN_CHARS + 1))
            .expect_err("oversized challenge tokens must fail");
        assert_eq!(error.code(), ParseErrorCode::TooLong);
    }

    #[test]
    fn oversized_second_factor_inputs_fail_before_normalization() {
        let error = TwoFactorCode::parse(" ".repeat(super::MAX_TWO_FACTOR_CODE_CHARS + 1))
            .expect_err("oversized codes must fail");
        assert_eq!(error.code(), ParseErrorCode::TooLong);

        let error =
            TwoFactorVerificationForm::new("0".repeat(super::MAX_TWO_FACTOR_CODE_CHARS + 1))
                .parse()
                .expect_err("oversized verification codes must fail");
        assert_eq!(error.code(), ParseErrorCode::TooLong);
    }

    #[test]
    fn rejects_disable_form_without_inputs() {
        let error = ParsedDisableTwoFactor::parse(DisableTwoFactorForm::new(None, None))
            .expect_err("disable form without inputs must fail");
        assert_eq!(error.code(), ParseErrorCode::Required);
    }

    #[test]
    fn rejects_disable_form_with_invalid_code() {
        let error = ParsedDisableTwoFactor::parse(DisableTwoFactorForm::new(
            Some("12ab".to_string()),
            None,
        ))
        .expect_err("invalid disable code must be rejected");
        assert_eq!(error.code(), ParseErrorCode::InvalidFormat);
    }
}