1use ch_parsing::error::{ParseError, ParseErrorCode};
2use ch_parsing::input::strings::{enforce_max_len, parse_optional_trimmed, require_trimmed};
3use serde::{Deserialize, Serialize};
4use std::fmt;
5use time::{Duration, OffsetDateTime};
6use uuid::Uuid;
7
8use crate::auth::login::forms::parse_password;
9use crate::messages::AuthMessage;
10
11pub mod api;
13
14pub const BACKUP_CODE_LENGTH: usize = 8;
16pub const BACKUP_CODE_COUNT: usize = 8;
18pub const TWO_FACTOR_TTL: Duration = Duration::minutes(5);
20pub const TOTP_PERIOD_SECONDS: u64 = 30;
22const MAX_TWO_FACTOR_TOKEN_CHARS: usize = 256;
23const MAX_TWO_FACTOR_CODE_CHARS: usize = 64;
24const _: () = {
25 assert!(BACKUP_CODE_LENGTH > 4);
26};
27
28#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
29pub struct TwoFactorLoginForm {
33 #[serde(alias = "form[token]")]
34 token: String,
35 #[serde(alias = "form[code]")]
36 code: String,
37}
38
39impl TwoFactorLoginForm {
40 pub fn new(token: String, code: String) -> Self {
42 Self { token, code }
43 }
44}
45
46#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
47pub struct TwoFactorSetup {
51 success: bool,
52 secret: String,
53 otpauth_uri: String,
54 qr_svg: String,
55 qr_png_data_uri: String,
56}
57
58impl TwoFactorSetup {
59 pub fn new(
61 success: bool,
62 secret: String,
63 otpauth_uri: String,
64 qr_svg: String,
65 qr_png_data_uri: String,
66 ) -> Self {
67 Self {
68 success,
69 secret,
70 otpauth_uri,
71 qr_svg,
72 qr_png_data_uri,
73 }
74 }
75 pub fn success(&self) -> bool {
77 self.success
78 }
79 pub fn secret(&self) -> &str {
81 self.secret.as_str()
82 }
83 pub fn otpauth_uri(&self) -> &str {
85 self.otpauth_uri.as_str()
86 }
87 pub fn qr_svg(&self) -> &str {
89 self.qr_svg.as_str()
90 }
91 pub fn qr_png_data_uri(&self) -> &str {
93 self.qr_png_data_uri.as_str()
94 }
95}
96
97#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
98pub struct TwoFactorVerificationForm {
102 #[serde(alias = "form[code]")]
103 code: String,
104}
105
106impl TwoFactorVerificationForm {
107 pub fn new(code: String) -> Self {
109 Self { code }
110 }
111 pub fn parse(self) -> Result<u32, ParseError> {
113 enforce_max_len(&self.code, MAX_TWO_FACTOR_CODE_CHARS, "code")?;
114 let trimmed = require_trimmed(&self.code, "code")?;
115 if trimmed.len() != 6 || !trimmed.chars().all(|char| char.is_ascii_digit()) {
116 return Err(ParseError::for_field("code", ParseErrorCode::InvalidFormat)
117 .with_parameter("expected", "six_ascii_digits"));
118 }
119 trimmed.parse::<u32>().map_err(|_| {
120 ParseError::for_field("code", ParseErrorCode::InvalidFormat)
121 .with_parameter("expected", "six_ascii_digits")
122 })
123 }
124}
125
126#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
127pub struct TwoFactorVerificationOutcome {
129 success: bool,
130 message: Option<AuthMessage>,
131}
132
133impl TwoFactorVerificationOutcome {
134 pub fn new(success: bool, message: Option<AuthMessage>) -> Self {
136 Self { success, message }
137 }
138 pub fn success(&self) -> bool {
140 self.success
141 }
142 pub fn message(&self) -> Option<&AuthMessage> {
144 self.message.as_ref()
145 }
146}
147
148#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
149pub struct DisableTwoFactorForm {
154 #[serde(alias = "form[code]")]
155 code: Option<String>,
156 #[serde(alias = "form[password]")]
157 password: Option<String>,
158}
159
160impl DisableTwoFactorForm {
161 pub fn new(code: Option<String>, password: Option<String>) -> Self {
163 Self { code, password }
164 }
165}
166
167#[derive(Clone, PartialEq, Eq)]
168pub struct ParsedDisableTwoFactor {
172 code: Option<u32>,
173 password: Option<String>,
174}
175
176impl ParsedDisableTwoFactor {
177 pub fn code(&self) -> Option<u32> {
179 self.code
180 }
181 pub fn password(&self) -> Option<&str> {
183 self.password.as_deref()
184 }
185 pub fn parse(form: DisableTwoFactorForm) -> Result<Self, ParseError> {
187 if let Some(code) = form.code.as_deref() {
188 enforce_max_len(code, MAX_TWO_FACTOR_CODE_CHARS, "code")?;
189 }
190 let code = match parse_optional_trimmed(form.code) {
191 Some(value) => {
192 let trimmed = value.trim();
193 if trimmed.len() != 6 || !trimmed.chars().all(|char| char.is_ascii_digit()) {
194 return Err(ParseError::for_field("code", ParseErrorCode::InvalidFormat)
195 .with_parameter("expected", "six_ascii_digits"));
196 }
197 Some(trimmed.parse::<u32>().map_err(|_| {
198 ParseError::for_field("code", ParseErrorCode::InvalidFormat)
199 .with_parameter("expected", "six_ascii_digits")
200 })?)
201 }
202 None => None,
203 };
204 let password = match form.password {
205 Some(password) => Some(parse_password(password, "password")?),
206 None => None,
207 };
208 if code.is_none() && password.is_none() {
209 return Err(ParseError::for_field("code", ParseErrorCode::Required)
210 .with_parameter("alternative", "password"));
211 }
212 Ok(Self { code, password })
213 }
214}
215
216impl TryFrom<DisableTwoFactorForm> for ParsedDisableTwoFactor {
217 type Error = ParseError;
218 fn try_from(form: DisableTwoFactorForm) -> Result<Self, ParseError> {
219 Self::parse(form)
220 }
221}
222
223#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
224pub struct TwoFactorDisableOutcome {
226 success: bool,
227 message: Option<AuthMessage>,
228}
229
230impl TwoFactorDisableOutcome {
231 pub fn new(success: bool, message: Option<AuthMessage>) -> Self {
233 Self { success, message }
234 }
235 pub fn success(&self) -> bool {
237 self.success
238 }
239 pub fn message(&self) -> Option<&AuthMessage> {
241 self.message.as_ref()
242 }
243}
244
245#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
246pub struct TwoFactorStatus {
248 enabled: bool,
249 has_secret: bool,
250}
251
252impl TwoFactorStatus {
253 pub fn new(enabled: bool, has_secret: bool) -> Self {
255 Self {
256 enabled,
257 has_secret,
258 }
259 }
260 pub fn enabled(&self) -> bool {
262 self.enabled
263 }
264 pub fn has_secret(&self) -> bool {
266 self.has_secret
267 }
268}
269
270#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
271pub struct TwoFactorBackupCodes {
275 success: bool,
276 codes: Vec<String>,
277 message: Option<AuthMessage>,
278}
279
280impl TwoFactorBackupCodes {
281 pub fn new(success: bool, codes: Vec<String>, message: Option<AuthMessage>) -> Self {
283 Self {
284 success,
285 codes,
286 message,
287 }
288 }
289 pub fn success(&self) -> bool {
291 self.success
292 }
293 pub fn codes(&self) -> &[String] {
295 &self.codes
296 }
297 pub fn message(&self) -> Option<&AuthMessage> {
299 self.message.as_ref()
300 }
301}
302
303#[derive(Clone, PartialEq, Eq)]
304pub struct TwoFactorToken(String);
308
309impl TwoFactorToken {
310 pub fn parse(raw: String) -> Result<Self, ParseError> {
312 enforce_max_len(&raw, MAX_TWO_FACTOR_TOKEN_CHARS, "token")?;
313 if raw.trim().is_empty() {
314 return Err(ParseError::for_field("token", ParseErrorCode::Required));
315 }
316 Ok(Self(raw))
317 }
318 pub fn as_str(&self) -> &str {
320 &self.0
321 }
322}
323
324#[derive(Clone, PartialEq, Eq)]
325pub enum TwoFactorCode {
329 Totp(String),
331 Backup(String),
333}
334
335impl TwoFactorCode {
336 pub fn parse(raw: String) -> Result<Self, ParseError> {
338 enforce_max_len(&raw, MAX_TWO_FACTOR_CODE_CHARS, "code")?;
339 let trimmed = require_trimmed(&raw, "code")?;
340 if trimmed.len() == 6 && trimmed.chars().all(|char| char.is_ascii_digit()) {
341 return Ok(Self::Totp(trimmed));
342 }
343 if let Some(normalized) = normalize_backup_code(trimmed.as_str()) {
344 return Ok(Self::Backup(normalized));
345 }
346 Err(ParseError::for_field("code", ParseErrorCode::InvalidFormat)
347 .with_parameter("expected", "totp_or_backup_code"))
348 }
349 pub fn totp_value(&self) -> Option<u32> {
351 match self {
352 Self::Totp(code) => Some(code.parse::<u32>().unwrap_or(0)),
353 Self::Backup(_) => None,
354 }
355 }
356 pub fn backup_code(&self) -> Option<&str> {
358 match self {
359 Self::Totp(_) => None,
360 Self::Backup(code) => Some(code.as_str()),
361 }
362 }
363}
364
365fn normalize_backup_code(raw: &str) -> Option<String> {
366 let mut normalized = String::with_capacity(BACKUP_CODE_LENGTH);
367 for ch in raw.chars() {
368 if ch.is_ascii_alphanumeric() {
369 normalized.push(ch.to_ascii_uppercase());
370 } else if ch == '-' || ch.is_whitespace() {
371 continue;
372 } else {
373 return None;
374 }
375 }
376 if normalized.len() == BACKUP_CODE_LENGTH {
377 Some(normalized)
378 } else {
379 None
380 }
381}
382
383#[derive(Clone, PartialEq, Eq)]
384pub struct TwoFactorLoginPayload {
388 token: TwoFactorToken,
389 code: TwoFactorCode,
390}
391
392impl TwoFactorLoginPayload {
393 pub fn parse(form: TwoFactorLoginForm) -> Result<Self, ParseError> {
395 Ok(Self {
396 token: TwoFactorToken::parse(form.token)?,
397 code: TwoFactorCode::parse(form.code)?,
398 })
399 }
400 pub fn token(&self) -> &TwoFactorToken {
402 &self.token
403 }
404 pub fn code(&self) -> &TwoFactorCode {
406 &self.code
407 }
408}
409
410#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
411pub struct TwoFactorChallenge {
415 account_id: String,
416 token: String,
417 issued_at: OffsetDateTime,
418}
419
420impl TwoFactorChallenge {
421 pub fn new(account_id: String) -> Self {
423 Self {
424 account_id,
425 token: Uuid::new_v4().to_string(),
426 issued_at: OffsetDateTime::now_utc(),
427 }
428 }
429 pub fn account_id(&self) -> &str {
431 self.account_id.as_str()
432 }
433 pub fn token(&self) -> &str {
435 self.token.as_str()
436 }
437 pub fn is_expired(&self, now: OffsetDateTime) -> bool {
439 now > self.issued_at + TWO_FACTOR_TTL
440 }
441}
442
443impl fmt::Debug for TwoFactorLoginForm {
444 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
445 formatter
446 .debug_struct("TwoFactorLoginForm")
447 .field("token", &"[REDACTED]")
448 .field("code", &"[REDACTED]")
449 .finish()
450 }
451}
452
453impl fmt::Debug for TwoFactorSetup {
454 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
455 formatter
456 .debug_struct("TwoFactorSetup")
457 .field("success", &self.success)
458 .field("secret", &"[REDACTED]")
459 .field("otpauth_uri", &"[REDACTED]")
460 .field("has_qr_svg", &!self.qr_svg.is_empty())
461 .field("has_qr_data_uri", &!self.qr_png_data_uri.is_empty())
462 .finish()
463 }
464}
465
466impl fmt::Debug for TwoFactorVerificationForm {
467 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
468 formatter
469 .debug_struct("TwoFactorVerificationForm")
470 .field("code", &"[REDACTED]")
471 .finish()
472 }
473}
474
475impl fmt::Debug for DisableTwoFactorForm {
476 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
477 formatter
478 .debug_struct("DisableTwoFactorForm")
479 .field("has_code", &self.code.is_some())
480 .field("has_password", &self.password.is_some())
481 .finish()
482 }
483}
484
485impl fmt::Debug for ParsedDisableTwoFactor {
486 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
487 formatter
488 .debug_struct("ParsedDisableTwoFactor")
489 .field("has_code", &self.code.is_some())
490 .field("has_password", &self.password.is_some())
491 .finish()
492 }
493}
494
495impl fmt::Debug for TwoFactorBackupCodes {
496 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
497 formatter
498 .debug_struct("TwoFactorBackupCodes")
499 .field("success", &self.success)
500 .field("code_count", &self.codes.len())
501 .field("message", &self.message)
502 .finish()
503 }
504}
505
506impl fmt::Debug for TwoFactorToken {
507 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
508 formatter
509 .debug_tuple("TwoFactorToken")
510 .field(&"[REDACTED]")
511 .finish()
512 }
513}
514
515impl fmt::Debug for TwoFactorCode {
516 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
517 formatter.write_str(match self {
518 Self::Totp(_) => "TwoFactorCode::Totp([REDACTED])",
519 Self::Backup(_) => "TwoFactorCode::Backup([REDACTED])",
520 })
521 }
522}
523
524impl fmt::Debug for TwoFactorLoginPayload {
525 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
526 formatter
527 .debug_struct("TwoFactorLoginPayload")
528 .field("token", &"[REDACTED]")
529 .field("code", &self.code)
530 .finish()
531 }
532}
533
534impl fmt::Debug for TwoFactorChallenge {
535 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
536 formatter
537 .debug_struct("TwoFactorChallenge")
538 .field("account_id", &self.account_id)
539 .field("token", &"[REDACTED]")
540 .field("issued_at", &self.issued_at)
541 .finish()
542 }
543}
544
545#[cfg(test)]
546mod tests {
547 use super::{
548 DisableTwoFactorForm, ParsedDisableTwoFactor, TWO_FACTOR_TTL, TwoFactorChallenge,
549 TwoFactorCode, TwoFactorLoginForm, TwoFactorLoginPayload, TwoFactorVerificationForm,
550 };
551 use ch_parsing::error::ParseErrorCode;
552 use time::{Duration, OffsetDateTime};
553
554 #[test]
555 fn accepts_totp_two_factor_codes() {
556 let code = TwoFactorCode::parse("654321".to_string()).expect("totp codes should parse");
557 assert_eq!(code.totp_value(), Some(654_321));
558 assert!(code.backup_code().is_none());
559 }
560
561 #[test]
562 fn accepts_backup_two_factor_codes() {
563 let code =
564 TwoFactorCode::parse("ab12-cd34".to_string()).expect("backup codes should parse");
565 assert_eq!(code.backup_code(), Some("AB12CD34"));
566 assert!(code.totp_value().is_none());
567 }
568
569 #[test]
570 fn rejects_invalid_two_factor_codes() {
571 let error = TwoFactorCode::parse("12ab34!".to_string())
572 .expect_err("invalid codes must be rejected");
573 assert_eq!(error.code(), ParseErrorCode::InvalidFormat);
574 assert_eq!(error.field(), Some("code"));
575 }
576
577 #[test]
578 fn two_factor_challenges_expire_after_ttl() {
579 let challenge = TwoFactorChallenge::new("account-1".to_string());
580 let before_expiry = challenge.is_expired(challenge.issued_at + TWO_FACTOR_TTL);
581 let after_expiry =
582 challenge.is_expired(challenge.issued_at + TWO_FACTOR_TTL + Duration::seconds(1));
583 assert!(!before_expiry);
584 assert!(after_expiry);
585 }
586
587 #[test]
588 fn parses_complete_two_factor_payload() {
589 let payload = TwoFactorLoginPayload::parse(TwoFactorLoginForm::new(
590 "token-1".to_string(),
591 "123456".to_string(),
592 ))
593 .expect("payload should parse");
594 assert_eq!(payload.token().as_str(), "token-1");
595 assert_eq!(payload.code().totp_value(), Some(123_456));
596 }
597
598 #[test]
599 fn rejects_short_backup_codes() {
600 let error =
601 TwoFactorCode::parse("abcd".to_string()).expect_err("short codes should be rejected");
602 assert_eq!(error.code(), ParseErrorCode::InvalidFormat);
603 }
604
605 #[test]
606 fn invalidates_expired_challenge_relative_to_now() {
607 let issued_at = OffsetDateTime::now_utc() - TWO_FACTOR_TTL - Duration::seconds(5);
608 let challenge = TwoFactorChallenge {
609 account_id: "account-2".to_string(),
610 token: "token-2".to_string(),
611 issued_at,
612 };
613 assert!(challenge.is_expired(OffsetDateTime::now_utc()));
614 }
615
616 #[test]
617 fn parses_verification_code() {
618 let value = TwoFactorVerificationForm::new("123456".to_string())
619 .parse()
620 .expect("verification code should parse");
621 assert_eq!(value, 123_456);
622 }
623
624 #[test]
625 fn rejects_invalid_verification_code() {
626 let error = TwoFactorVerificationForm::new("12ab".to_string())
627 .parse()
628 .expect_err("invalid code should be rejected");
629 assert_eq!(error.code(), ParseErrorCode::InvalidFormat);
630 }
631
632 #[test]
633 fn parses_disable_form_with_code() {
634 let parsed = ParsedDisableTwoFactor::parse(DisableTwoFactorForm::new(
635 Some("654321".to_string()),
636 None,
637 ))
638 .expect("disable form with code should parse");
639 assert_eq!(parsed.code(), Some(654_321));
640 assert!(parsed.password().is_none());
641 }
642
643 #[test]
644 fn parses_disable_form_with_password() {
645 let password = " secret ".to_owned();
646 let parsed =
647 ParsedDisableTwoFactor::parse(DisableTwoFactorForm::new(None, Some(password.clone())))
648 .expect("disable form with password should parse");
649 assert!(parsed.code().is_none());
650 assert_eq!(parsed.password(), Some(password.as_str()));
651 }
652
653 #[test]
654 fn challenge_tokens_preserve_bytes_and_enforce_limits() {
655 let raw = " token-with-significant-space ".to_owned();
656 let token = super::TwoFactorToken::parse(raw.clone()).expect("token should parse");
657 assert_eq!(token.as_str(), raw);
658
659 let error = super::TwoFactorToken::parse("x".repeat(super::MAX_TWO_FACTOR_TOKEN_CHARS + 1))
660 .expect_err("oversized challenge tokens must fail");
661 assert_eq!(error.code(), ParseErrorCode::TooLong);
662 }
663
664 #[test]
665 fn oversized_second_factor_inputs_fail_before_normalization() {
666 let error = TwoFactorCode::parse(" ".repeat(super::MAX_TWO_FACTOR_CODE_CHARS + 1))
667 .expect_err("oversized codes must fail");
668 assert_eq!(error.code(), ParseErrorCode::TooLong);
669
670 let error =
671 TwoFactorVerificationForm::new("0".repeat(super::MAX_TWO_FACTOR_CODE_CHARS + 1))
672 .parse()
673 .expect_err("oversized verification codes must fail");
674 assert_eq!(error.code(), ParseErrorCode::TooLong);
675 }
676
677 #[test]
678 fn rejects_disable_form_without_inputs() {
679 let error = ParsedDisableTwoFactor::parse(DisableTwoFactorForm::new(None, None))
680 .expect_err("disable form without inputs must fail");
681 assert_eq!(error.code(), ParseErrorCode::Required);
682 }
683
684 #[test]
685 fn rejects_disable_form_with_invalid_code() {
686 let error = ParsedDisableTwoFactor::parse(DisableTwoFactorForm::new(
687 Some("12ab".to_string()),
688 None,
689 ))
690 .expect_err("invalid disable code must be rejected");
691 assert_eq!(error.code(), ParseErrorCode::InvalidFormat);
692 }
693}