axess-core 0.11.0

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.
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
//! [`DeviceLifecycleService`]: opinionated higher-level helper that
//! composes [`DeviceStore`] primitives into the two operations every
//! axess consumer needs at request/authn boundaries:
//!
//! 1. **Ensure-or-create**: given a fingerprint, look up the existing
//!    `Device` row or create a fresh one with
//!    [`DeviceTrustLevel::Unknown`]. Idempotent on the existing-device
//!    path; bumps `last_seen_at` either way (at most once per sighting
//!    granularity for a known device, see
//!    [`DeviceLifecycleService::with_sighting_granularity`]).
//! 2. **Promote-on-authn**: atomically transition `Unknown → Seen`
//!    when authentication succeeds. No-op when the device is already
//!    `Seen`, `Trusted`, or `Revoked`; never re-elevates a revoked
//!    device, never demotes a trusted one.
//!
//! # Why a separate helper (not a trait extension)
//!
//! The store trait stays focused on storage primitives so SQL / Valkey
//! backends don't have to re-implement the lifecycle state machine.
//! Composition over inheritance: every backend that implements
//! [`DeviceStore`] gets the lifecycle logic for free, and the unit
//! tests on the lifecycle live in one place.
//!
//! # What this helper does **not** do
//!
//! - **Compute the fingerprint.** The application supplies a
//!   pre-computed [`FingerprintHash`]. Choosing the input set
//!   (User-Agent family, IP /24, Accept-Language, …), the
//!   tenant-scoped HMAC pepper, and the parsing strategy is an
//!   application concern that varies by deployment;
//!   [`DefaultFingerprintExtractor`](crate::device::DefaultFingerprintExtractor)
//!   is the stock choice, and the lifecycle layer is
//!   fingerprint-agnostic.
//! - **Wire itself into middleware.** The decision of *where* in the
//!   request pipeline `ensure_device` runs is made by the
//!   [`DeviceResolver`](crate::device::DeviceResolver) the session layer
//!   is given (see
//!   [`LifecycleDeviceResolver`](crate::device::LifecycleDeviceResolver)),
//!   or by application code calling it directly. This keeps the helper
//!   testable in isolation and lets apps make the cost trade-offs.
//! - **Revoke devices when a refresh family is compromised.** That is
//!   [`cascade_revoke_by_refresh_family`](crate::device::cascade_revoke_by_refresh_family),
//!   which finds the devices through
//!   [`DeviceStore::find_by_refresh_family`].

use chrono::{DateTime, Utc};
use std::future::Future;
use std::sync::Arc;

use crate::authn::event::{AuthEventBuilder, AuthEventType};
use crate::authn::ids::{DeviceId, TenantId, UserId};
use crate::authn::service::FactorOutcome;
use crate::device::events::{DeviceEventSink, NoopDeviceEventSink};
#[cfg(feature = "fido2")]
use crate::device::store::BindingsUpdate;
use crate::device::store::{DeviceStore, OwnerClaim, TrustTransition};
use crate::device::types::{Device, DeviceTrustLevel, FingerprintHash};

/// How long after a device's recorded `last_seen_at` `ensure_device`
/// treats another sighting as redundant, unless
/// [`DeviceLifecycleService::with_sighting_granularity`] says otherwise.
const DEFAULT_SIGHTING_GRANULARITY_SECS: i64 = 300;

/// How often a bindings edit re-reads the row and tries again after losing a
/// compare-and-swap to a concurrent edit.
#[cfg(feature = "fido2")]
const BINDINGS_RETRIES: usize = 16;

/// `true` when `device` may serve a request made by `user`: the device is
/// unowned, the request is not yet attributed to a user (a guest), or the
/// owner is that user.
fn is_usable_by(device: &Device, user: Option<&UserId>) -> bool {
    match (device.user_id.as_ref(), user) {
        (Some(owner), Some(user)) => owner == user,
        _ => true,
    }
}

/// Composes [`DeviceStore`] primitives into the lifecycle operations
/// every axess consumer needs at request/authn boundaries.
///
/// Cheap to clone (the inner store is `Clone` and the optional event
/// sink is `Arc`-backed); construct once at startup and share across
/// handlers.
#[derive(Clone)]
pub struct DeviceLifecycleService<S>
where
    S: DeviceStore,
{
    store: S,
    /// Optional sink for device-lifecycle audit events.
    /// Defaults to [`NoopDeviceEventSink`] so deployments that don't
    /// (yet) record audit events run unchanged.
    event_sink: Arc<dyn DeviceEventSink>,
    /// A known device whose `last_seen_at` is newer than this is not
    /// written again by `ensure_device`.
    sighting_granularity: chrono::Duration,
}

