use ch_parsing::error::ParseError;
use ch_parsing::error::ParseErrorCode;
use ch_parsing::input::account_hash::AccountHash;
use ch_parsing::input::email::parse_required_email;
use ch_parsing::input::strings::{enforce_max_len, parse_optional_trimmed, require_trimmed};
use serde::{Deserialize, Serialize};
use std::fmt;
use crate::messages::AuthMessage;
use crate::status::AuthDenyReason;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum LoginErrorCode {
#[default]
None,
RateLimited,
CredentialsInvalid,
AccountDenied,
TwoFactorRequired,
TwoFactorInvalid,
TwoFactorExpired,
TwoFactorMissing,
TwoFactorUnavailable,
TwoFactorDisabled,
}
impl LoginErrorCode {
pub fn message(self) -> Option<AuthMessage> {
let key = match self {
Self::None => return None,
Self::RateLimited => "auth.login.feedback.rate_limited",
Self::CredentialsInvalid => "auth.login.feedback.credentials_invalid",
Self::AccountDenied => "auth.access.denied.unknown",
Self::TwoFactorRequired => "auth.login.feedback.two_factor_required",
Self::TwoFactorInvalid => "auth.login.feedback.two_factor_invalid",
Self::TwoFactorExpired => "auth.login.feedback.two_factor_expired",
Self::TwoFactorMissing => "auth.login.feedback.two_factor_missing",
Self::TwoFactorUnavailable => "auth.login.feedback.two_factor_unavailable",
Self::TwoFactorDisabled => "auth.login.feedback.two_factor_disabled",
};
Some(AuthMessage::from_static(key))
}
}
const MAX_LOGIN_IDENTIFIER_CHARS: usize = 320;
const MAX_PASSWORD_CHARS: usize = 1_024;
const MAX_REGISTRATION_NAME_CHARS: usize = 256;
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct LoginFormData {
pub identifier: String,
pub password: String,
}
impl LoginFormData {
pub fn parse(self) -> Result<ParsedLoginFormData, ParseError> {
let identifier = LoginIdentifier::parse(self.identifier)?;
let password = parse_password(self.password, "password")?;
Ok(ParsedLoginFormData {
identifier,
password,
})
}
}
impl fmt::Debug for LoginFormData {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("LoginFormData")
.field("identifier", &self.identifier)
.field("password", &"[REDACTED]")
.finish()
}
}
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RegisterFormData {
pub email: Option<String>,
pub full_name: Option<String>,
pub password: String,
}
impl RegisterFormData {
pub fn parse(self) -> Result<ParsedRegisterFormData, ParseError> {
if let Some(email) = self.email.as_deref() {
enforce_max_len(email, MAX_LOGIN_IDENTIFIER_CHARS, "email")?;
}
if let Some(full_name) = self.full_name.as_deref() {
enforce_max_len(full_name, MAX_REGISTRATION_NAME_CHARS, "full_name")?;
}
let email = parse_optional_trimmed(self.email);
let email = match email {
Some(value) => Some(parse_required_email(value.as_str(), "email")?),
None => None,
};
let full_name = parse_optional_trimmed(self.full_name);
let password = parse_password(self.password, "password")?;
Ok(ParsedRegisterFormData {
email,
full_name,
password,
})
}
}
impl fmt::Debug for RegisterFormData {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("RegisterFormData")
.field("email", &self.email)
.field("full_name", &self.full_name)
.field("password", &"[REDACTED]")
.finish()
}
}
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct LoginOutcome {
pub success: bool,
pub message: Option<AuthMessage>,
pub error_code: LoginErrorCode,
pub deny_reason: Option<AuthDenyReason>,
pub captcha_valid: bool,
pub requires_two_factor: bool,
pub two_factor_token: Option<String>,
}
impl fmt::Debug for LoginOutcome {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("LoginOutcome")
.field("success", &self.success)
.field("message", &self.message)
.field("error_code", &self.error_code)
.field("deny_reason", &self.deny_reason)
.field("captcha_valid", &self.captcha_valid)
.field("requires_two_factor", &self.requires_two_factor)
.field("has_two_factor_token", &self.two_factor_token.is_some())
.finish()
}
}
impl LoginOutcome {
pub fn success(message: Option<AuthMessage>, captcha_valid: bool) -> Self {
Self {
success: true,
message,
error_code: LoginErrorCode::None,
deny_reason: None,
captcha_valid,
requires_two_factor: false,
two_factor_token: None,
}
}
pub fn success_with_two_factor(
message: Option<AuthMessage>,
captcha_valid: bool,
token: Option<String>,
) -> Self {
Self {
success: true,
message,
error_code: LoginErrorCode::TwoFactorRequired,
deny_reason: None,
captcha_valid,
requires_two_factor: true,
two_factor_token: token,
}
}
pub fn failure(
error_code: LoginErrorCode,
message: Option<AuthMessage>,
captcha_valid: bool,
) -> Self {
Self {
success: false,
message,
error_code,
deny_reason: None,
captcha_valid,
requires_two_factor: false,
two_factor_token: None,
}
}
pub fn failure_with_two_factor(
error_code: LoginErrorCode,
message: Option<AuthMessage>,
captcha_valid: bool,
token: Option<String>,
) -> Self {
let requires_two_factor = token.is_some();
Self {
success: false,
message,
error_code,
deny_reason: None,
captcha_valid,
requires_two_factor,
two_factor_token: token,
}
}
pub fn account_denied(
reason: AuthDenyReason,
message: Option<AuthMessage>,
captcha_valid: bool,
) -> Self {
Self {
success: false,
message,
error_code: LoginErrorCode::AccountDenied,
deny_reason: Some(reason),
captcha_valid,
requires_two_factor: false,
two_factor_token: None,
}
}
pub fn two_factor_invalid(captcha_valid: bool, token: Option<String>) -> Self {
let message = AuthMessage::from_static("auth.login.feedback.two_factor_invalid");
Self::failure_with_two_factor(
LoginErrorCode::TwoFactorInvalid,
Some(message),
captcha_valid,
token,
)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RegisterOutcome {
pub success: bool,
pub message: Option<AuthMessage>,
pub account_hash: Option<String>,
}
#[derive(Clone, PartialEq, Eq)]
pub struct ParsedLoginFormData {
pub identifier: LoginIdentifier,
pub password: String,
}
impl fmt::Debug for ParsedLoginFormData {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ParsedLoginFormData")
.field("identifier", &self.identifier)
.field("password", &"[REDACTED]")
.finish()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LoginIdentifier {
Hash(AccountHash),
Email(String),
}
impl LoginIdentifier {
pub fn parse(raw: String) -> Result<Self, ParseError> {
enforce_max_len(&raw, MAX_LOGIN_IDENTIFIER_CHARS, "identifier")?;
let trimmed = require_trimmed(raw.as_str(), "identifier")?;
let normalized = trimmed.to_uppercase();
if let Ok(hash) = AccountHash::parse(normalized.as_str(), "identifier") {
return Ok(Self::Hash(hash));
}
let email = parse_required_email(trimmed.as_str(), "identifier")?;
Ok(Self::Email(email))
}
pub fn as_str(&self) -> &str {
match self {
Self::Hash(hash) => hash.as_str(),
Self::Email(email) => email.as_str(),
}
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct ParsedRegisterFormData {
pub email: Option<String>,
pub full_name: Option<String>,
pub password: String,
}
impl fmt::Debug for ParsedRegisterFormData {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ParsedRegisterFormData")
.field("email", &self.email)
.field("full_name", &self.full_name)
.field("password", &"[REDACTED]")
.finish()
}
}
pub(crate) fn parse_password(raw: String, field: &'static str) -> Result<String, ParseError> {
enforce_max_len(&raw, MAX_PASSWORD_CHARS, field)?;
if raw.trim().is_empty() {
return Err(ParseError::for_field(field, ParseErrorCode::Required));
}
Ok(raw)
}
#[cfg(test)]
mod tests {
use super::LoginErrorCode;
use super::{LoginFormData, LoginOutcome, MAX_PASSWORD_CHARS, RegisterFormData};
use ch_parsing::error::ParseErrorCode;
#[test]
fn login_password_preserves_every_accepted_character() {
let password = " leading and trailing whitespace\t\n".to_owned();
let parsed = LoginFormData {
identifier: "person@example.com".to_owned(),
password: password.clone(),
}
.parse()
.expect("password should parse");
assert_eq!(parsed.password, password);
}
#[test]
fn registration_password_preserves_every_accepted_character() {
let password = " pass phrase ".to_owned();
let parsed = RegisterFormData {
email: Some("person@example.com".to_owned()),
full_name: None,
password: password.clone(),
}
.parse()
.expect("password should parse");
assert_eq!(parsed.password, password);
}
#[test]
fn rejects_display_addresses_in_login_and_registration() {
let login = LoginFormData {
identifier: "Person <person@example.com>".to_owned(),
password: "correct password".to_owned(),
}
.parse()
.expect_err("login requires an address without a display name");
assert_eq!(login.code(), ParseErrorCode::InvalidFormat);
assert_eq!(login.field(), Some("identifier"));
let registration = RegisterFormData {
email: Some("Person <person@example.com>".to_owned()),
full_name: None,
password: "correct password".to_owned(),
}
.parse()
.expect_err("registration requires an address without a display name");
assert_eq!(registration.code(), ParseErrorCode::InvalidFormat);
assert_eq!(registration.field(), Some("email"));
}
#[test]
fn rejects_whitespace_only_and_oversized_passwords() {
let whitespace = LoginFormData {
identifier: "person@example.com".to_owned(),
password: " \t\n ".to_owned(),
}
.parse()
.expect_err("whitespace-only passwords must fail");
assert_eq!(whitespace.code(), ParseErrorCode::Required);
let oversized = LoginFormData {
identifier: "person@example.com".to_owned(),
password: "x".repeat(MAX_PASSWORD_CHARS + 1),
}
.parse()
.expect_err("oversized passwords must fail");
assert_eq!(oversized.code(), ParseErrorCode::TooLong);
}
#[test]
fn login_outcome_debug_never_exposes_two_factor_token() {
let outcome = LoginOutcome::failure_with_two_factor(
LoginErrorCode::TwoFactorInvalid,
None,
true,
Some("secret-challenge-token".to_owned()),
);
let debug = format!("{outcome:?}");
assert!(!debug.contains("secret-challenge-token"));
assert!(debug.contains("has_two_factor_token: true"));
}
}