Skip to main content

ch_auth/auth/login/
api.rs

1use std::future::Future;
2
3use serde::{Serialize, de::DeserializeOwned};
4use time::OffsetDateTime;
5
6use crate::auth::login::forms::{LoginErrorCode, LoginOutcome};
7use crate::auth::two_factor::api::{TwoFactorServerError, verify_totp_step};
8use crate::auth::two_factor::{
9    TwoFactorChallenge, TwoFactorCode, TwoFactorLoginForm, TwoFactorLoginPayload,
10};
11use crate::messages::AuthMessage;
12use crate::ratelimit::SecurityState;
13use crate::status::{AuthDecision, AuthDenyReason, auth_deny_message};
14
15const TWO_FACTOR_SESSION_KEY: &str = "two_factor_challenge";
16
17/// Session access abstraction for shared login flows.
18pub trait LoginSession {
19    /// User type stored inside the session.
20    type User;
21    /// User id type stored in the session.
22    type Id;
23
24    /// Reads a typed value from the session store.
25    fn session_get<T: DeserializeOwned>(&self, key: &str) -> Option<T>;
26    /// Writes a typed value into the session store.
27    fn session_set<T: Serialize>(&mut self, key: &str, value: &T);
28    /// Removes a key from the session store.
29    fn session_remove(&mut self, key: &str);
30
31    /// Reads the pending two-factor login challenge.
32    fn pending_two_factor_challenge(&self) -> Option<TwoFactorChallenge> {
33        self.session_get(TWO_FACTOR_SESSION_KEY)
34    }
35
36    /// Stores a pending two-factor login challenge.
37    fn set_pending_two_factor_challenge(&mut self, challenge: &TwoFactorChallenge) {
38        self.session_set(TWO_FACTOR_SESSION_KEY, challenge);
39    }
40
41    /// Removes the pending two-factor login challenge.
42    fn clear_pending_two_factor_challenge(&mut self) {
43        self.session_remove(TWO_FACTOR_SESSION_KEY);
44    }
45    /// Opts the session into persistence after authentication starts.
46    fn session_opt_in(&mut self);
47    /// Rotates the session identifier across an authentication boundary.
48    fn renew_session(&mut self);
49
50    /// Persists the user id into the session for subsequent requests.
51    fn login_user(&mut self, id: Self::Id);
52    /// Marks whether the session should be persistent.
53    fn remember_user(&mut self, remember: bool);
54    /// Stores the authenticated user model in memory.
55    fn set_current_user(&mut self, user: Self::User);
56
57    /// Rotates and persists a fully authenticated session.
58    fn establish_authenticated_session(&mut self, id: Self::Id, user: Self::User, remember: bool) {
59        self.renew_session();
60        self.session_opt_in();
61        self.login_user(id);
62        self.remember_user(remember);
63        self.set_current_user(user);
64    }
65}
66
67/// Minimal account data required for shared login flows.
68pub trait LoginAccount {
69    /// Returns the unique identifier of the account.
70    fn id(&self) -> &str;
71    /// Returns the authentication decision for the account.
72    fn auth_decision(&self) -> AuthDecision;
73}
74
75/// Credentials wrapper used by shared login flows.
76pub trait LoginCredentials {
77    /// Account type associated with these credentials.
78    type Account: LoginAccount;
79
80    /// Returns the underlying account row.
81    fn account(&self) -> &Self::Account;
82    /// Returns the stored password hash.
83    fn password_hash(&self) -> &str;
84    /// Returns `true` when two-factor authentication is enabled.
85    fn two_factor_enabled(&self) -> bool;
86}
87
88/// Exposes the account hash used during registration.
89pub trait AccountHash {
90    /// Returns the public account hash.
91    fn account_hash(&self) -> &str;
92}
93
94/// Implements login traits for standard account and credential types.
95#[macro_export]
96macro_rules! impl_login_traits {
97    ($account:ty, $credentials:ty, $decision:expr) => {
98        impl $crate::auth::login::api::LoginAccount for $account {
99            fn id(&self) -> &str {
100                self.id.as_str()
101            }
102
103            fn auth_decision(&self) -> $crate::status::AuthDecision {
104                ($decision)(self)
105            }
106        }
107
108        impl $crate::auth::login::api::AccountHash for $account {
109            fn account_hash(&self) -> &str {
110                self.account_hash.as_str()
111            }
112        }
113
114        impl $crate::auth::login::api::LoginCredentials for $credentials {
115            type Account = $account;
116
117            fn account(&self) -> &Self::Account {
118                &self.account
119            }
120
121            fn password_hash(&self) -> &str {
122                self.password_hash.as_str()
123            }
124
125            fn two_factor_enabled(&self) -> bool {
126                self.twofa_enabled
127            }
128        }
129    };
130}
131
132impl<User, Type, Sess, Pool> LoginSession for axum_session_auth::AuthSession<User, Type, Sess, Pool>
133where
134    User: axum_session_auth::Authentication<User, Type, Pool> + Clone + Send,
135    Pool: Clone + Send + Sync + std::fmt::Debug + 'static,
136    Type: Eq
137        + Default
138        + Clone
139        + Send
140        + Sync
141        + std::hash::Hash
142        + Serialize
143        + DeserializeOwned
144        + 'static,
145    Sess: axum_session::DatabasePool + Clone + std::fmt::Debug + Sync + Send + 'static,
146{
147    type User = User;
148    type Id = Type;
149
150    fn session_get<T: DeserializeOwned>(&self, key: &str) -> Option<T> {
151        self.session.get::<T>(key)
152    }
153
154    fn session_set<T: Serialize>(&mut self, key: &str, value: &T) {
155        self.session.set(key, value);
156    }
157
158    fn session_remove(&mut self, key: &str) {
159        self.session.remove(key);
160    }
161
162    fn session_opt_in(&mut self) {
163        self.session.set_store(true);
164    }
165
166    fn renew_session(&mut self) {
167        self.session.renew();
168    }
169
170    fn login_user(&mut self, id: Self::Id) {
171        axum_session_auth::AuthSession::login_user(self, id);
172    }
173
174    fn remember_user(&mut self, remember: bool) {
175        axum_session_auth::AuthSession::remember_user(self, remember);
176    }
177
178    fn set_current_user(&mut self, user: Self::User) {
179        self.current_user = Some(user);
180    }
181}
182
183/// Session and CAPTCHA state used by shared login flows.
184pub struct LoginContext<'a, Auth> {
185    auth: &'a mut Auth,
186    captcha_valid: bool,
187}
188
189impl<'a, Auth: LoginSession<Id = String>> LoginContext<'a, Auth> {
190    /// Creates a login context after the application's CAPTCHA check.
191    pub fn new(auth: &'a mut Auth, captcha_valid: bool) -> Self {
192        Self {
193            auth,
194            captcha_valid,
195        }
196    }
197
198    fn success_outcome(&self) -> LoginOutcome {
199        LoginOutcome::success(
200            Some(AuthMessage::from_static("auth.login.feedback.success")),
201            self.captcha_valid,
202        )
203    }
204
205    fn account_denied_outcome(&self, reason: AuthDenyReason) -> LoginOutcome {
206        let message = auth_deny_message(&reason);
207        LoginOutcome::account_denied(reason, Some(message), self.captcha_valid)
208    }
209
210    fn outcome_for_error(&self, code: LoginErrorCode, token: Option<String>) -> LoginOutcome {
211        LoginOutcome::failure_with_two_factor(code, code.message(), self.captcha_valid, token)
212    }
213}
214
215/// Login could not be checked because an application service was unavailable.
216/// Callback errors and configured credentials are never retained.
217#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
218#[non_exhaustive]
219pub enum LoginError {
220    /// Stored credentials could not be loaded.
221    #[error("login credentials are unavailable")]
222    CredentialsUnavailable,
223    /// The application's password verifier could not complete.
224    #[error("password verification is unavailable")]
225    VerificationUnavailable,
226}
227
228/// No-op hook for shared login flows.
229pub fn noop_login_hook<Auth, Account>(_: &mut Auth, _: Account) -> std::future::Ready<()> {
230    std::future::ready(())
231}
232
233/// No-op hook for shared login flows that only need the session.
234pub fn noop_session_hook<Auth>(_: &mut Auth) -> std::future::Ready<()> {
235    std::future::ready(())
236}
237
238/// Builds the uniform public outcome for a server-side login rate rejection.
239pub fn rate_limited_login_outcome(captcha_valid: bool) -> LoginOutcome {
240    LoginOutcome::failure(
241        LoginErrorCode::RateLimited,
242        LoginErrorCode::RateLimited.message(),
243        captcha_valid,
244    )
245}
246
247/// Completes the login session after credentials have been verified.
248pub async fn finalize_login<
249    'a,
250    Auth,
251    Account,
252    BuildUser,
253    OnTwoFactor,
254    OnTwoFactorFut,
255    OnSuccess,
256    OnSuccessFut,
257>(
258    ctx: &'a mut LoginContext<'a, Auth>,
259    account: Account,
260    two_factor_enabled: bool,
261    build_user: BuildUser,
262    on_two_factor: OnTwoFactor,
263    on_success: OnSuccess,
264) -> LoginOutcome
265where
266    Auth: LoginSession<Id = String>,
267    Account: LoginAccount,
268    BuildUser: Fn(&Account) -> Auth::User,
269    OnTwoFactor: FnOnce(&'a mut Auth, Account) -> OnTwoFactorFut,
270    OnTwoFactorFut: Future<Output = ()>,
271    OnSuccess: FnOnce(&'a mut Auth, Account) -> OnSuccessFut,
272    OnSuccessFut: Future<Output = ()>,
273{
274    if two_factor_enabled {
275        let challenge = TwoFactorChallenge::new(account.id().to_string());
276        let token = challenge.token().to_string();
277        ctx.auth.renew_session();
278        ctx.auth.session_opt_in();
279        ctx.auth.set_pending_two_factor_challenge(&challenge);
280
281        let outcome = LoginOutcome::success_with_two_factor(
282            Some(AuthMessage::from_static(
283                "auth.login.feedback.two_factor_required",
284            )),
285            ctx.captcha_valid,
286            Some(token),
287        );
288        on_two_factor(ctx.auth, account).await;
289        return outcome;
290    }
291
292    let account_id = account.id().to_string();
293    ctx.auth
294        .establish_authenticated_session(account_id, build_user(&account), true);
295
296    let outcome = ctx.success_outcome();
297    on_success(ctx.auth, account).await;
298    outcome
299}
300
301/// Collects the callbacks needed to authenticate a login request.
302pub struct LoginWithCredentialsCallbacks<
303    FetchCredentials,
304    VerifyPassword,
305    BuildUser,
306    OnTwoFactor,
307    OnSuccess,
308    OnFailure,
309> {
310    /// Loads stored credentials for the normalized login identifier.
311    pub fetch_credentials: FetchCredentials,
312    /// Verifies the submitted password against the stored password hash.
313    pub verify_password: VerifyPassword,
314    /// Valid hash used when the normalized identifier has no account.
315    ///
316    /// It must use the same algorithm and comparable cost as real hashes so
317    /// negative lookups cannot be distinguished by skipping password work.
318    pub dummy_password_hash: DummyPasswordHash,
319    /// Converts the authenticated account into the application's session user.
320    pub build_user: BuildUser,
321    /// Runs application-owned work when the account requires two-factor authentication.
322    pub on_two_factor: OnTwoFactor,
323    /// Runs application-owned work after a complete successful login.
324    pub on_success: OnSuccess,
325    /// Runs application-owned cleanup after invalid credentials.
326    pub on_failure: OnFailure,
327}
328
329/// Valid hash used to equalize password work for unknown accounts.
330///
331/// Its custom [`std::fmt::Debug`] implementation never exposes the hash.
332#[derive(Clone, PartialEq, Eq)]
333pub struct DummyPasswordHash(String);
334
335impl DummyPasswordHash {
336    /// Creates an application-specific dummy hash without changing it.
337    ///
338    /// # Errors
339    ///
340    /// Returns an error when the supplied hash is empty or whitespace-only.
341    pub fn new(hash: impl Into<String>) -> Result<Self, DummyPasswordHashError> {
342        let hash = hash.into();
343        if hash.trim().is_empty() {
344            return Err(DummyPasswordHashError);
345        }
346        Ok(Self(hash))
347    }
348
349    /// Returns the hash passed to the application-owned password verifier.
350    #[must_use]
351    pub fn as_str(&self) -> &str {
352        self.0.as_str()
353    }
354}
355
356impl Default for DummyPasswordHash {
357    /// Builds a valid Argon2id hash with parameters matching the default
358    /// Argon2 verifier. Applications using another algorithm construct their
359    /// own value with [`Self::new`].
360    fn default() -> Self {
361        Self(
362            "$argon2id$v=19$m=19456,t=2,p=1$arjXQ/LUUIuovdLClWFtIw$J9sIrzrUPQ+mDJ2cgQdR90xL0PGfOwekiPGXJadZ/fE"
363                .to_owned(),
364        )
365    }
366}
367
368impl std::fmt::Debug for DummyPasswordHash {
369    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
370        formatter
371            .debug_tuple("DummyPasswordHash")
372            .field(&"[REDACTED]")
373            .finish()
374    }
375}
376
377/// Error returned when an unknown-account dummy hash is empty.
378#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
379#[error("dummy password hash must not be empty")]
380pub struct DummyPasswordHashError;
381
382/// Authenticates a login request using stored credentials.
383pub async fn login_with_credentials<
384    'a,
385    'b,
386    Auth,
387    Credentials,
388    FetchCredentials,
389    FetchFuture,
390    FetchError,
391    VerifyPassword,
392    VerifyError,
393    BuildUser,
394    OnTwoFactor,
395    OnTwoFactorFut,
396    OnSuccess,
397    OnSuccessFut,
398    OnFailure,
399    OnFailureFut,
400>(
401    ctx: &'a mut LoginContext<'a, Auth>,
402    lookup: &'b str,
403    password: &'b str,
404    callbacks: LoginWithCredentialsCallbacks<
405        FetchCredentials,
406        VerifyPassword,
407        BuildUser,
408        OnTwoFactor,
409        OnSuccess,
410        OnFailure,
411    >,
412) -> Result<LoginOutcome, LoginError>
413where
414    Auth: LoginSession<Id = String>,
415    Credentials: LoginCredentials,
416    Credentials::Account: LoginAccount + Clone,
417    FetchCredentials: FnOnce(&'b str) -> FetchFuture,
418    FetchFuture: Future<Output = Result<Option<Credentials>, FetchError>>,
419    VerifyPassword: AsyncFnOnce(&str, &str) -> Result<bool, VerifyError>,
420    BuildUser: Fn(&Credentials::Account) -> Auth::User,
421    OnTwoFactor: FnOnce(&'a mut Auth, Credentials::Account) -> OnTwoFactorFut,
422    OnTwoFactorFut: Future<Output = ()>,
423    OnSuccess: FnOnce(&'a mut Auth, Credentials::Account) -> OnSuccessFut,
424    OnSuccessFut: Future<Output = ()>,
425    OnFailure: FnOnce(&'a mut Auth) -> OnFailureFut,
426    OnFailureFut: Future<Output = ()>,
427{
428    let LoginWithCredentialsCallbacks {
429        fetch_credentials,
430        verify_password,
431        dummy_password_hash,
432        build_user,
433        on_two_factor,
434        on_success,
435        on_failure,
436    } = callbacks;
437
438    ctx.auth.clear_pending_two_factor_challenge();
439
440    let credentials = fetch_credentials(lookup)
441        .await
442        .map_err(|_error| LoginError::CredentialsUnavailable)?;
443
444    let password_matches = match credentials.as_ref() {
445        Some(credentials) => verify_password(password, credentials.password_hash()).await,
446        None => verify_password(password, dummy_password_hash.as_str()).await,
447    }
448    .map_err(|_error| LoginError::VerificationUnavailable)?;
449
450    if password_matches && let Some(credentials) = credentials {
451        let account = credentials.account();
452        let outcome = match account.auth_decision() {
453            AuthDecision::Allow => {
454                let account = account.clone();
455                Ok(finalize_login(
456                    ctx,
457                    account,
458                    credentials.two_factor_enabled(),
459                    build_user,
460                    on_two_factor,
461                    on_success,
462                )
463                .await)
464            }
465            AuthDecision::Deny(reason) => {
466                let outcome = ctx.account_denied_outcome(reason);
467                on_failure(ctx.auth).await;
468                Ok(outcome)
469            }
470        };
471        return outcome;
472    }
473
474    let outcome = ctx.outcome_for_error(LoginErrorCode::CredentialsInvalid, None);
475    on_failure(ctx.auth).await;
476    Ok(outcome)
477}
478
479/// Collects the callbacks needed to complete two-factor logins.
480pub struct TwoFactorLoginCallbacks<
481    LoadAccount,
482    LoadTwoFactorState,
483    ConsumeBackup,
484    ConsumeTotp,
485    BuildUser,
486    OnSuccess,
487    OnCleanup,
488> {
489    /// Loads the account referenced by the pending challenge.
490    pub load_account: LoadAccount,
491    /// Loads whether two-factor authentication is enabled and its TOTP secret.
492    pub load_two_factor_state: LoadTwoFactorState,
493    /// Atomically consumes a matching backup code.
494    pub consume_backup_code: ConsumeBackup,
495    /// Atomically records a verified timestep for the still-current TOTP secret.
496    pub consume_totp_step: ConsumeTotp,
497    /// Converts the authenticated account into the application's session user.
498    pub build_user: BuildUser,
499    /// Runs application-owned work after successful verification.
500    pub on_success: OnSuccess,
501    /// Removes or invalidates application-owned challenge state.
502    pub on_cleanup: OnCleanup,
503}
504
505/// Distinguishes invalid client input from unavailable verification backends.
506/// Submitted tokens, codes, secrets and callback errors are never retained.
507#[derive(Debug, thiserror::Error)]
508pub enum TwoFactorLoginError {
509    /// The canonical input parser rejected the submitted form.
510    #[error("auth.two_factor.invalid_input")]
511    InvalidInput(#[source] ch_parsing::error::ParseError),
512    /// The account's stored second-factor state could not be loaded.
513    #[error("auth.two_factor.state_unavailable")]
514    StateUnavailable,
515    /// Verification could not run because its server-side prerequisites failed.
516    #[error("auth.two_factor.verification_unavailable")]
517    Totp(#[source] TwoFactorServerError),
518    /// Atomic recovery-code consumption could not be completed.
519    #[error("auth.two_factor.backup_unavailable")]
520    BackupUnavailable,
521    /// The verified TOTP step could not be consumed durably.
522    #[error("auth.two_factor.consumption_unavailable")]
523    ConsumptionUnavailable,
524}
525
526/// Completes a two-factor login challenge using the provided payload.
527pub async fn complete_two_factor_login<
528    'a,
529    Auth,
530    Account,
531    LoadAccount,
532    LoadAccountFuture,
533    LoadAccountError,
534    LoadTwoFactorState,
535    LoadTwoFactorFuture,
536    LoadTwoFactorError,
537    ConsumeBackup,
538    ConsumeTotp,
539    ConsumeBackupFuture,
540    ConsumeBackupError,
541    ConsumeTotpError,
542    BuildUser,
543    OnSuccess,
544    OnSuccessFut,
545    OnCleanup,
546    OnCleanupFut,
547>(
548    ctx: &'a mut LoginContext<'a, Auth>,
549    form: TwoFactorLoginForm,
550    security: &SecurityState,
551    callbacks: TwoFactorLoginCallbacks<
552        LoadAccount,
553        LoadTwoFactorState,
554        ConsumeBackup,
555        ConsumeTotp,
556        BuildUser,
557        OnSuccess,
558        OnCleanup,
559    >,
560) -> Result<LoginOutcome, TwoFactorLoginError>
561where
562    Auth: LoginSession<Id = String>,
563    Account: LoginAccount,
564    LoadAccount: FnOnce(&str) -> LoadAccountFuture,
565    LoadAccountFuture: Future<Output = Result<Account, LoadAccountError>>,
566    LoadTwoFactorState: FnOnce(&Account) -> LoadTwoFactorFuture,
567    LoadTwoFactorFuture: Future<Output = Result<(bool, Option<String>), LoadTwoFactorError>>,
568    ConsumeBackup: FnOnce(&Account, &str) -> ConsumeBackupFuture,
569    ConsumeBackupFuture: Future<Output = Result<bool, ConsumeBackupError>>,
570    ConsumeTotp: AsyncFnOnce(&Account, &str, u64) -> Result<bool, ConsumeTotpError>,
571    BuildUser: Fn(&Account) -> Auth::User,
572    OnSuccess: FnOnce(&'a mut Auth, Account) -> OnSuccessFut,
573    OnSuccessFut: Future<Output = ()>,
574    OnCleanup: FnOnce(&'a mut Auth) -> OnCleanupFut,
575    OnCleanupFut: Future<Output = ()>,
576{
577    let TwoFactorLoginCallbacks {
578        load_account,
579        load_two_factor_state,
580        consume_backup_code,
581        consume_totp_step,
582        build_user,
583        on_success,
584        on_cleanup,
585    } = callbacks;
586
587    let parsed = TwoFactorLoginPayload::parse(form).map_err(TwoFactorLoginError::InvalidInput)?;
588    let token = parsed.token().as_str();
589    let code = parsed.code();
590
591    let now = OffsetDateTime::now_utc();
592    let Some(challenge) = ctx.auth.pending_two_factor_challenge() else {
593        return Ok(ctx.outcome_for_error(LoginErrorCode::TwoFactorMissing, None));
594    };
595
596    if challenge.is_expired(now) {
597        ctx.auth.clear_pending_two_factor_challenge();
598
599        let outcome = ctx.outcome_for_error(LoginErrorCode::TwoFactorExpired, None);
600        on_cleanup(ctx.auth).await;
601        return Ok(outcome);
602    }
603
604    if challenge.token() != token {
605        ctx.auth.clear_pending_two_factor_challenge();
606
607        let outcome = ctx.outcome_for_error(LoginErrorCode::TwoFactorMissing, None);
608        on_cleanup(ctx.auth).await;
609        return Ok(outcome);
610    }
611
612    if security
613        .check_two_factor_account(challenge.account_id())
614        .is_err()
615    {
616        return Ok(ctx.outcome_for_error(
617            LoginErrorCode::RateLimited,
618            Some(challenge.token().to_owned()),
619        ));
620    }
621
622    let account = match load_account(challenge.account_id()).await {
623        Ok(account) => account,
624        Err(_error) => {
625            ctx.auth.clear_pending_two_factor_challenge();
626
627            let outcome = ctx.outcome_for_error(LoginErrorCode::TwoFactorMissing, None);
628            on_cleanup(ctx.auth).await;
629            return Ok(outcome);
630        }
631    };
632
633    if let AuthDecision::Deny(reason) = account.auth_decision() {
634        ctx.auth.clear_pending_two_factor_challenge();
635
636        let outcome = ctx.account_denied_outcome(reason);
637        on_cleanup(ctx.auth).await;
638        return Ok(outcome);
639    }
640
641    let (two_factor_enabled, two_factor_secret) = load_two_factor_state(&account)
642        .await
643        .map_err(|_error| TwoFactorLoginError::StateUnavailable)?;
644
645    if !two_factor_enabled {
646        ctx.auth.clear_pending_two_factor_challenge();
647
648        let outcome = ctx.outcome_for_error(LoginErrorCode::TwoFactorDisabled, None);
649        on_cleanup(ctx.auth).await;
650        return Ok(outcome);
651    }
652
653    let verified = match code {
654        TwoFactorCode::Totp(code) => {
655            let Some(secret) = two_factor_secret.as_deref() else {
656                ctx.auth.clear_pending_two_factor_challenge();
657                let outcome = ctx.outcome_for_error(LoginErrorCode::TwoFactorUnavailable, None);
658                on_cleanup(ctx.auth).await;
659                return Ok(outcome);
660            };
661            let value = code
662                .as_str()
663                .parse::<u32>()
664                .expect("validated six-digit TOTP");
665            match verify_totp_step(secret, value).map_err(TwoFactorLoginError::Totp)? {
666                Some(step) => consume_totp_step(&account, secret, step)
667                    .await
668                    .map_err(|_error| TwoFactorLoginError::ConsumptionUnavailable)?,
669                None => false,
670            }
671        }
672        TwoFactorCode::Backup(code) => consume_backup_code(&account, code.as_str())
673            .await
674            .map_err(|_error| TwoFactorLoginError::BackupUnavailable)?,
675    };
676    if !verified {
677        return Ok(ctx.outcome_for_error(
678            LoginErrorCode::TwoFactorInvalid,
679            Some(challenge.token().to_owned()),
680        ));
681    }
682
683    let account_id = account.id().to_string();
684    ctx.auth
685        .establish_authenticated_session(account_id, build_user(&account), true);
686    ctx.auth.clear_pending_two_factor_challenge();
687
688    let outcome = ctx.success_outcome();
689    on_success(ctx.auth, account).await;
690    Ok(outcome)
691}
692
693/// Registers a new account and persists the authenticated session.
694pub async fn register_account_with_database<
695    Auth,
696    Account,
697    InsertAccount,
698    InsertFuture,
699    InsertError,
700    BuildUser,
701>(
702    auth: &mut Auth,
703    form: crate::auth::login::forms::RegisterFormData,
704    insert_account: InsertAccount,
705    build_user: BuildUser,
706) -> Result<crate::auth::login::forms::RegisterOutcome, ch_parsing::error::ParseError>
707where
708    Auth: LoginSession<Id = String>,
709    Account: LoginAccount + AccountHash,
710    InsertAccount: FnOnce(Option<String>, Option<String>, &str) -> InsertFuture,
711    InsertFuture: Future<Output = Result<Account, InsertError>>,
712    BuildUser: Fn(&Account) -> Auth::User,
713{
714    let parsed = form.parse()?;
715
716    Ok(register_account_with_values(
717        auth,
718        parsed.email,
719        parsed.full_name,
720        parsed.password,
721        insert_account,
722        build_user,
723    )
724    .await)
725}
726
727/// Registers a new account and persists the authenticated session from validated inputs.
728pub async fn register_account_with_values<
729    Auth,
730    Account,
731    InsertAccount,
732    InsertFuture,
733    InsertError,
734    BuildUser,
735>(
736    auth: &mut Auth,
737    email: Option<String>,
738    full_name: Option<String>,
739    password: String,
740    insert_account: InsertAccount,
741    build_user: BuildUser,
742) -> crate::auth::login::forms::RegisterOutcome
743where
744    Auth: LoginSession<Id = String>,
745    Account: LoginAccount + AccountHash,
746    InsertAccount: FnOnce(Option<String>, Option<String>, &str) -> InsertFuture,
747    InsertFuture: Future<Output = Result<Account, InsertError>>,
748    BuildUser: Fn(&Account) -> Auth::User,
749{
750    let success_message = AuthMessage::from_static("auth.register.feedback.success");
751    let failure_message = AuthMessage::from_static("auth.register.feedback.failed");
752
753    let account = match insert_account(email, full_name, password.as_str()).await {
754        Ok(account) => account,
755        Err(_error) => {
756            return crate::auth::login::forms::RegisterOutcome {
757                success: false,
758                message: Some(failure_message),
759                account_hash: None,
760            };
761        }
762    };
763
764    auth.establish_authenticated_session(account.id().to_string(), build_user(&account), true);
765
766    crate::auth::login::forms::RegisterOutcome {
767        success: true,
768        message: Some(success_message),
769        account_hash: Some(account.account_hash().to_string()),
770    }
771}
772
773#[cfg(test)]
774mod tests {
775    use super::LoginError;
776    use super::{
777        AccountHash, DummyPasswordHash, LoginAccount, LoginContext, LoginCredentials, LoginOutcome,
778        LoginSession, LoginWithCredentialsCallbacks, TwoFactorLoginCallbacks, TwoFactorLoginError,
779        complete_two_factor_login, login_with_credentials,
780    };
781    use crate::auth::login::forms::LoginErrorCode;
782    use crate::auth::two_factor::api::TwoFactorServerError;
783    use crate::auth::two_factor::{TwoFactorChallenge, TwoFactorLoginForm};
784    use crate::ratelimit::SecurityState;
785    use crate::status::{AuthDecision, AuthDenyReason};
786    use anyhow::Error as AuthError;
787    use argon2::Argon2;
788    use argon2::password_hash::{PasswordHash, PasswordVerifier};
789    use serde::{Deserialize, Serialize};
790    use std::cell::Cell;
791    use std::collections::HashMap;
792
793    #[test]
794    fn default_dummy_password_hash_is_valid_argon2id() {
795        let dummy_hash = DummyPasswordHash::default();
796        let hash = PasswordHash::new(dummy_hash.as_str())
797            .expect("the published dummy hash must stay valid");
798        assert!(
799            Argon2::default()
800                .verify_password(b"deliberately-wrong", &hash)
801                .is_err()
802        );
803    }
804
805    #[test]
806    fn custom_dummy_password_hash_is_non_empty_and_redacted() {
807        assert!(DummyPasswordHash::new(" \t ").is_err());
808
809        let dummy_hash = DummyPasswordHash::new("algorithm-specific-hash")
810            .expect("non-empty custom hashes should be accepted");
811        assert_eq!(dummy_hash.as_str(), "algorithm-specific-hash");
812        assert!(!format!("{dummy_hash:?}").contains("algorithm-specific-hash"));
813    }
814
815    #[derive(Clone, Debug, PartialEq, Eq)]
816    struct TestAccount {
817        id: String,
818        decision: AuthDecision,
819        account_hash: String,
820    }
821
822    impl LoginAccount for TestAccount {
823        fn id(&self) -> &str {
824            self.id.as_str()
825        }
826
827        fn auth_decision(&self) -> AuthDecision {
828            self.decision.clone()
829        }
830    }
831
832    impl AccountHash for TestAccount {
833        fn account_hash(&self) -> &str {
834            self.account_hash.as_str()
835        }
836    }
837
838    #[derive(Clone, Debug)]
839    struct TestCredentials {
840        account: TestAccount,
841        password_hash: String,
842        two_factor: bool,
843    }
844
845    impl LoginCredentials for TestCredentials {
846        type Account = TestAccount;
847
848        fn account(&self) -> &Self::Account {
849            &self.account
850        }
851
852        fn password_hash(&self) -> &str {
853            self.password_hash.as_str()
854        }
855
856        fn two_factor_enabled(&self) -> bool {
857            self.two_factor
858        }
859    }
860
861    /// Test account status used for macro coverage.
862    #[derive(Clone, Debug, PartialEq, Eq)]
863    enum MacroStatus {
864        Active,
865        Blocked,
866    }
867
868    /// Test account model used for macro coverage.
869    #[derive(Clone, Debug, PartialEq, Eq)]
870    struct MacroAccount {
871        id: String,
872        status: MacroStatus,
873        account_hash: String,
874    }
875
876    /// Test credentials wrapper used for macro coverage.
877    #[derive(Clone, Debug)]
878    struct MacroCredentials {
879        account: MacroAccount,
880        password_hash: String,
881        twofa_enabled: bool,
882    }
883
884    impl_login_traits!(MacroAccount, MacroCredentials, |account: &MacroAccount| {
885        match account.status {
886            MacroStatus::Active => AuthDecision::allow(),
887            MacroStatus::Blocked => AuthDecision::deny(AuthDenyReason::blocked()),
888        }
889    });
890
891    #[derive(Default)]
892    struct TestSessionStore {
893        entries: HashMap<String, serde_json::Value>,
894    }
895
896    impl TestSessionStore {
897        fn get<T: for<'de> Deserialize<'de>>(&self, key: &str) -> Option<T> {
898            let value = self.entries.get(key)?;
899            serde_json::from_value(value.clone()).ok()
900        }
901
902        fn set<T: Serialize>(&mut self, key: &str, value: &T) {
903            if let Ok(serialized) = serde_json::to_value(value) {
904                self.entries.insert(key.to_string(), serialized);
905            }
906        }
907
908        fn remove(&mut self, key: &str) {
909            self.entries.remove(key);
910        }
911    }
912
913    #[derive(Default)]
914    struct TestAuthSession {
915        session: TestSessionStore,
916        store: bool,
917        logged_in: Option<String>,
918        remember: bool,
919        renewals: usize,
920        user: Option<TestAccount>,
921    }
922
923    impl LoginSession for TestAuthSession {
924        type User = TestAccount;
925        type Id = String;
926
927        fn session_get<T: for<'de> Deserialize<'de>>(&self, key: &str) -> Option<T> {
928            self.session.get(key)
929        }
930
931        fn session_set<T: Serialize>(&mut self, key: &str, value: &T) {
932            self.session.set(key, value);
933        }
934
935        fn session_remove(&mut self, key: &str) {
936            self.session.remove(key);
937        }
938
939        fn session_opt_in(&mut self) {
940            self.store = true;
941        }
942
943        fn renew_session(&mut self) {
944            self.renewals += 1;
945        }
946
947        fn login_user(&mut self, id: Self::Id) {
948            self.logged_in = Some(id);
949        }
950
951        fn remember_user(&mut self, remember: bool) {
952            self.remember = remember;
953        }
954
955        fn set_current_user(&mut self, user: Self::User) {
956            self.user = Some(user);
957        }
958    }
959
960    /// Executes a login flow with fixed credentials and standard hooks.
961    async fn login_with_test_credentials<'a>(
962        ctx: &'a mut LoginContext<'a, TestAuthSession>,
963        credentials: TestCredentials,
964    ) -> Result<LoginOutcome, LoginError> {
965        login_with_credentials(
966            ctx,
967            "account-1",
968            "password",
969            LoginWithCredentialsCallbacks {
970                fetch_credentials: move |_lookup| {
971                    std::future::ready(Ok::<Option<TestCredentials>, std::convert::Infallible>(
972                        Some(credentials),
973                    ))
974                },
975                verify_password: async |_password: &str, _hash: &str| {
976                    Ok::<_, std::convert::Infallible>(true)
977                },
978                dummy_password_hash: DummyPasswordHash::default(),
979                build_user: |account: &TestAccount| account.clone(),
980                on_two_factor: |_, _| std::future::ready(()),
981                on_success: |_, _| std::future::ready(()),
982                on_failure: |_| std::future::ready(()),
983            },
984        )
985        .await
986    }
987
988    #[tokio::test]
989    async fn login_with_credentials_success() {
990        let mut auth = TestAuthSession::default();
991        let mut ctx = LoginContext::new(&mut auth, true);
992
993        let credentials = TestCredentials {
994            account: TestAccount {
995                id: "account-1".to_string(),
996                decision: AuthDecision::allow(),
997                account_hash: "hash".to_string(),
998            },
999            password_hash: "hashed".to_string(),
1000            two_factor: false,
1001        };
1002
1003        let outcome = login_with_test_credentials(&mut ctx, credentials)
1004            .await
1005            .expect("login should succeed");
1006
1007        assert!(outcome.success);
1008        assert_eq!(outcome.error_code, LoginErrorCode::None);
1009        assert!(auth.logged_in.is_some());
1010        assert!(auth.store);
1011        assert!(auth.remember);
1012        assert_eq!(auth.renewals, 1);
1013    }
1014
1015    #[tokio::test]
1016    async fn unknown_account_runs_the_injected_password_verifier() {
1017        let mut auth = TestAuthSession::default();
1018        let mut ctx = LoginContext::new(&mut auth, true);
1019        let verifier_called = Cell::new(false);
1020        let dummy_password_hash = DummyPasswordHash::default();
1021        let expected_dummy_hash = dummy_password_hash.as_str().to_owned();
1022
1023        let outcome = login_with_credentials(
1024            &mut ctx,
1025            "missing@example.test",
1026            "submitted-password",
1027            LoginWithCredentialsCallbacks {
1028                fetch_credentials: |_lookup| {
1029                    std::future::ready(Ok::<Option<TestCredentials>, std::convert::Infallible>(
1030                        None,
1031                    ))
1032                },
1033                verify_password: async |password: &str, hash: &str| {
1034                    verifier_called.set(true);
1035                    assert_eq!(password, "submitted-password");
1036                    assert_eq!(hash, expected_dummy_hash);
1037                    Ok::<_, std::convert::Infallible>(true)
1038                },
1039                dummy_password_hash,
1040                build_user: |account: &TestAccount| account.clone(),
1041                on_two_factor: |_, _| std::future::ready(()),
1042                on_success: |_, _| std::future::ready(()),
1043                on_failure: |_| std::future::ready(()),
1044            },
1045        )
1046        .await
1047        .expect("unknown accounts should return a public login outcome");
1048
1049        assert!(verifier_called.get());
1050        assert!(!outcome.success);
1051        assert_eq!(outcome.error_code, LoginErrorCode::CredentialsInvalid);
1052        assert!(auth.logged_in.is_none());
1053    }
1054
1055    #[tokio::test]
1056    async fn login_with_credentials_two_factor() {
1057        let mut auth = TestAuthSession::default();
1058        let mut ctx = LoginContext::new(&mut auth, true);
1059
1060        let credentials = TestCredentials {
1061            account: TestAccount {
1062                id: "account-1".to_string(),
1063                decision: AuthDecision::allow(),
1064                account_hash: "hash".to_string(),
1065            },
1066            password_hash: "hashed".to_string(),
1067            two_factor: true,
1068        };
1069
1070        let outcome = login_with_test_credentials(&mut ctx, credentials)
1071            .await
1072            .expect("login should succeed");
1073
1074        assert!(outcome.success);
1075        assert!(outcome.requires_two_factor);
1076        assert!(auth.store);
1077        assert_eq!(auth.renewals, 1);
1078        assert!(auth.logged_in.is_none());
1079        let stored = auth.pending_two_factor_challenge();
1080        assert!(stored.is_some());
1081    }
1082
1083    #[tokio::test]
1084    async fn two_factor_backup_code_success() {
1085        let mut auth = TestAuthSession::default();
1086        let challenge = TwoFactorChallenge::new("account-1".to_string());
1087        auth.set_pending_two_factor_challenge(&challenge);
1088        let mut ctx = LoginContext::new(&mut auth, true);
1089
1090        let form = TwoFactorLoginForm::new(challenge.token().to_string(), "ABCDEFGH".to_string());
1091
1092        let outcome = complete_two_factor_login(
1093            &mut ctx,
1094            form,
1095            &SecurityState::new(100.try_into().unwrap()),
1096            TwoFactorLoginCallbacks {
1097                load_account: |_id: &str| {
1098                    std::future::ready(Ok::<TestAccount, std::convert::Infallible>(TestAccount {
1099                        id: "account-1".to_string(),
1100                        decision: AuthDecision::allow(),
1101                        account_hash: "hash".to_string(),
1102                    }))
1103                },
1104                load_two_factor_state: |_account: &TestAccount| {
1105                    std::future::ready(Ok::<(bool, Option<String>), std::convert::Infallible>((
1106                        true, None,
1107                    )))
1108                },
1109                consume_backup_code: |_account: &TestAccount, _code: &str| {
1110                    std::future::ready(Ok::<bool, std::convert::Infallible>(true))
1111                },
1112                consume_totp_step: async |_: &TestAccount, _: &str, _: u64| {
1113                    Ok::<_, std::convert::Infallible>(true)
1114                },
1115                build_user: |account: &TestAccount| account.clone(),
1116                on_success: |_, _| std::future::ready(()),
1117                on_cleanup: |_| std::future::ready(()),
1118            },
1119        )
1120        .await
1121        .expect("two factor should succeed");
1122
1123        assert!(outcome.success);
1124        assert_eq!(outcome.error_code, LoginErrorCode::None);
1125        assert!(auth.store);
1126        assert_eq!(auth.renewals, 1);
1127        assert!(auth.pending_two_factor_challenge().is_none());
1128    }
1129
1130    #[tokio::test]
1131    async fn two_factor_backup_code_invalid() {
1132        let mut auth = TestAuthSession::default();
1133        let challenge = TwoFactorChallenge::new("account-1".to_string());
1134        auth.set_pending_two_factor_challenge(&challenge);
1135        let mut ctx = LoginContext::new(&mut auth, true);
1136
1137        let form = TwoFactorLoginForm::new(challenge.token().to_string(), "ABCDEFGH".to_string());
1138
1139        let outcome = complete_two_factor_login(
1140            &mut ctx,
1141            form,
1142            &SecurityState::new(100.try_into().unwrap()),
1143            TwoFactorLoginCallbacks {
1144                load_account: |_id: &str| {
1145                    std::future::ready(Ok::<TestAccount, std::convert::Infallible>(TestAccount {
1146                        id: "account-1".to_string(),
1147                        decision: AuthDecision::allow(),
1148                        account_hash: "hash".to_string(),
1149                    }))
1150                },
1151                load_two_factor_state: |_account: &TestAccount| {
1152                    std::future::ready(Ok::<(bool, Option<String>), std::convert::Infallible>((
1153                        true, None,
1154                    )))
1155                },
1156                consume_backup_code: |_account: &TestAccount, _code: &str| {
1157                    std::future::ready(Ok::<bool, std::convert::Infallible>(false))
1158                },
1159                consume_totp_step: async |_: &TestAccount, _: &str, _: u64| {
1160                    Ok::<_, std::convert::Infallible>(true)
1161                },
1162                build_user: |account: &TestAccount| account.clone(),
1163                on_success: |_, _| std::future::ready(()),
1164                on_cleanup: |_| std::future::ready(()),
1165            },
1166        )
1167        .await
1168        .expect("two factor should return outcome");
1169
1170        assert!(!outcome.success);
1171        assert_eq!(outcome.error_code, LoginErrorCode::TwoFactorInvalid);
1172        assert!(auth.pending_two_factor_challenge().is_some());
1173    }
1174
1175    #[tokio::test]
1176    async fn two_factor_malformed_input_is_typed_before_callbacks() {
1177        fn assert_error_contract<E: std::error::Error + Send + Sync + 'static>() {}
1178        assert_error_contract::<TwoFactorLoginError>();
1179
1180        let valid_token = "submitted-token-sensitive-marker";
1181        for (token, code) in [
1182            (valid_token.to_string(), "code-sensitive!marker".to_string()),
1183            (String::new(), "123456".to_string()),
1184            ("token-sensitive-marker".repeat(13), "123456".to_string()),
1185            (valid_token.to_string(), "code-sensitive-marker".repeat(4)),
1186        ] {
1187            let mut auth = TestAuthSession::default();
1188            let challenge = TwoFactorChallenge::new("account-1".to_string());
1189            auth.set_pending_two_factor_challenge(&challenge);
1190            let original_entries = auth.session.entries.clone();
1191            let mut ctx = LoginContext::new(&mut auth, true);
1192            let error = complete_two_factor_login(
1193                &mut ctx,
1194                TwoFactorLoginForm::new(token.clone(), code.clone()),
1195                &SecurityState::new(100.try_into().unwrap()),
1196                TwoFactorLoginCallbacks {
1197                    load_account:
1198                        |_id: &str| -> std::future::Ready<Result<TestAccount, AuthError>> {
1199                            panic!("malformed input must not load an account")
1200                        },
1201                    load_two_factor_state: |_account: &TestAccount| -> std::future::Ready<
1202                        Result<(bool, Option<String>), AuthError>,
1203                    > {
1204                        panic!("malformed input must not load verification state")
1205                    },
1206                    consume_backup_code:
1207                        |_account: &TestAccount,
1208                         _code: &str|
1209                         -> std::future::Ready<Result<bool, AuthError>> {
1210                            panic!("malformed input must not consume backup codes")
1211                        },
1212                    consume_totp_step: async |_: &TestAccount, _: &str, _: u64| {
1213                        Ok::<_, std::convert::Infallible>(true)
1214                    },
1215                    build_user: |_account: &TestAccount| -> TestAccount {
1216                        panic!("malformed input must not build a session user")
1217                    },
1218                    on_success: |_, _| -> std::future::Ready<()> {
1219                        panic!("malformed input must not invoke successful login work")
1220                    },
1221                    on_cleanup: |_| -> std::future::Ready<()> {
1222                        panic!("malformed input must preserve the pending challenge")
1223                    },
1224                },
1225            )
1226            .await
1227            .expect_err("malformed input must return a typed parser failure");
1228
1229            assert!(matches!(error, TwoFactorLoginError::InvalidInput(_)));
1230            for rendered in [error.to_string(), format!("{error:?}")] {
1231                assert!(!rendered.contains(&code));
1232                if !token.is_empty() {
1233                    assert!(!rendered.contains(&token));
1234                }
1235            }
1236            assert_eq!(auth.session.entries, original_entries);
1237            assert!(!auth.store && !auth.remember);
1238            assert_eq!(auth.renewals, 0);
1239            assert!(auth.logged_in.is_none() && auth.user.is_none());
1240        }
1241    }
1242
1243    #[tokio::test]
1244    async fn two_factor_state_backend_failure_preserves_pending_session() {
1245        let mut auth = TestAuthSession::default();
1246        let challenge = TwoFactorChallenge::new("account-1".to_string());
1247        auth.set_pending_two_factor_challenge(&challenge);
1248        let original_entries = auth.session.entries.clone();
1249        let state_called = Cell::new(false);
1250        let mut ctx = LoginContext::new(&mut auth, true);
1251        let error = complete_two_factor_login(
1252            &mut ctx,
1253            TwoFactorLoginForm::new(challenge.token().to_string(), "123456".to_string()),
1254            &SecurityState::new(100.try_into().unwrap()),
1255            TwoFactorLoginCallbacks {
1256                load_account: |id: &str| {
1257                    assert_eq!(id, "account-1");
1258                    std::future::ready(Ok::<_, AuthError>(TestAccount {
1259                        id: id.to_string(),
1260                        decision: AuthDecision::allow(),
1261                        account_hash: "hash".to_string(),
1262                    }))
1263                },
1264                load_two_factor_state: |_account: &TestAccount| {
1265                    state_called.set(true);
1266                    std::future::ready(Err::<(bool, Option<String>), _>(anyhow::anyhow!(
1267                        "state-backend-sensitive-marker"
1268                    )))
1269                },
1270                consume_backup_code:
1271                    |_account: &TestAccount,
1272                     _code: &str|
1273                     -> std::future::Ready<Result<bool, AuthError>> {
1274                        panic!("state backend failure must not consume backup codes")
1275                    },
1276                consume_totp_step: async |_: &TestAccount, _: &str, _: u64| {
1277                    Ok::<_, std::convert::Infallible>(true)
1278                },
1279                build_user: |_account: &TestAccount| -> TestAccount {
1280                    panic!("state backend failure must not build a session user")
1281                },
1282                on_success: |_, _| -> std::future::Ready<()> {
1283                    panic!("state backend failure must not authenticate")
1284                },
1285                on_cleanup: |_| -> std::future::Ready<()> {
1286                    panic!("state backend failure must preserve the pending challenge")
1287                },
1288            },
1289        )
1290        .await
1291        .expect_err("backend state failure must be typed");
1292
1293        assert!(state_called.get());
1294        assert!(matches!(error, TwoFactorLoginError::StateUnavailable));
1295        assert!(!format!("{error} {error:?}").contains("state-backend-sensitive-marker"));
1296        assert_eq!(auth.session.entries, original_entries);
1297        assert!(!auth.store && !auth.remember);
1298        assert_eq!(auth.renewals, 0);
1299        assert!(auth.logged_in.is_none() && auth.user.is_none());
1300    }
1301
1302    #[tokio::test]
1303    async fn two_factor_invalid_stored_secret_returns_totp_decode_error() {
1304        let mut auth = TestAuthSession::default();
1305        let challenge = TwoFactorChallenge::new("account-1".to_string());
1306        auth.set_pending_two_factor_challenge(&challenge);
1307        let original_entries = auth.session.entries.clone();
1308        let mut ctx = LoginContext::new(&mut auth, true);
1309        let error = complete_two_factor_login(
1310            &mut ctx,
1311            TwoFactorLoginForm::new(challenge.token().to_string(), "123456".to_string()),
1312            &SecurityState::new(100.try_into().unwrap()),
1313            TwoFactorLoginCallbacks {
1314                load_account: |_id: &str| {
1315                    std::future::ready(Ok::<_, AuthError>(TestAccount {
1316                        id: "account-1".to_string(),
1317                        decision: AuthDecision::allow(),
1318                        account_hash: "hash".to_string(),
1319                    }))
1320                },
1321                load_two_factor_state: |_account: &TestAccount| {
1322                    std::future::ready(Ok::<_, AuthError>((
1323                        true,
1324                        Some("stored-secret-sensitive-marker!!!".to_string()),
1325                    )))
1326                },
1327                consume_backup_code:
1328                    |_account: &TestAccount,
1329                     _code: &str|
1330                     -> std::future::Ready<Result<bool, AuthError>> {
1331                        panic!("a TOTP request must not fall back to backup consumption")
1332                    },
1333                consume_totp_step: async |_: &TestAccount, _: &str, _: u64| {
1334                    Ok::<_, std::convert::Infallible>(true)
1335                },
1336                build_user: |_account: &TestAccount| -> TestAccount {
1337                    panic!("a corrupt server secret must not build a session user")
1338                },
1339                on_success: |_, _| -> std::future::Ready<()> {
1340                    panic!("a corrupt server secret must not authenticate")
1341                },
1342                on_cleanup: |_| -> std::future::Ready<()> {
1343                    panic!("a corrupt server secret must preserve the pending challenge")
1344                },
1345            },
1346        )
1347        .await
1348        .expect_err("real TOTP verification must reject an undecodable stored secret");
1349
1350        assert!(matches!(
1351            error,
1352            TwoFactorLoginError::Totp(TwoFactorServerError::TotpDecode)
1353        ));
1354        assert!(!format!("{error} {error:?}").contains("stored-secret-sensitive-marker"));
1355        assert_eq!(auth.session.entries, original_entries);
1356        assert!(!auth.store && !auth.remember);
1357        assert_eq!(auth.renewals, 0);
1358        assert!(auth.logged_in.is_none() && auth.user.is_none());
1359    }
1360
1361    #[tokio::test]
1362    async fn two_factor_backup_backend_failure_is_redacted_and_preserves_session() {
1363        let mut auth = TestAuthSession::default();
1364        let challenge = TwoFactorChallenge::new("account-1".to_string());
1365        auth.set_pending_two_factor_challenge(&challenge);
1366        let original_entries = auth.session.entries.clone();
1367        let consume_called = Cell::new(false);
1368        let mut ctx = LoginContext::new(&mut auth, true);
1369        let error = complete_two_factor_login(
1370            &mut ctx,
1371            TwoFactorLoginForm::new(challenge.token().to_string(), "ABCDEFGH".to_string()),
1372            &SecurityState::new(100.try_into().unwrap()),
1373            TwoFactorLoginCallbacks {
1374                load_account: |_id: &str| {
1375                    std::future::ready(Ok::<_, AuthError>(TestAccount {
1376                        id: "account-1".to_string(),
1377                        decision: AuthDecision::allow(),
1378                        account_hash: "hash".to_string(),
1379                    }))
1380                },
1381                load_two_factor_state: |_account: &TestAccount| {
1382                    std::future::ready(Ok::<_, AuthError>((true, None)))
1383                },
1384                consume_backup_code: |account: &TestAccount, code: &str| {
1385                    assert_eq!(account.id, "account-1");
1386                    assert_eq!(code, "ABCDEFGH");
1387                    consume_called.set(true);
1388                    std::future::ready(Err::<bool, _>(anyhow::anyhow!(
1389                        "backup-backend-sensitive-marker"
1390                    )))
1391                },
1392                consume_totp_step: async |_: &TestAccount, _: &str, _: u64| {
1393                    Ok::<_, std::convert::Infallible>(true)
1394                },
1395                build_user: |_account: &TestAccount| -> TestAccount {
1396                    panic!("failed atomic consumption must not build a session user")
1397                },
1398                on_success: |_, _| -> std::future::Ready<()> {
1399                    panic!("failed atomic consumption must not authenticate")
1400                },
1401                on_cleanup: |_| -> std::future::Ready<()> {
1402                    panic!("failed atomic consumption must preserve the pending challenge")
1403                },
1404            },
1405        )
1406        .await
1407        .expect_err("atomic backup consumption failure must be typed");
1408
1409        assert!(consume_called.get());
1410        assert!(matches!(error, TwoFactorLoginError::BackupUnavailable));
1411        assert!(std::error::Error::source(&error).is_none());
1412        assert!(!format!("{error} {error:?}").contains("backup-backend-sensitive-marker"));
1413        assert_eq!(auth.session.entries, original_entries);
1414        assert!(!auth.store && !auth.remember);
1415        assert_eq!(auth.renewals, 0);
1416        assert!(auth.logged_in.is_none() && auth.user.is_none());
1417    }
1418
1419    #[tokio::test]
1420    async fn two_factor_real_totp_success_establishes_authenticated_session() {
1421        const SECRET: &str = "JBSWY3DPEHPK3PXP";
1422        let now = std::time::SystemTime::now()
1423            .duration_since(std::time::UNIX_EPOCH)
1424            .expect("test clock must follow the Unix epoch");
1425        let remainder = (now.as_millis() % 30_000) as u64;
1426        if remainder >= 29_000 {
1427            tokio::time::sleep(std::time::Duration::from_millis(30_020 - remainder)).await;
1428        }
1429        let timestamp = std::time::SystemTime::now()
1430            .duration_since(std::time::UNIX_EPOCH)
1431            .expect("test clock must follow the Unix epoch")
1432            .as_secs();
1433        let code = otpauth::TOTP::from_base32(SECRET)
1434            .expect("synthetic TOTP secret must decode")
1435            .generate(30, timestamp);
1436        let mut auth = TestAuthSession::default();
1437        let challenge = TwoFactorChallenge::new("account-1".to_string());
1438        auth.set_pending_two_factor_challenge(&challenge);
1439        let expected_account = TestAccount {
1440            id: "account-1".to_string(),
1441            decision: AuthDecision::allow(),
1442            account_hash: "hash".to_string(),
1443        };
1444        let success_called = Cell::new(false);
1445        let mut ctx = LoginContext::new(&mut auth, true);
1446        let outcome = complete_two_factor_login(
1447            &mut ctx,
1448            TwoFactorLoginForm::new(challenge.token().to_string(), format!("{code:06}")),
1449            &SecurityState::new(100.try_into().unwrap()),
1450            TwoFactorLoginCallbacks {
1451                load_account: |id: &str| {
1452                    assert_eq!(id, expected_account.id);
1453                    std::future::ready(Ok::<_, AuthError>(expected_account.clone()))
1454                },
1455                load_two_factor_state: |_account: &TestAccount| {
1456                    std::future::ready(Ok::<_, AuthError>((true, Some(SECRET.to_string()))))
1457                },
1458                consume_backup_code:
1459                    |_account: &TestAccount,
1460                     _code: &str|
1461                     -> std::future::Ready<Result<bool, AuthError>> {
1462                        panic!("real TOTP success must not consume a backup code")
1463                    },
1464                consume_totp_step: async |_: &TestAccount, _: &str, _: u64| {
1465                    Ok::<_, std::convert::Infallible>(true)
1466                },
1467                build_user: |account: &TestAccount| account.clone(),
1468                on_success: |session: &mut TestAuthSession, account: TestAccount| {
1469                    assert_eq!(account, expected_account);
1470                    assert_eq!(session.logged_in.as_deref(), Some("account-1"));
1471                    assert!(session.store && session.remember);
1472                    assert_eq!(session.renewals, 1);
1473                    assert!(session.pending_two_factor_challenge().is_none());
1474                    success_called.set(true);
1475                    std::future::ready(())
1476                },
1477                on_cleanup: |_| -> std::future::Ready<()> {
1478                    panic!("successful login must use its success callback")
1479                },
1480            },
1481        )
1482        .await
1483        .expect("real current TOTP must authenticate");
1484
1485        assert!(outcome.success && !outcome.requires_two_factor);
1486        assert_eq!(outcome.error_code, LoginErrorCode::None);
1487        assert!(success_called.get());
1488        assert_eq!(auth.logged_in.as_deref(), Some("account-1"));
1489        assert_eq!(auth.user, Some(expected_account));
1490        assert!(auth.store && auth.remember);
1491        assert_eq!(auth.renewals, 1);
1492        assert!(auth.pending_two_factor_challenge().is_none());
1493    }
1494
1495    async fn complete_totp_fixture(
1496        auth: &mut TestAuthSession,
1497        form: TwoFactorLoginForm,
1498        security: &SecurityState,
1499        consume_result: Result<bool, AuthError>,
1500        load_count: &Cell<usize>,
1501    ) -> Result<LoginOutcome, TwoFactorLoginError> {
1502        let mut ctx = LoginContext::new(auth, true);
1503        complete_two_factor_login(
1504            &mut ctx,
1505            form,
1506            security,
1507            TwoFactorLoginCallbacks {
1508                load_account: |id: &str| {
1509                    load_count.set(load_count.get() + 1);
1510                    std::future::ready(Ok::<_, AuthError>(TestAccount {
1511                        id: id.to_owned(),
1512                        account_hash: "hash".to_owned(),
1513                        decision: AuthDecision::allow(),
1514                    }))
1515                },
1516                load_two_factor_state: |_: &TestAccount| {
1517                    std::future::ready(Ok::<_, AuthError>((
1518                        true,
1519                        Some("JBSWY3DPEHPK3PXP".to_owned()),
1520                    )))
1521                },
1522                consume_totp_step: async |_: &TestAccount, secret: &str, _: u64| {
1523                    assert_eq!(secret, "JBSWY3DPEHPK3PXP");
1524                    consume_result
1525                },
1526                consume_backup_code: |_: &TestAccount, _: &str| {
1527                    std::future::ready(Ok::<_, AuthError>(false))
1528                },
1529                build_user: |account: &TestAccount| account.clone(),
1530                on_success: |_, _| std::future::ready(()),
1531                on_cleanup: |_| std::future::ready(()),
1532            },
1533        )
1534        .await
1535    }
1536
1537    #[tokio::test]
1538    async fn verified_totp_requires_successful_durable_consumption_before_session_creation() {
1539        let now = std::time::SystemTime::now()
1540            .duration_since(std::time::UNIX_EPOCH)
1541            .unwrap();
1542        let remainder = (now.as_millis() % 30_000) as u64;
1543        if remainder >= 29_000 {
1544            tokio::time::sleep(std::time::Duration::from_millis(30_020 - remainder)).await;
1545        }
1546        for consume_result in [
1547            Ok(false),
1548            Err(anyhow::anyhow!("private database secret")),
1549            Ok(true),
1550        ] {
1551            let expected = match &consume_result {
1552                Ok(value) => Some(*value),
1553                Err(_) => None,
1554            };
1555            let mut auth = TestAuthSession::default();
1556            let challenge = TwoFactorChallenge::new("account-1".to_owned());
1557            auth.set_pending_two_factor_challenge(&challenge);
1558            let timestamp = std::time::SystemTime::now()
1559                .duration_since(std::time::UNIX_EPOCH)
1560                .unwrap()
1561                .as_secs();
1562            let code = otpauth::TOTP::from_base32("JBSWY3DPEHPK3PXP")
1563                .unwrap()
1564                .generate(30, timestamp);
1565            let result = complete_totp_fixture(
1566                &mut auth,
1567                TwoFactorLoginForm::new(challenge.token().to_owned(), format!("{code:06}")),
1568                &SecurityState::new(100.try_into().unwrap()),
1569                consume_result,
1570                &Cell::new(0),
1571            )
1572            .await;
1573            match expected {
1574                Some(true) => assert!(result.expect("durable consumption").success),
1575                Some(false) => assert_eq!(
1576                    result.expect("replay rejection").error_code,
1577                    LoginErrorCode::TwoFactorInvalid
1578                ),
1579                None => {
1580                    let error = result.expect_err("storage failure must fail closed");
1581                    assert!(matches!(error, TwoFactorLoginError::ConsumptionUnavailable));
1582                    assert!(!format!("{error:?} {error}").contains("private"));
1583                }
1584            }
1585            assert_eq!(auth.logged_in.is_some(), expected == Some(true));
1586            assert_eq!(auth.renewals, usize::from(expected == Some(true)));
1587            assert_eq!(
1588                auth.pending_two_factor_challenge().is_some(),
1589                expected != Some(true)
1590            );
1591        }
1592    }
1593
1594    #[tokio::test]
1595    async fn invalid_challenges_do_not_spend_account_budget_and_new_challenges_do_not_reset_it() {
1596        let security = SecurityState::with_auth_policy(
1597            100.try_into().unwrap(),
1598            crate::ratelimit::AuthRateLimitPolicy {
1599                two_factor_account_per_minute: 1.try_into().unwrap(),
1600                ..Default::default()
1601            },
1602        );
1603        let loads = Cell::new(0);
1604        for invalid_kind in 0..3 {
1605            let mut auth = TestAuthSession::default();
1606            let challenge = TwoFactorChallenge::new("account-1".to_owned());
1607            if invalid_kind != 0 {
1608                let challenge = if invalid_kind == 1 {
1609                    let mut value = serde_json::to_value(&challenge).unwrap();
1610                    value["issued_at"] = serde_json::to_value(
1611                        time::OffsetDateTime::now_utc() - time::Duration::hours(1),
1612                    )
1613                    .unwrap();
1614                    serde_json::from_value(value).unwrap()
1615                } else {
1616                    challenge.clone()
1617                };
1618                auth.set_pending_two_factor_challenge(&challenge);
1619            }
1620            let token = if invalid_kind == 2 {
1621                uuid::Uuid::new_v4().to_string()
1622            } else {
1623                challenge.token().to_owned()
1624            };
1625            let result = complete_totp_fixture(
1626                &mut auth,
1627                TwoFactorLoginForm::new(token, "000000".to_owned()),
1628                &security,
1629                Ok(true),
1630                &loads,
1631            )
1632            .await
1633            .unwrap();
1634            assert!(!result.success);
1635            assert_ne!(result.error_code, LoginErrorCode::RateLimited);
1636        }
1637        assert_eq!(loads.get(), 0);
1638        for (attempt, expected) in [
1639            LoginErrorCode::TwoFactorInvalid,
1640            LoginErrorCode::RateLimited,
1641        ]
1642        .into_iter()
1643        .enumerate()
1644        {
1645            let mut auth = TestAuthSession::default();
1646            let challenge = TwoFactorChallenge::new("account-1".to_owned());
1647            auth.set_pending_two_factor_challenge(&challenge);
1648            assert!(
1649                security
1650                    .check_two_factor(&format!("192.0.2.{}", attempt + 1))
1651                    .is_ok()
1652            );
1653            let result = complete_totp_fixture(
1654                &mut auth,
1655                TwoFactorLoginForm::new(challenge.token().to_owned(), "ABCDEFGH".to_owned()),
1656                &security,
1657                Ok(true),
1658                &loads,
1659            )
1660            .await
1661            .unwrap();
1662            assert_eq!(result.error_code, expected);
1663            assert!(auth.logged_in.is_none());
1664        }
1665        assert_eq!(
1666            loads.get(),
1667            1,
1668            "exhausted account must reject before backend work"
1669        );
1670    }
1671
1672    /// Verifies the macro-generated trait impls expose the expected fields.
1673    #[test]
1674    fn macro_impls_expose_login_fields() {
1675        let account = MacroAccount {
1676            id: "account-1".to_string(),
1677            status: MacroStatus::Active,
1678            account_hash: "hash".to_string(),
1679        };
1680        let blocked_account = MacroAccount {
1681            id: "account-2".to_string(),
1682            status: MacroStatus::Blocked,
1683            account_hash: "hash-2".to_string(),
1684        };
1685        let credentials = MacroCredentials {
1686            account: account.clone(),
1687            password_hash: "hashed".to_string(),
1688            twofa_enabled: true,
1689        };
1690
1691        assert_eq!(LoginAccount::id(&account), "account-1");
1692        assert!(matches!(
1693            LoginAccount::auth_decision(&account),
1694            AuthDecision::Allow
1695        ));
1696        assert!(matches!(
1697            LoginAccount::auth_decision(&blocked_account),
1698            AuthDecision::Deny(reason) if reason == AuthDenyReason::blocked()
1699        ));
1700        assert_eq!(AccountHash::account_hash(&account), "hash");
1701        assert_eq!(LoginCredentials::password_hash(&credentials), "hashed");
1702        assert!(LoginCredentials::two_factor_enabled(&credentials));
1703        assert_eq!(
1704            LoginAccount::id(LoginCredentials::account(&credentials)),
1705            "account-1"
1706        );
1707    }
1708}