impl<S> DeviceLifecycleService<S>
where
    S: DeviceStore,
{
    /// Wrap a [`DeviceStore`]. Audit events are dropped on the floor
    /// until [`Self::with_event_sink`] is called; the underlying
    /// device-state mutations always happen regardless.
    pub fn new(store: S) -> Self {
        Self {
            store,
            event_sink: Arc::new(NoopDeviceEventSink),
            sighting_granularity: chrono::Duration::seconds(DEFAULT_SIGHTING_GRANULARITY_SECS),
        }
    }

    /// Set how stale a device's `last_seen_at` must be before
    /// [`ensure_device`](Self::ensure_device) writes a new sighting
    /// (default 5 minutes). A request for a device seen more recently
    /// than `granularity` before `now` performs no write, so a busy
    /// client costs one store write per window rather than one per
    /// request. [`Duration::zero`](chrono::Duration::zero) records every
    /// sighting.
    pub fn with_sighting_granularity(mut self, granularity: chrono::Duration) -> Self {
        self.sighting_granularity = granularity;
        self
    }

    /// Wire a [`DeviceEventSink`] so device-lifecycle transitions emit
    /// audit events. Typically wraps an
    /// [`IdentityStore`](crate::authn::store::IdentityStore) via
    /// [`IdentityStoreEventSink`](super::events::IdentityStoreEventSink).
    pub fn with_event_sink<E: DeviceEventSink>(mut self, sink: E) -> Self {
        self.event_sink = Arc::new(sink);
        self
    }

    /// Borrow the underlying store. Use sparingly: bypasses the
    /// lifecycle invariants this service exists to enforce.
    pub fn store(&self) -> &S {
        &self.store
    }

    /// Look up a device by `fingerprint` within `tenant`. If present,
    /// bump `last_seen_at = now` (skipped when the device was seen within
    /// the [sighting granularity](Self::with_sighting_granularity)) and
    /// return its `device_id`. If absent,
    /// create a new row at [`DeviceTrustLevel::Unknown`] using
    /// `new_id_fn()` for the device_id and return it.
    ///
    /// When `user` is `Some`, only a device that user owns (or one with
    /// no owner) is reused. A device owned by someone else is skipped:
    /// the caller's own device with that fingerprint is returned if it
    /// has one, otherwise a new `Unknown` device is created. Two people
    /// behind one office or VPN address with the same browser therefore
    /// never share a device or its trust. When `user` is `None` the
    /// owner cannot be compared, so the fingerprint's device is returned
    /// as is; compare the owner with the authenticating user before
    /// trusting it (see [`decide_step_up_for_user`](crate::authn::service::decide_step_up_for_user)).
    ///
    /// `user` is `None` for guest sessions (pre-authn requests). The
    /// `user_id` field on the created Device row is set to whatever
    /// is passed in. A device that exists without an owner (it was made
    /// during a guest request) is claimed by the first authenticated user
    /// that resolves it, through [`DeviceStore::claim_owner`], so it cannot
    /// be reused by a later user; a user who loses that race gets a device
    /// of their own.
    ///
    /// `new_id_fn` is the application's choice of identifier scheme: a
    /// UUID v4 built from an injected [`SecureRng`](axess_rng::SecureRng)
    /// (a seeded one under test) is the canonical shape. Only called on
    /// the create path.
    pub fn ensure_device(
        &self,
        tenant: &TenantId,
        user: Option<&UserId>,
        fingerprint: FingerprintHash,
        now: DateTime<Utc>,
        new_id_fn: impl FnOnce() -> DeviceId + Send,
    ) -> impl Future<Output = Result<DeviceId, S::Error>> + Send {
        let tenant = *tenant;
        let user = user.cloned();
        async move {
            // Fast path: device already known by this fingerprint. A
            // device owned by a different user is not reused: a shared
            // office, NAT or VPN gives two people the same fingerprint,
            // and the second must not inherit the first one's trust.
            if let Some(existing) = self
                .store
                .find_by_fingerprint(&tenant, &fingerprint)
                .await?
            {
                if is_usable_by(&existing, user.as_ref()) {
                    // An unowned device (made during a guest request) is
                    // claimed by the first authenticated user to reach it,
                    // as one conditional write; otherwise any later user
                    // could resolve it. A user who loses the race to
                    // another falls through and gets a device of their own.
                    let usable = match (existing.user_id.as_ref(), user.as_ref()) {
                        (None, Some(user)) => matches!(
                            self.store
                                .claim_owner(&tenant, &existing.id, user, now)
                                .await?,
                            OwnerClaim::Claimed
                        ),
                        _ => true,
                    };
                    if usable {
                        self.note_sighting(&tenant, &existing, now).await?;
                        return Ok(existing.id);
                    }
                }
                // The lookup by fingerprint returns one row, which may be
                // another user's. Look for the caller's own device with
                // that fingerprint before minting a new one, so a repeat
                // visit finds the same device again however many devices
                // the user has.
                if let Some(user) = user.as_ref() {
                    let own = self
                        .store
                        .find_by_fingerprint_for_user(&tenant, user, &fingerprint)
                        .await?;
                    if let Some(own) = own {
                        self.note_sighting(&tenant, &own, now).await?;
                        return Ok(own.id);
                    }
                }
            }

            // Create path: brand-new device at Unknown.
            let id = new_id_fn();
            let device = Device {
                id,
                tenant_id: tenant,
                user_id: user,
                trust_level: DeviceTrustLevel::Unknown,
                fingerprint_hash: fingerprint,
                first_seen_at: now,
                last_seen_at: now,
                revoked_at: None,
                demoted_at: None,
                bindings: Vec::new(),
            };
            self.store.save(&device, now).await?;

            // Emit `DeviceFirstSeen` after the row commit so a
            // sink failure can never fail the device creation. The
            // sink's own failure handling logs and swallows, so the
            // outer caller never observes audit-pipeline blips.
            let event = AuthEventBuilder::success(AuthEventType::DeviceFirstSeen)
                .maybe_attributed_to(user.as_ref(), Some(&tenant))
                .with_device(id)
                .build_at(now);
            self.event_sink.emit(event).await;

            Ok(id)
        }
    }

    /// Record a sighting of `device` unless it was seen within the
    /// sighting granularity of `now`.
    async fn note_sighting(
        &self,
        tenant: &TenantId,
        device: &Device,
        now: DateTime<Utc>,
    ) -> Result<(), S::Error> {
        if now.signed_duration_since(device.last_seen_at) < self.sighting_granularity
            && now >= device.last_seen_at
        {
            return Ok(());
        }
        self.store.record_sighting(tenant, &device.id, now).await
    }

    /// Promote a device's trust level after a successful
    /// authentication ceremony.
    ///
    /// State machine:
    ///
    /// | Current | After `promote_on_authn` |
    /// |---------|--------------------------|
    /// | `Unknown` | `Seen` (recorded with `record_sighting(now)`) |
    /// | `Seen` | `Seen` (no-op; `last_seen_at` bumped) |
    /// | `Trusted` | `Trusted` (no-op; `last_seen_at` bumped) |
    /// | `Revoked` | `Revoked` (no-op; `last_seen_at` **not** bumped) |
    ///
    /// **Never re-elevates a `Revoked` device.** Revocation is a
    /// terminal state until an admin / user explicitly resurrects the
    /// device via [`DeviceStore::set_trust_level`]; passing through
    /// `promote_on_authn` after a successful login on a revoked
    /// device must not silently undo the revocation. (The application
    /// should reject the login earlier in such cases; this is
    /// defence-in-depth.)
    ///
    /// **Never demotes a `Trusted` device.** A Trusted device that
    /// authenticates again stays Trusted. This is the standard "user
    /// elevated device once via explicit consent; subsequent logins
    /// don't downgrade trust" semantic.
    ///
    /// Returns the trust level the device is in after the call.
    /// `Ok(Some(DeviceTrustLevel::Revoked))` is the "not promoted because
    /// revoked" outcome, whether the device was already revoked when it was
    /// loaded or was revoked between the load and the promotion; the
    /// promotion is a conditional write ([`DeviceStore::set_trust_level_if`])
    /// so the revocation is never overwritten. `Ok(None)` if the `device_id` doesn't resolve: defensive,
    /// callers shouldn't see this if they pass an id from
    /// [`Self::ensure_device`].
    pub fn promote_on_authn(
        &self,
        tenant: &TenantId,
        device_id: &DeviceId,
        now: DateTime<Utc>,
    ) -> impl Future<Output = Result<Option<DeviceTrustLevel>, S::Error>> + Send {
        let tenant = *tenant;
        let device_id = *device_id;
        async move {
            let device = match self.store.load(&tenant, &device_id).await? {
                Some(d) => d,
                None => return Ok(None),
            };

            match device.trust_level {
                DeviceTrustLevel::Unknown => {
                    // One conditional write: the device becomes Seen only
                    // if it is still Unknown, so a revocation that landed
                    // after the load above is not overwritten.
                    match self
                        .store
                        .set_trust_level_if(
                            &tenant,
                            &device_id,
                            DeviceTrustLevel::Unknown,
                            DeviceTrustLevel::Seen,
                            now,
                        )
                        .await?
                    {
                        TrustTransition::Applied => {
                            self.store.record_sighting(&tenant, &device_id, now).await?;
                            Ok(Some(DeviceTrustLevel::Seen))
                        }
                        // Revoked in between: not promoted, and reported as
                        // Revoked, never as Seen.
                        TrustTransition::Refused {
                            current: DeviceTrustLevel::Revoked,
                        } => Ok(Some(DeviceTrustLevel::Revoked)),
                        // Another request promoted it first.
                        TrustTransition::Refused { current } => {
                            self.store.record_sighting(&tenant, &device_id, now).await?;
                            Ok(Some(current))
                        }
                        TrustTransition::Missing => Ok(None),
                    }
                }
                DeviceTrustLevel::Seen | DeviceTrustLevel::Trusted => {
                    self.store.record_sighting(&tenant, &device_id, now).await?;
                    Ok(Some(device.trust_level))
                }
                DeviceTrustLevel::Revoked => {
                    // Terminal; no last_seen bump, no trust change.
                    Ok(Some(DeviceTrustLevel::Revoked))
                }
            }
        }
    }

    /// Convenience composition for the AuthnService glue pattern:
    /// fire [`Self::promote_on_authn`] iff the [`FactorOutcome`]
    /// indicates the user just completed authentication. No-op on
    /// `FactorRequired` / `InvalidCredential` / `Locked`.
    ///
    /// Usage:
    ///
    /// ```text
    /// let outcome = authn.complete_factor_step(...).await?;
    /// let _ = device_lifecycle
    ///     .promote_if_authenticated(&outcome, &tenant, &device_id, now)
    ///     .await?;
    /// ```
    ///
    /// Returns the same `Option<DeviceTrustLevel>` as
    /// [`Self::promote_on_authn`] when the outcome was
    /// `Authenticated`; `Ok(None)` otherwise (including the absent-
    /// device-id case, mirroring `promote_on_authn` semantics).
    pub fn promote_if_authenticated(
        &self,
        outcome: &FactorOutcome,
        tenant: &TenantId,
        device_id: &DeviceId,
        now: DateTime<Utc>,
    ) -> impl Future<Output = Result<Option<DeviceTrustLevel>, S::Error>> + Send {
        let is_authenticated = matches!(outcome, FactorOutcome::Authenticated);
        let tenant = *tenant;
        let device_id = *device_id;
        async move {
            if is_authenticated {
                self.promote_on_authn(&tenant, &device_id, now).await
            } else {
                Ok(None)
            }
        }
    }

    // ── WebAuthn binding ────────────────────────────────────────────

    /// Record a `DeviceBinding::WebAuthn` on a device after a successful
    /// FIDO2 registration ceremony.
    ///
    /// If the device already carries a `WebAuthn` binding for the same
    /// `credential_id`, this is a no-op (idempotent). Otherwise the new
    /// binding is appended and a [`AuthEventType::DeviceBindingAdded`]
    /// audit event is emitted.
    ///
    /// Returns `Ok(true)` when a new binding was added and `Ok(false)` when
    /// nothing was added: the credential was already bound, the device does
    /// not exist, or the device is `Revoked` (a revoked device never gains a
    /// binding, including when it was revoked while this call ran).
    #[cfg(feature = "fido2")]
    pub fn bind_webauthn_credential(
        &self,
        tenant: &TenantId,
        device_id: &DeviceId,
        credential_id: String,
        attestation_class: crate::device::types::AttestationClass,
        now: DateTime<Utc>,
    ) -> impl Future<Output = Result<bool, S::Error>> + Send {
        let tenant = *tenant;
        let device_id = *device_id;
        let event_sink = self.event_sink.clone();
        async move {
            let mut attempts = 0;
            let device = loop {
                let mut device = match self.store.load(&tenant, &device_id).await? {
                    Some(d) => d,
                    None => return Ok(false),
                };

                // A revoked device gains no bindings.
                if device.trust_level == DeviceTrustLevel::Revoked {
                    return Ok(false);
                }

                // Dedup: don't add a second binding for the same credential.
                let already_bound = device.bindings.iter().any(|b| {
                    matches!(
                        b,
                        crate::device::types::DeviceBinding::WebAuthn {
                            credential_id: cid, ..
                        } if cid == &credential_id
                    )
                });
                if already_bound {
                    return Ok(false);
                }

                let before = device.bindings.clone();
                device
                    .bindings
                    .push(crate::device::types::DeviceBinding::WebAuthn {
                        credential_id: credential_id.clone(),
                        attestation_class,
                        bound_at: now,
                        last_used_at: now,
                    });
                // Bindings-only compare-and-swap that refuses a revoked row:
                // a revocation made since the load is neither undone nor
                // given a new binding, and a concurrent bindings edit makes
                // this conflict, so the row is re-read and the change
                // decided again instead of one edit overwriting the other.
                match self
                    .store
                    .replace_bindings(&tenant, &device_id, &before, &device.bindings, now)
                    .await?
                {
                    BindingsUpdate::Written => break device,
                    BindingsUpdate::Conflict if attempts < BINDINGS_RETRIES => attempts += 1,
                    BindingsUpdate::Conflict => {
                        tracing::warn!(
                            "device bindings kept changing under concurrent writers; \
                             WebAuthn binding not recorded"
                        );
                        return Ok(false);
                    }
                    BindingsUpdate::Revoked | BindingsUpdate::Missing => return Ok(false),
                }
            };

            // Emit `DeviceBindingAdded` after the write so the
            // binding is persisted even if the sink fails.
            let event = AuthEventBuilder::success(AuthEventType::DeviceBindingAdded)
                .maybe_attributed_to(device.user_id.as_ref(), Some(&tenant))
                .with_device(device_id)
                .build_at(now);
            event_sink.emit(event).await;

            Ok(true)
        }
    }

    /// Update the `last_used_at` timestamp on an existing
    /// `DeviceBinding::WebAuthn` after a successful FIDO2 assertion.
    ///
    /// No-op if the device doesn't exist, is `Revoked`, or has no `WebAuthn`
    /// binding matching `credential_id`. A concurrent bindings edit makes the
    /// write conflict; the row is then re-read and the update applied to what
    /// is stored now.
    #[cfg(feature = "fido2")]
    pub fn record_webauthn_usage(
        &self,
        tenant: &TenantId,
        device_id: &DeviceId,
        credential_id: &str,
        now: DateTime<Utc>,
    ) -> impl Future<Output = Result<(), S::Error>> + Send {
        let tenant = *tenant;
        let device_id = *device_id;
        let credential_id = credential_id.to_owned();
        async move {
            for _ in 0..=BINDINGS_RETRIES {
                let device = match self.store.load(&tenant, &device_id).await? {
                    Some(d) => d,
                    None => return Ok(()),
                };

                let mut bindings = device.bindings.clone();
                let mut touched = false;
                for binding in &mut bindings {
                    if let crate::device::types::DeviceBinding::WebAuthn {
                        credential_id: cid,
                        last_used_at,
                        ..
                    } = binding
                        && cid == &credential_id
                    {
                        *last_used_at = now;
                        touched = true;
                        break;
                    }
                }
                if !touched {
                    return Ok(());
                }
                // Bindings-only; a revoked device is left as it is.
                match self
                    .store
                    .replace_bindings(&tenant, &device_id, &device.bindings, &bindings, now)
                    .await?
                {
                    BindingsUpdate::Conflict => continue,
                    _ => return Ok(()),
                }
            }
            tracing::warn!(
                "device bindings kept changing under concurrent writers; \
                 WebAuthn last-used time not recorded"
            );
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests;

#[cfg(test)]
mod ownership;

#[cfg(test)]
mod sighting;

#[cfg(test)]
mod races;