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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
14#[serde(rename_all = "snake_case")]
15pub enum LoginErrorCode {
16 #[default]
18 None,
19 RateLimited,
21 CredentialsInvalid,
23 AccountDenied,
25 TwoFactorRequired,
27 TwoFactorInvalid,
29 TwoFactorExpired,
31 TwoFactorMissing,
33 TwoFactorUnavailable,
35 TwoFactorDisabled,
37}
38
39impl LoginErrorCode {
40 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;
59const MAX_PASSWORD_CHARS: usize = 1_024;
62const MAX_REGISTRATION_NAME_CHARS: usize = 256;
63
64#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
65pub struct LoginFormData {
69 pub identifier: String,
71 pub password: String,
73}
74
75impl LoginFormData {
76 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)]
98pub struct RegisterFormData {
102 pub email: Option<String>,
104 pub full_name: Option<String>,
106 pub password: String,
108}
109
110impl RegisterFormData {
111 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)]
146pub struct LoginOutcome {
148 pub success: bool,
150 pub message: Option<AuthMessage>,
152 pub error_code: LoginErrorCode,
154 pub deny_reason: Option<AuthDenyReason>,
156 pub captcha_valid: bool,
158 pub requires_two_factor: bool,
160 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 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 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 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 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 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 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)]
276pub struct RegisterOutcome {
278 pub success: bool,
280 pub message: Option<AuthMessage>,
282 pub account_hash: Option<String>,
284}
285
286#[derive(Clone, PartialEq, Eq)]
287pub struct ParsedLoginFormData {
291 pub identifier: LoginIdentifier,
293 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)]
308pub enum LoginIdentifier {
310 Hash(AccountHash),
312 Email(String),
314}
315
316impl LoginIdentifier {
317 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 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)]
339pub struct ParsedRegisterFormData {
343 pub email: Option<String>,
345 pub full_name: Option<String>,
347 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
362pub(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}