ch-auth 0.3.2

Authentication and session primitives with explicit security policies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
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;

/// Enumerates machine-readable login error codes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum LoginErrorCode {
    /// No error occurred for the outcome.
    #[default]
    None,
    /// Too many attempts were made in a short period.
    RateLimited,
    /// The submitted credentials did not match an account.
    CredentialsInvalid,
    /// The account is not permitted to authenticate.
    AccountDenied,
    /// The account requires a two-factor challenge before login succeeds.
    TwoFactorRequired,
    /// The provided two-factor code was invalid.
    TwoFactorInvalid,
    /// The two-factor challenge expired before completion.
    TwoFactorExpired,
    /// No active two-factor challenge was found for the session.
    TwoFactorMissing,
    /// Two-factor authentication is unavailable for the account.
    TwoFactorUnavailable,
    /// Two-factor authentication is disabled for the account.
    TwoFactorDisabled,
}

impl LoginErrorCode {
    /// Returns the stable default message for this failure or challenge.
    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;
// Passwords are intentionally not normalized. This generous bound limits
// password-hashing work without changing ordinary passphrases.
const MAX_PASSWORD_CHARS: usize = 1_024;
const MAX_REGISTRATION_NAME_CHARS: usize = 256;

#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
/// Raw credentials submitted to a login endpoint.
///
/// Its custom [`fmt::Debug`] implementation redacts the password.
pub struct LoginFormData {
    /// Account hash or email address used to identify the account.
    pub identifier: String,
    /// Plaintext password supplied by the caller.
    pub password: String,
}

impl LoginFormData {
    /// Validates and normalizes the submitted credentials.
    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)]
/// Raw fields submitted to a registration endpoint.
///
/// Its custom [`fmt::Debug`] implementation redacts the password.
pub struct RegisterFormData {
    /// Optional account email address.
    pub email: Option<String>,
    /// Optional human-readable account name.
    pub full_name: Option<String>,
    /// Plaintext password supplied by the caller.
    pub password: String,
}

impl RegisterFormData {
    /// Validates and normalizes the submitted registration fields.
    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)]
/// Serializable result of a login attempt.
pub struct LoginOutcome {
    /// Whether the current login step succeeded.
    pub success: bool,
    /// Optional translatable feedback for the caller.
    pub message: Option<AuthMessage>,
    /// Stable machine-readable outcome code.
    pub error_code: LoginErrorCode,
    /// Authorization reason when the account was denied.
    pub deny_reason: Option<AuthDenyReason>,
    /// Whether the associated CAPTCHA response was accepted.
    pub captcha_valid: bool,
    /// Whether the caller must complete a two-factor challenge.
    pub requires_two_factor: bool,
    /// Opaque token for a pending two-factor challenge.
    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 {
    /// Creates a completed successful login outcome.
    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,
        }
    }

    /// Creates a successful first-step outcome that requires two-factor authentication.
    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,
        }
    }

    /// Creates a failed login outcome without a pending two-factor challenge.
    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,
        }
    }

    /// Creates a failed login outcome while preserving an optional challenge token.
    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,
        }
    }

    /// Creates an outcome for a valid account that authorization policy denied.
    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,
        }
    }

    /// Creates an outcome for an invalid two-factor code.
    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)]
/// Serializable result of a registration attempt.
pub struct RegisterOutcome {
    /// Whether account creation succeeded.
    pub success: bool,
    /// Optional translatable feedback for the caller.
    pub message: Option<AuthMessage>,
    /// Public account hash assigned to the created account.
    pub account_hash: Option<String>,
}

#[derive(Clone, PartialEq, Eq)]
/// Validated and normalized login credentials.
///
/// Its custom [`fmt::Debug`] implementation redacts the password.
pub struct ParsedLoginFormData {
    /// Normalized account identifier.
    pub identifier: LoginIdentifier,
    /// Non-empty plaintext password supplied by the caller.
    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)]
/// Normalized identifier accepted by the login workflow.
pub enum LoginIdentifier {
    /// Valid public account hash.
    Hash(AccountHash),
    /// Normalized email address.
    Email(String),
}

impl LoginIdentifier {
    /// Parses a raw account hash or email address.
    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))
    }

    /// Returns the normalized identifier as text.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Hash(hash) => hash.as_str(),
            Self::Email(email) => email.as_str(),
        }
    }
}

#[derive(Clone, PartialEq, Eq)]
/// Validated and normalized registration fields.
///
/// Its custom [`fmt::Debug`] implementation redacts the password.
pub struct ParsedRegisterFormData {
    /// Normalized optional email address.
    pub email: Option<String>,
    /// Trimmed optional human-readable account name.
    pub full_name: Option<String>,
    /// Non-empty plaintext password supplied by the caller.
    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()
    }
}

/// Validates a password without normalizing or otherwise mutating it.
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"));
    }
}