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;
pub mod api;
pub const BACKUP_CODE_LENGTH: usize = 8;
pub const BACKUP_CODE_COUNT: usize = 8;
pub const TWO_FACTOR_TTL: Duration = Duration::minutes(5);
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)]
pub struct TwoFactorLoginForm {
#[serde(alias = "form[token]")]
token: String,
#[serde(alias = "form[code]")]
code: String,
}
impl TwoFactorLoginForm {
pub fn new(token: String, code: String) -> Self {
Self { token, code }
}
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TwoFactorSetup {
success: bool,
secret: String,
otpauth_uri: String,
qr_svg: String,
qr_png_data_uri: String,
}
impl TwoFactorSetup {
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,
}
}
pub fn success(&self) -> bool {
self.success
}
pub fn secret(&self) -> &str {
self.secret.as_str()
}
pub fn otpauth_uri(&self) -> &str {
self.otpauth_uri.as_str()
}
pub fn qr_svg(&self) -> &str {
self.qr_svg.as_str()
}
pub fn qr_png_data_uri(&self) -> &str {
self.qr_png_data_uri.as_str()
}
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TwoFactorVerificationForm {
#[serde(alias = "form[code]")]
code: String,
}
impl TwoFactorVerificationForm {
pub fn new(code: String) -> Self {
Self { 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)]
pub struct TwoFactorVerificationOutcome {
success: bool,
message: Option<AuthMessage>,
}
impl TwoFactorVerificationOutcome {
pub fn new(success: bool, message: Option<AuthMessage>) -> Self {
Self { success, message }
}
pub fn success(&self) -> bool {
self.success
}
pub fn message(&self) -> Option<&AuthMessage> {
self.message.as_ref()
}
}
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct DisableTwoFactorForm {
#[serde(alias = "form[code]")]
code: Option<String>,
#[serde(alias = "form[password]")]
password: Option<String>,
}
impl DisableTwoFactorForm {
pub fn new(code: Option<String>, password: Option<String>) -> Self {
Self { code, password }
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct ParsedDisableTwoFactor {
code: Option<u32>,
password: Option<String>,
}
impl ParsedDisableTwoFactor {
pub fn code(&self) -> Option<u32> {
self.code
}
pub fn password(&self) -> Option<&str> {
self.password.as_deref()
}
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)]
pub struct TwoFactorDisableOutcome {
success: bool,
message: Option<AuthMessage>,
}
impl TwoFactorDisableOutcome {
pub fn new(success: bool, message: Option<AuthMessage>) -> Self {
Self { success, message }
}
pub fn success(&self) -> bool {
self.success
}
pub fn message(&self) -> Option<&AuthMessage> {
self.message.as_ref()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TwoFactorStatus {
enabled: bool,
has_secret: bool,
}
impl TwoFactorStatus {
pub fn new(enabled: bool, has_secret: bool) -> Self {
Self {
enabled,
has_secret,
}
}
pub fn enabled(&self) -> bool {
self.enabled
}
pub fn has_secret(&self) -> bool {
self.has_secret
}
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TwoFactorBackupCodes {
success: bool,
codes: Vec<String>,
message: Option<AuthMessage>,
}
impl TwoFactorBackupCodes {
pub fn new(success: bool, codes: Vec<String>, message: Option<AuthMessage>) -> Self {
Self {
success,
codes,
message,
}
}
pub fn success(&self) -> bool {
self.success
}
pub fn codes(&self) -> &[String] {
&self.codes
}
pub fn message(&self) -> Option<&AuthMessage> {
self.message.as_ref()
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct TwoFactorToken(String);
impl TwoFactorToken {
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))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Clone, PartialEq, Eq)]
pub enum TwoFactorCode {
Totp(String),
Backup(String),
}
impl TwoFactorCode {
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"))
}
pub fn totp_value(&self) -> Option<u32> {
match self {
Self::Totp(code) => Some(code.parse::<u32>().unwrap_or(0)),
Self::Backup(_) => None,
}
}
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)]
pub struct TwoFactorLoginPayload {
token: TwoFactorToken,
code: TwoFactorCode,
}
impl TwoFactorLoginPayload {
pub fn parse(form: TwoFactorLoginForm) -> Result<Self, ParseError> {
Ok(Self {
token: TwoFactorToken::parse(form.token)?,
code: TwoFactorCode::parse(form.code)?,
})
}
pub fn token(&self) -> &TwoFactorToken {
&self.token
}
pub fn code(&self) -> &TwoFactorCode {
&self.code
}
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TwoFactorChallenge {
account_id: String,
token: String,
issued_at: OffsetDateTime,
}
impl TwoFactorChallenge {
pub fn new(account_id: String) -> Self {
Self {
account_id,
token: Uuid::new_v4().to_string(),
issued_at: OffsetDateTime::now_utc(),
}
}
pub fn account_id(&self) -> &str {
self.account_id.as_str()
}
pub fn token(&self) -> &str {
self.token.as_str()
}
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);
}
}