axess-core 0.5.1

Core implementation for the axess library. Session state machine, multi-factor authentication engine, Cedar Policy evaluation, and pluggable storage backends. Use the `axess` facade crate unless you need direct access to internals.
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
//! Login flow: begin_login, prepare_factor, verify_factor, check_session, logout.

use super::outcomes::{FactorOutcome, LoginOutcome, PrepareOutcome};
use super::verification::{VerifyOutcome, generate_otp_code, verify_credential};
use crate::authn::{
    error::AuthnError,
    event::{AuthEventBuilder, AuthEventType},
    factor::{FactorConfig, FactorCredential, FactorKind},
    store::{FactorStore, IdentityStore},
    types::{AuthnScope, EntityState},
};
use crate::session::extractor::AuthSession;
impl<I, F> super::AuthnService<I, F>
where
    I: IdentityStore,
    F: FactorStore<Error = I::Error>,
{
    /// Begin the login flow for an identifier (username/email) within a tenant.
    ///
    /// Looks up the user, checks account status, and begins the first factor.
    /// Updates the session to `Authenticating`.
    ///
    /// Returns a [`LoginOutcome`] describing what the UI should do next.
    #[tracing::instrument(skip(self, session, client_ip), fields(tenant = %tenant_identifier))]
    pub async fn begin_login(
        &self,
        identifier: &str,
        tenant_identifier: &str,
        session: &AuthSession,
        client_ip: Option<std::net::IpAddr>,
    ) -> Result<LoginOutcome, AuthnError<I::Error>> {
        use crate::validation::MAX_IDENTIFIER_BYTES;

        self.metrics.auth_attempt();

        // 0. Reject oversized identifiers before hitting the database.
        if identifier.is_empty()
            || identifier.len() > MAX_IDENTIFIER_BYTES
            || tenant_identifier.is_empty()
            || tenant_identifier.len() > MAX_IDENTIFIER_BYTES
        {
            self.metrics.auth_failure();
            return Ok(LoginOutcome::InvalidCredentials);
        }

        // 1. Find tenant. An unknown tenant is a credential failure like
        // any other, not a distinct error: returning `NotActive` here made
        // tenant existence observable, because that variant maps to 403
        // "account not active" while a wrong password yields
        // `InvalidCredentials`. An attacker could separate "no such tenant"
        // from "wrong password" on the status code alone, which is the
        // enumeration the identifier path below is careful to prevent.
        //
        // Response shape alone is not enough: bailing out here would skip
        // the user lookup entirely and answer measurably sooner, so the
        // same dummy store queries run against a throwaway tenant id to
        // keep the timing of an unknown tenant in line with a known one.
        let tenant = match self
            .identity
            .find_tenant(tenant_identifier)
            .await
            .map_err(AuthnError::Store)?
        {
            Some(t) => t,
            None => {
                let dummy_tenant =
                    crate::authn::ids::TenantId::try_new(uuid::Uuid::new_v4().to_string())
                        .expect("fresh v4 UUID is a valid TenantId");
                let _ = self
                    .find_user_with_timing_equalization(identifier, &dummy_tenant)
                    .await;
                self.metrics.auth_failure();
                return Ok(LoginOutcome::InvalidCredentials);
            }
        };

        if let Err(e) = tenant.validate() {
            tracing::error!(error = %e, "IdentityStore returned invalid Tenant");
            self.metrics.auth_failure();
            return Ok(LoginOutcome::InvalidCredentials);
        }

        // 1a. Enforce tenant-level status. A Suspended or Terminated
        // tenant rejects all logins before we reveal anything
        // user-specific; this is the operator lever for "lock everyone
        // out of tenant X" (see `docs/identity/tenancy.md`).
        if !tenant.status.allows_login() {
            tracing::warn!(
                tenant = %tenant.id,
                status = ?tenant.status,
                "login rejected: tenant status does not allow login"
            );
            self.metrics.auth_failure();
            return Err(AuthnError::NotActive(tenant.status.clone()));
        }

        // 1b. Enforce tenant IP policy if a client IP was provided.
        if let Some(ip) = client_ip {
            let policy = self
                .identity
                .ip_policy_for_tenant(&tenant.id)
                .await
                .map_err(AuthnError::Store)?;
            if !policy.is_allowed(ip) {
                tracing::warn!(
                    tenant = %tenant.id,
                    client_ip = %ip,
                    "login rejected by tenant IP policy"
                );
                self.metrics.auth_failure();
                return Ok(LoginOutcome::InvalidCredentials);
            }
        }

        // 2. Find user with timing equalization; when the identifier is
        // unknown OR the returned User fails validation, the helper
        // still runs the same store queries the happy path would,
        // against a fresh-UUID dummy id, so DB latency doesn't leak
        // whether the identifier exists. See helper for the full
        // security argument.
        let user = match self
            .find_user_with_timing_equalization(identifier, &tenant.id)
            .await?
        {
            Some(u) => u,
            None => {
                self.metrics.auth_failure();
                return Ok(LoginOutcome::InvalidCredentials);
            }
        };

        // 3. Check account status.
        let status = self
            .identity
            .account_status(&user.id)
            .await
            .map_err(AuthnError::Store)?;

        if !status.allows_login() {
            self.metrics.auth_failure();
            // Emit a `Failure(LoginAttempt)` audit row before returning so
            // a fresh session probing a known-locked account leaves a SOC
            // trail. `begin_login` does not go through
            // `enforce_account_status`, so the audit emit must happen
            // here explicitly. The error tag distinguishes locked from
            // other non-active states so dashboards can separate
            // brute-force probes from administrative-state mismatches.
            let error_tag = if status.is_locked() {
                "locked"
            } else {
                "not_active"
            };
            self.emit_audit(
                AuthEventBuilder::failure(AuthEventType::LoginAttempt)
                    .attributed_to(&user.id, &tenant.id)
                    .with_error(error_tag),
            )
            .await;
            if status.is_locked() {
                self.metrics.account_locked();
                // Surface the lockout expiry so UIs can render
                // "locked until X" on the begin path. Mirrors
                // `prepare_factor`: read `until` off
                // `Suspended(StatusDetail{until,..})` when the store
                // carries it.
                let until = if let EntityState::Suspended(detail) = &status {
                    detail.until
                } else {
                    None
                };
                return Ok(LoginOutcome::Locked { until });
            }
            return Err(AuthnError::NotActive(status));
        }

        // 4. Load available authentication methods.
        let methods = self
            .factors
            .available_methods(&user.id, &tenant.id)
            .await
            .map_err(AuthnError::Store)?;

        let method = methods.into_iter().next().ok_or(AuthnError::NoFlow)?;

        let resolved_factors = method.factors();
        if resolved_factors.is_empty() {
            self.metrics.auth_failure();
            return Ok(LoginOutcome::InvalidCredentials);
        }

        let first_kind = resolved_factors[0].clone();

        // 5. Begin the authentication flow in the session.
        session
            .begin_authenticating(user.id, tenant.id, method.name.clone(), resolved_factors)
            .await;

        // Record login attempt event.
        self.emit_audit(
            AuthEventBuilder::success(AuthEventType::LoginAttempt)
                .attributed_to(&user.id, &tenant.id)
                .with_factor(first_kind.clone()),
        )
        .await;

        Ok(LoginOutcome::FactorRequired(first_kind))
    }

    /// Prepare the current factor challenge, if the factor kind requires it.
    ///
    /// Call this after `begin_login` (or after a successful `verify_factor`
    /// that returns `FactorRequired`) to set up the next factor step.
    ///
    /// - **Password / TOTP / HOTP** → returns [`PrepareOutcome::Ready`].
    ///   The UI can show the input form immediately.
    /// - **EmailOtp** → generates a random code, hashes it with Argon2id,
    ///   persists it in the factor store, and returns
    ///   [`PrepareOutcome::SendOtp`] with the plaintext code and the
    ///   destination email. The application is responsible for delivering the
    ///   code (via SMTP, SendGrid, etc.).
    /// - **Fido2** → placeholder, currently returns `Ready`.
    ///
    /// The session must be in [`AuthState::Authenticating`](crate::session::data::AuthState::Authenticating).
    #[tracing::instrument(skip(self, session))]
    pub async fn prepare_factor(
        &self,
        session: &AuthSession,
    ) -> Result<PrepareOutcome, AuthnError<I::Error>> {
        use super::factor_pipeline::AccountStatusEnforcement;

        let (user_id, tenant_id, remaining) = session
            .authenticating_state()
            .await
            .ok_or(AuthnError::NoFlow)?;

        // A locked/suspended (or otherwise non-Active) account must not
        // trigger challenge delivery (e.g. OTP email sends). The
        // The audit row on `Locked` is emitted by
        // `enforce_account_status` itself.
        match self
            .enforce_account_status(&user_id, &tenant_id, remaining.first().cloned(), session)
            .await?
        {
            AccountStatusEnforcement::Ok => {}
            // Distinguish locked (suspension) from other
            // non-Active states. UIs can render the lockout expiry
            // for `Locked` and a generic "account not active" for
            // the rest. The earlier behaviour collapsed both into
            // `NotActive(status)`, forcing UIs to deep-pattern-match
            // `EntityState::Suspended(StatusDetail { until, .. })`
            // to render the expiry; the new shape exposes `until`
            // at the top level.
            AccountStatusEnforcement::Locked { until, .. } => {
                return Err(AuthnError::Locked { until });
            }
            AccountStatusEnforcement::NotActive(status) => {
                return Err(AuthnError::NotActive(status));
            }
        }

        let current_kind = remaining.first().ok_or(AuthnError::NoFlow)?.clone();

        match current_kind {
            FactorKind::Password | FactorKind::Totp | FactorKind::Hotp | FactorKind::LdapBind => {
                Ok(PrepareOutcome::Ready)
            }

            FactorKind::EmailOtp => {
                // Load the EmailOtp config to get the destination and parameters.
                let user_scope = AuthnScope::User { tenant_id, user_id };
                let config = self
                    .factors
                    .resolve_factor(&user_scope, FactorKind::EmailOtp)
                    .await
                    .map_err(AuthnError::Store)?
                    .ok_or(AuthnError::NoFlow)?
                    .config;

                // Take ownership of the inner cfg up front so we don't
                // need a second destructure (which used to require an
                // unreachable arm for "config changed kind mid-function").
                let FactorConfig::EmailOtp(mut cfg) = config else {
                    return Err(AuthnError::NoFlow);
                };

                // Cooldown: reject if a pending code hasn't expired yet.
                // This prevents email bombing; the application can only trigger
                // one send per TTL window.
                let now = self.clock.now();
                if cfg.pending_until.is_some_and(|until| now < until) {
                    return Ok(PrepareOutcome::AlreadySent {
                        destination: cfg.email.clone(),
                    });
                }

                let email = cfg.email.clone();
                let code_length = cfg.code_length as usize;
                let ttl_secs = cfg.ttl_secs;

                // Reject unreasonable code lengths to prevent DoS via
                // misconfigured factor config.
                if !(4..=8).contains(&code_length) {
                    tracing::error!(code_length, "email OTP code_length out of bounds (4–8)");
                    return Err(AuthnError::NoFlow);
                }

                // Generate a random numeric code using the injectable RNG.
                // Wrap in ZeroizedString so it's cleared from memory after use.
                let code = crate::authn::factor::ZeroizedString::new(generate_otp_code(
                    &self.rng,
                    code_length,
                ));

                // Hash the code with Argon2id for storage.
                let hash = axess_factors::generate_password_hash(&*code);

                // Compute expiry from config TTL.
                let expires = now + chrono::Duration::seconds(ttl_secs as i64);

                cfg.pending_hash = Some(crate::authn::factor::ZeroizedString::new(hash));
                cfg.pending_until = Some(expires);

                // Save to user scope (per-user pending state).
                self.factors
                    .save_factor(&user_scope, FactorConfig::EmailOtp(cfg))
                    .await
                    .map_err(AuthnError::Store)?;

                Ok(PrepareOutcome::SendOtp {
                    code,
                    destination: email,
                })
            }

            FactorKind::Fido2 => {
                #[cfg(feature = "fido2")]
                {
                    let webauthn = match &self.fido2 {
                        Some(w) => w,
                        None => return Ok(PrepareOutcome::Ready),
                    };

                    // Load stored credentials.
                    let user_scope = AuthnScope::User { tenant_id, user_id };
                    let config = self
                        .factors
                        .resolve_factor(&user_scope, FactorKind::Fido2)
                        .await
                        .map_err(AuthnError::Store)?
                        .ok_or(AuthnError::NoFlow)?
                        .config;

                    let FactorConfig::Fido2(cfg) = &config else {
                        return Err(AuthnError::NoFlow);
                    };

                    if cfg.credentials.is_empty() {
                        return Err(AuthnError::NoFlow);
                    }

                    // Extract raw passkeys for the ceremony.
                    let passkeys: Vec<_> =
                        cfg.credentials.iter().map(|c| c.passkey.clone()).collect();

                    // Start the authentication ceremony.
                    let (challenge, auth_state) =
                        webauthn.start_authentication(&passkeys).map_err(|e| {
                            tracing::warn!("FIDO2 start_passkey_authentication failed: {e:?}");
                            AuthnError::NoFlow
                        })?;

                    // Store the ceremony state and timestamp in the session.
                    let state_json =
                        serde_json::to_value(&auth_state).map_err(|_| AuthnError::NoFlow)?;
                    session.set_custom(fido2_keys::AUTH_STATE, state_json).await;
                    self.stamp_ceremony_start(session).await;

                    let challenge_json =
                        serde_json::to_value(&challenge).map_err(|_| AuthnError::NoFlow)?;
                    Ok(PrepareOutcome::Fido2Challenge {
                        challenge: challenge_json,
                    })
                }

                #[cfg(not(feature = "fido2"))]
                {
                    Ok(PrepareOutcome::Ready)
                }
            }

            FactorKind::Federated(_) => {
                // Federated auth is handled externally (OAuth redirect flow).
                Ok(PrepareOutcome::Ready)
            }
        }
    }

    /// Verify a factor credential during an in-progress authentication flow.
    ///
    /// The session must be in [`AuthState::Authenticating`](crate::session::data::AuthState::Authenticating).
    /// Returns a [`FactorOutcome`] describing the next step.
    #[tracing::instrument(skip(self, credential, session))]
    pub async fn verify_factor(
        &self,
        credential: &FactorCredential,
        session: &AuthSession,
    ) -> Result<FactorOutcome, AuthnError<I::Error>> {
        use super::factor_pipeline::AccountStatusEnforcement;

        let (user_id, tenant_id, remaining) = session
            .authenticating_state()
            .await
            .ok_or(AuthnError::NoFlow)?;

        match self
            .enforce_account_status(&user_id, &tenant_id, remaining.first().cloned(), session)
            .await?
        {
            AccountStatusEnforcement::Ok => {}
            AccountStatusEnforcement::Locked { until, .. } => {
                return Ok(FactorOutcome::Locked { until });
            }
            AccountStatusEnforcement::NotActive(status) => {
                return Err(AuthnError::NotActive(status));
            }
        }

        let current_kind = remaining.first().ok_or(AuthnError::NoFlow)?.clone();

        // Runtime resolution: User → Tenant → System, single-query in the store.
        let user_scope = AuthnScope::User { tenant_id, user_id };
        let config = self
            .factors
            .resolve_factor(&user_scope, current_kind.clone())
            .await
            .map_err(AuthnError::Store)?
            .ok_or(AuthnError::NoFlow)?
            .config;

        // FIDO2 + LDAP have their own verification methods (different
        // ceremony shape, network call) and short-circuit with their
        // own FactorOutcome. The local-hash factors continue below.
        #[cfg(feature = "fido2")]
        if current_kind == FactorKind::Fido2 {
            return self
                .verify_fido2_factor(
                    credential,
                    &config,
                    &user_scope,
                    &user_id,
                    &tenant_id,
                    session,
                )
                .await;
        }
        #[cfg(feature = "ldap")]
        if current_kind == FactorKind::LdapBind {
            return self
                .verify_ldap_factor(credential, &config, &user_id, &tenant_id, session)
                .await;
        }

        self.metrics.factor_attempt();
        let outcome = verify_credential(credential, &config, &current_kind, self.clock.now());

        if let VerifyOutcome::FailWithUpdate(updated_config) = &outcome {
            self.persist_fail_with_update(&user_scope, current_kind.clone(), updated_config)
                .await?;
        }

        if matches!(
            outcome,
            VerifyOutcome::Fail | VerifyOutcome::FailWithUpdate(_)
        ) {
            return self
                .record_factor_failure(&user_id, &tenant_id, &current_kind, session)
                .await;
        }

        self.metrics.factor_success();

        if let VerifyOutcome::PassWithUpdate(updated_config) = outcome {
            let swapped = self
                .persist_pass_with_update(&user_scope, current_kind.clone(), updated_config)
                .await?;
            if !swapped {
                // Concurrent verification spent the same step/counter
                // first; treat as a replay and reject.
                self.metrics.factor_failure();
                return Ok(FactorOutcome::InvalidCredential);
            }
        }

        session
            .advance_factor(&current_kind, self.clock.now())
            .await;
        self.complete_factor_step(&user_id, &tenant_id, session)
            .await
    }

    /// Check whether the current session is valid (consults the registry if installed).
    #[tracing::instrument(skip(self, session))]
    pub async fn check_session(&self, session: &AuthSession) -> bool {
        if !session.is_authenticated().await {
            return false;
        }
        let user_id = match session.user_id().await {
            Some(id) => id,
            None => return false,
        };
        let sid = session.session_id().await;
        if let Some(reg) = &self.registry {
            reg.is_valid(&user_id, &sid).await
        } else {
            true
        }
    }

    /// Log out the current user: clear the session and invalidate in the registry.
    #[tracing::instrument(skip(self, session))]
    pub async fn logout(&self, session: &AuthSession) -> Result<(), AuthnError<I::Error>> {
        if let Some(user_id) = session.user_id().await {
            self.metrics.session_invalidated();
            let sid = session.session_id().await;
            if let Some(reg) = &self.registry {
                reg.invalidate_user(&user_id).await;
            }
            // When the session is authenticated (user_id exists) but the
            // tenant is somehow missing, record the logout event with
            // `tenant_id = None` rather than inventing an attribution.
            // Logged at WARN because it should never happen in practice:
            // authenticated sessions always carry a tenant_id.
            let tenant_id = session.tenant_id().await;
            if tenant_id.is_none() {
                tracing::warn!(
                    user_id = %user_id,
                    "logout: authenticated session missing tenant_id; audit event will have no tenant attribution",
                );
            }
            self.emit_audit(
                AuthEventBuilder::success(AuthEventType::LogoutAttempt)
                    .maybe_attributed_to(Some(&user_id), tenant_id.as_ref())
                    .with_session(sid),
            )
            .await;
        }
        session.clear().await;
        // Cycle the session ID to prevent session fixation after logout.
        session.regenerate().await;
        Ok(())
    }

    /// Look up a user by identifier with timing-equalization on miss.
    ///
    /// Returns `Ok(Some(user))` on a clean find + `validate()`,
    /// `Ok(None)` when the identifier is unknown OR the returned
    /// `User` failed validation. The caller maps `None` to
    /// `LoginOutcome::InvalidCredentials`.
    ///
    /// **Security invariant, do not change this without thinking
    /// carefully:** the `None` paths MUST run the same store queries
    /// the found-user path would (against a fresh-UUID dummy id) so
    /// the response time does not leak whether the identifier
    /// exists. Two-step MFA flows (identify → verify) inherently
    /// reveal whether an identifier maps to a valid account through
    /// the response *shape*, but timing must not be a second
    /// side-channel on top of that. This is the same trade-off
    /// Gmail, Microsoft, and most banks accept.
    ///
    /// The dummy UUID is generated per request so it cannot collide
    /// with any real user (including the reserved
    /// [`UserId::system()`](crate::authn::ids::UserId::system)),
    /// preserving timing-equalization semantics regardless of which
    /// principals the application has installed.
    ///
    /// **Scope of equalisation:** DB queries only. LDAP network
    /// latency is NOT equalised because LDAP bind only happens in
    /// `verify_factor` (after the user is already known to exist);
    /// user enumeration via LDAP timing is not reachable from
    /// `begin_login`. Re-evaluate this comment if any LDAP call
    /// migrates earlier in the flow.
    async fn find_user_with_timing_equalization(
        &self,
        identifier: &str,
        tenant_id: &crate::authn::ids::TenantId,
    ) -> Result<Option<crate::authn::types::User>, AuthnError<I::Error>> {
        let user_opt = self
            .identity
            .find_user(identifier, tenant_id)
            .await
            .map_err(AuthnError::Store)?;

        if let Some(u) = user_opt {
            return match u.validate() {
                Ok(()) => Ok(Some(u)),
                Err(e) => {
                    tracing::error!(error = %e, "IdentityStore returned invalid User");
                    // Validate-fail returns `None` *without* running
                    // the dummy queries below: the user exists (find_user
                    // already paid that cost), the observable response
                    // matches the unknown-user path, and a validate
                    // failure on a stored row indicates internal data
                    // corruption, not an attacker-driven enumeration
                    // probe. Re-evaluate if the threat model changes.
                    Ok(None)
                }
            };
        }

        // Unknown identifier; run the same store queries the
        // happy path would, against a fresh-UUID dummy, to keep
        // response time independent of identifier existence.
        let dummy_id = crate::authn::ids::UserId::try_new(uuid::Uuid::new_v4().to_string())
            .expect("fresh v4 UUID is a valid UserId");
        let _ = self.identity.account_status(&dummy_id).await;
        let _ = self.factors.available_methods(&dummy_id, tenant_id).await;
        Ok(None)
    }
}

// Re-export fido2_keys for use in prepare_factor when fido2 feature is enabled.
#[cfg(feature = "fido2")]
pub(crate) use super::fido2_service::fido2_keys;

#[cfg(test)]
mod login_tests;