Skip to main content

ch_auth/auth/login/
forms.rs

1use ch_parsing::error::ParseError;
2use ch_parsing::error::ParseErrorCode;
3use ch_parsing::input::account_hash::AccountHash;
4use ch_parsing::input::email::parse_required_email;
5use ch_parsing::input::strings::{enforce_max_len, parse_optional_trimmed, require_trimmed};
6use serde::{Deserialize, Serialize};
7use std::fmt;
8
9use crate::messages::AuthMessage;
10use crate::status::AuthDenyReason;
11
12/// Enumerates machine-readable login error codes.
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
14#[serde(rename_all = "snake_case")]
15pub enum LoginErrorCode {
16    /// No error occurred for the outcome.
17    #[default]
18    None,
19    /// Too many attempts were made in a short period.
20    RateLimited,
21    /// The submitted credentials did not match an account.
22    CredentialsInvalid,
23    /// The account is not permitted to authenticate.
24    AccountDenied,
25    /// The account requires a two-factor challenge before login succeeds.
26    TwoFactorRequired,
27    /// The provided two-factor code was invalid.
28    TwoFactorInvalid,
29    /// The two-factor challenge expired before completion.
30    TwoFactorExpired,
31    /// No active two-factor challenge was found for the session.
32    TwoFactorMissing,
33    /// Two-factor authentication is unavailable for the account.
34    TwoFactorUnavailable,
35    /// Two-factor authentication is disabled for the account.
36    TwoFactorDisabled,
37}
38
39impl LoginErrorCode {
40    /// Returns the stable default message for this failure or challenge.
41    pub fn message(self) -> Option<AuthMessage> {
42        let key = match self {
43            Self::None => return None,
44            Self::RateLimited => "auth.login.feedback.rate_limited",
45            Self::CredentialsInvalid => "auth.login.feedback.credentials_invalid",
46            Self::AccountDenied => "auth.access.denied.unknown",
47            Self::TwoFactorRequired => "auth.login.feedback.two_factor_required",
48            Self::TwoFactorInvalid => "auth.login.feedback.two_factor_invalid",
49            Self::TwoFactorExpired => "auth.login.feedback.two_factor_expired",
50            Self::TwoFactorMissing => "auth.login.feedback.two_factor_missing",
51            Self::TwoFactorUnavailable => "auth.login.feedback.two_factor_unavailable",
52            Self::TwoFactorDisabled => "auth.login.feedback.two_factor_disabled",
53        };
54        Some(AuthMessage::from_static(key))
55    }
56}
57
58const MAX_LOGIN_IDENTIFIER_CHARS: usize = 320;
59// Passwords are intentionally not normalized. This generous bound limits
60// password-hashing work without changing ordinary passphrases.
61const MAX_PASSWORD_CHARS: usize = 1_024;
62const MAX_REGISTRATION_NAME_CHARS: usize = 256;
63
64#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
65/// Raw credentials submitted to a login endpoint.
66///
67/// Its custom [`fmt::Debug`] implementation redacts the password.
68pub struct LoginFormData {
69    /// Account hash or email address used to identify the account.
70    pub identifier: String,
71    /// Plaintext password supplied by the caller.
72    pub password: String,
73}
74
75impl LoginFormData {
76    /// Validates and normalizes the submitted credentials.
77    pub fn parse(self) -> Result<ParsedLoginFormData, ParseError> {
78        let identifier = LoginIdentifier::parse(self.identifier)?;
79        let password = parse_password(self.password, "password")?;
80        Ok(ParsedLoginFormData {
81            identifier,
82            password,
83        })
84    }
85}
86
87impl fmt::Debug for LoginFormData {
88    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
89        formatter
90            .debug_struct("LoginFormData")
91            .field("identifier", &self.identifier)
92            .field("password", &"[REDACTED]")
93            .finish()
94    }
95}
96
97#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
98/// Raw fields submitted to a registration endpoint.
99///
100/// Its custom [`fmt::Debug`] implementation redacts the password.
101pub struct RegisterFormData {
102    /// Optional account email address.
103    pub email: Option<String>,
104    /// Optional human-readable account name.
105    pub full_name: Option<String>,
106    /// Plaintext password supplied by the caller.
107    pub password: String,
108}
109
110impl RegisterFormData {
111    /// Validates and normalizes the submitted registration fields.
112    pub fn parse(self) -> Result<ParsedRegisterFormData, ParseError> {
113        if let Some(email) = self.email.as_deref() {
114            enforce_max_len(email, MAX_LOGIN_IDENTIFIER_CHARS, "email")?;
115        }
116        if let Some(full_name) = self.full_name.as_deref() {
117            enforce_max_len(full_name, MAX_REGISTRATION_NAME_CHARS, "full_name")?;
118        }
119        let email = parse_optional_trimmed(self.email);
120        let email = match email {
121            Some(value) => Some(parse_required_email(value.as_str(), "email")?),
122            None => None,
123        };
124        let full_name = parse_optional_trimmed(self.full_name);
125        let password = parse_password(self.password, "password")?;
126        Ok(ParsedRegisterFormData {
127            email,
128            full_name,
129            password,
130        })
131    }
132}
133
134impl fmt::Debug for RegisterFormData {
135    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
136        formatter
137            .debug_struct("RegisterFormData")
138            .field("email", &self.email)
139            .field("full_name", &self.full_name)
140            .field("password", &"[REDACTED]")
141            .finish()
142    }
143}
144
145#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
146/// Serializable result of a login attempt.
147pub struct LoginOutcome {
148    /// Whether the current login step succeeded.
149    pub success: bool,
150    /// Optional translatable feedback for the caller.
151    pub message: Option<AuthMessage>,
152    /// Stable machine-readable outcome code.
153    pub error_code: LoginErrorCode,
154    /// Authorization reason when the account was denied.
155    pub deny_reason: Option<AuthDenyReason>,
156    /// Whether the associated CAPTCHA response was accepted.
157    pub captcha_valid: bool,
158    /// Whether the caller must complete a two-factor challenge.
159    pub requires_two_factor: bool,
160    /// Opaque token for a pending two-factor challenge.
161    pub two_factor_token: Option<String>,
162}
163
164impl fmt::Debug for LoginOutcome {
165    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
166        formatter
167            .debug_struct("LoginOutcome")
168            .field("success", &self.success)
169            .field("message", &self.message)
170            .field("error_code", &self.error_code)
171            .field("deny_reason", &self.deny_reason)
172            .field("captcha_valid", &self.captcha_valid)
173            .field("requires_two_factor", &self.requires_two_factor)
174            .field("has_two_factor_token", &self.two_factor_token.is_some())
175            .finish()
176    }
177}
178
179impl LoginOutcome {
180    /// Creates a completed successful login outcome.
181    pub fn success(message: Option<AuthMessage>, captcha_valid: bool) -> Self {
182        Self {
183            success: true,
184            message,
185            error_code: LoginErrorCode::None,
186            deny_reason: None,
187            captcha_valid,
188            requires_two_factor: false,
189            two_factor_token: None,
190        }
191    }
192
193    /// Creates a successful first-step outcome that requires two-factor authentication.
194    pub fn success_with_two_factor(
195        message: Option<AuthMessage>,
196        captcha_valid: bool,
197        token: Option<String>,
198    ) -> Self {
199        Self {
200            success: true,
201            message,
202            error_code: LoginErrorCode::TwoFactorRequired,
203            deny_reason: None,
204            captcha_valid,
205            requires_two_factor: true,
206            two_factor_token: token,
207        }
208    }
209
210    /// Creates a failed login outcome without a pending two-factor challenge.
211    pub fn failure(
212        error_code: LoginErrorCode,
213        message: Option<AuthMessage>,
214        captcha_valid: bool,
215    ) -> Self {
216        Self {
217            success: false,
218            message,
219            error_code,
220            deny_reason: None,
221            captcha_valid,
222            requires_two_factor: false,
223            two_factor_token: None,
224        }
225    }
226
227    /// Creates a failed login outcome while preserving an optional challenge token.
228    pub fn failure_with_two_factor(
229        error_code: LoginErrorCode,
230        message: Option<AuthMessage>,
231        captcha_valid: bool,
232        token: Option<String>,
233    ) -> Self {
234        let requires_two_factor = token.is_some();
235        Self {
236            success: false,
237            message,
238            error_code,
239            deny_reason: None,
240            captcha_valid,
241            requires_two_factor,
242            two_factor_token: token,
243        }
244    }
245
246    /// Creates an outcome for a valid account that authorization policy denied.
247    pub fn account_denied(
248        reason: AuthDenyReason,
249        message: Option<AuthMessage>,
250        captcha_valid: bool,
251    ) -> Self {
252        Self {
253            success: false,
254            message,
255            error_code: LoginErrorCode::AccountDenied,
256            deny_reason: Some(reason),
257            captcha_valid,
258            requires_two_factor: false,
259            two_factor_token: None,
260        }
261    }
262
263    /// Creates an outcome for an invalid two-factor code.
264    pub fn two_factor_invalid(captcha_valid: bool, token: Option<String>) -> Self {
265        let message = AuthMessage::from_static("auth.login.feedback.two_factor_invalid");
266        Self::failure_with_two_factor(
267            LoginErrorCode::TwoFactorInvalid,
268            Some(message),
269            captcha_valid,
270            token,
271        )
272    }
273}
274
275#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
276/// Serializable result of a registration attempt.
277pub struct RegisterOutcome {
278    /// Whether account creation succeeded.
279    pub success: bool,
280    /// Optional translatable feedback for the caller.
281    pub message: Option<AuthMessage>,
282    /// Public account hash assigned to the created account.
283    pub account_hash: Option<String>,
284}
285
286#[derive(Clone, PartialEq, Eq)]
287/// Validated and normalized login credentials.
288///
289/// Its custom [`fmt::Debug`] implementation redacts the password.
290pub struct ParsedLoginFormData {
291    /// Normalized account identifier.
292    pub identifier: LoginIdentifier,
293    /// Non-empty plaintext password supplied by the caller.
294    pub password: String,
295}
296
297impl fmt::Debug for ParsedLoginFormData {
298    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
299        formatter
300            .debug_struct("ParsedLoginFormData")
301            .field("identifier", &self.identifier)
302            .field("password", &"[REDACTED]")
303            .finish()
304    }
305}
306
307#[derive(Clone, Debug, PartialEq, Eq)]
308/// Normalized identifier accepted by the login workflow.
309pub enum LoginIdentifier {
310    /// Valid public account hash.
311    Hash(AccountHash),
312    /// Normalized email address.
313    Email(String),
314}
315
316impl LoginIdentifier {
317    /// Parses a raw account hash or email address.
318    pub fn parse(raw: String) -> Result<Self, ParseError> {
319        enforce_max_len(&raw, MAX_LOGIN_IDENTIFIER_CHARS, "identifier")?;
320        let trimmed = require_trimmed(raw.as_str(), "identifier")?;
321        let normalized = trimmed.to_uppercase();
322        if let Ok(hash) = AccountHash::parse(normalized.as_str(), "identifier") {
323            return Ok(Self::Hash(hash));
324        }
325        let email = parse_required_email(trimmed.as_str(), "identifier")?;
326        Ok(Self::Email(email))
327    }
328
329    /// Returns the normalized identifier as text.
330    pub fn as_str(&self) -> &str {
331        match self {
332            Self::Hash(hash) => hash.as_str(),
333            Self::Email(email) => email.as_str(),
334        }
335    }
336}
337
338#[derive(Clone, PartialEq, Eq)]
339/// Validated and normalized registration fields.
340///
341/// Its custom [`fmt::Debug`] implementation redacts the password.
342pub struct ParsedRegisterFormData {
343    /// Normalized optional email address.
344    pub email: Option<String>,
345    /// Trimmed optional human-readable account name.
346    pub full_name: Option<String>,
347    /// Non-empty plaintext password supplied by the caller.
348    pub password: String,
349}
350
351impl fmt::Debug for ParsedRegisterFormData {
352    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
353        formatter
354            .debug_struct("ParsedRegisterFormData")
355            .field("email", &self.email)
356            .field("full_name", &self.full_name)
357            .field("password", &"[REDACTED]")
358            .finish()
359    }
360}
361
362/// Validates a password without normalizing or otherwise mutating it.
363pub(crate) fn parse_password(raw: String, field: &'static str) -> Result<String, ParseError> {
364    enforce_max_len(&raw, MAX_PASSWORD_CHARS, field)?;
365    if raw.trim().is_empty() {
366        return Err(ParseError::for_field(field, ParseErrorCode::Required));
367    }
368    Ok(raw)
369}
370
371#[cfg(test)]
372mod tests {
373    use super::LoginErrorCode;
374    use super::{LoginFormData, LoginOutcome, MAX_PASSWORD_CHARS, RegisterFormData};
375    use ch_parsing::error::ParseErrorCode;
376
377    #[test]
378    fn login_password_preserves_every_accepted_character() {
379        let password = "  leading and trailing whitespace\t\n".to_owned();
380        let parsed = LoginFormData {
381            identifier: "person@example.com".to_owned(),
382            password: password.clone(),
383        }
384        .parse()
385        .expect("password should parse");
386
387        assert_eq!(parsed.password, password);
388    }
389
390    #[test]
391    fn registration_password_preserves_every_accepted_character() {
392        let password = " pass phrase ".to_owned();
393        let parsed = RegisterFormData {
394            email: Some("person@example.com".to_owned()),
395            full_name: None,
396            password: password.clone(),
397        }
398        .parse()
399        .expect("password should parse");
400
401        assert_eq!(parsed.password, password);
402    }
403
404    #[test]
405    fn rejects_display_addresses_in_login_and_registration() {
406        let login = LoginFormData {
407            identifier: "Person <person@example.com>".to_owned(),
408            password: "correct password".to_owned(),
409        }
410        .parse()
411        .expect_err("login requires an address without a display name");
412        assert_eq!(login.code(), ParseErrorCode::InvalidFormat);
413        assert_eq!(login.field(), Some("identifier"));
414
415        let registration = RegisterFormData {
416            email: Some("Person <person@example.com>".to_owned()),
417            full_name: None,
418            password: "correct password".to_owned(),
419        }
420        .parse()
421        .expect_err("registration requires an address without a display name");
422        assert_eq!(registration.code(), ParseErrorCode::InvalidFormat);
423        assert_eq!(registration.field(), Some("email"));
424    }
425
426    #[test]
427    fn rejects_whitespace_only_and_oversized_passwords() {
428        let whitespace = LoginFormData {
429            identifier: "person@example.com".to_owned(),
430            password: " \t\n ".to_owned(),
431        }
432        .parse()
433        .expect_err("whitespace-only passwords must fail");
434        assert_eq!(whitespace.code(), ParseErrorCode::Required);
435
436        let oversized = LoginFormData {
437            identifier: "person@example.com".to_owned(),
438            password: "x".repeat(MAX_PASSWORD_CHARS + 1),
439        }
440        .parse()
441        .expect_err("oversized passwords must fail");
442        assert_eq!(oversized.code(), ParseErrorCode::TooLong);
443    }
444
445    #[test]
446    fn login_outcome_debug_never_exposes_two_factor_token() {
447        let outcome = LoginOutcome::failure_with_two_factor(
448            LoginErrorCode::TwoFactorInvalid,
449            None,
450            true,
451            Some("secret-challenge-token".to_owned()),
452        );
453
454        let debug = format!("{outcome:?}");
455        assert!(!debug.contains("secret-challenge-token"));
456        assert!(debug.contains("has_two_factor_token: true"));
457    }
458}