axess-core 0.10.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
//! [`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.
//! 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. axess will
//!   eventually ship a default extractor (separate iteration); the
//!   lifecycle layer is fingerprint-agnostic.
//! - **Wire itself into middleware.** The decision of *where* in the
//!   request pipeline `ensure_device` runs (session middleware,
//!   authn service, application-specific layer) is left to the
//!   consumer. This keeps the helper testable in isolation and lets
//!   apps make the cost trade-offs.
//! - **Refresh-cascade revocation.** When a refresh-token family is
//!   revoked, every `Device` bound to that family must transition to
//!   `Revoked`. That requires `DeviceBinding` to track refresh-family
//!   identifiers, which it does not yet. Tracked separately.

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};
use crate::device::store::DeviceStore;
use crate::device::types::{Device, DeviceTrustLevel, FingerprintHash};

/// How many of a user's own devices `ensure_device` scans for a matching
/// fingerprint when the fingerprint lookup returned someone else's.
const OWN_DEVICE_SCAN_LIMIT: usize = 100;

/// `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>,
}

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),
        }
    }

    /// 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` 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; updates that arrive later (e.g. when authn
    /// completes for a previously-guest device) need to call
    /// [`DeviceStore::save`] directly via [`Self::store`]; this
    /// helper deliberately doesn't touch user_id on the existing-
    /// device path to keep the create-vs-find branches symmetric.
    ///
    /// `new_id_fn` is the application's choice of identifier scheme.
    /// Pass `|| DeviceId::try_new(Uuid::new_v4().to_string()).unwrap()`
    /// for the canonical UUID-v4 shape, or a deterministic generator
    /// driven by `MockRng` for tests.
    /// 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()) {
                    self.store
                        .record_sighting(&tenant, &existing.id, now)
                        .await?;
                    return Ok(existing.id);
                }
                // The lookup by fingerprint returns one row, which may be
                // another user's. Look through the caller's own devices
                // before minting a new one, so a repeat visit finds the
                // same device again.
                if let Some(user) = user.as_ref() {
                    let own = self
                        .store
                        .find_for_user(&tenant, user, OWN_DEVICE_SCAN_LIMIT)
                        .await?
                        .into_iter()
                        .find(|d| d.fingerprint_hash == fingerprint);
                    if let Some(own) = own {
                        self.store.record_sighting(&tenant, &own.id, 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,
                bindings: Vec::new(),
            };
            self.store.save(&device).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();
            self.event_sink.emit(event).await;

            Ok(id)
        }
    }

    /// 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(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 => {
                    self.store
                        .set_trust_level(&tenant, &device_id, DeviceTrustLevel::Seen, now)
                        .await?;
                    self.store.record_sighting(&tenant, &device_id, now).await?;
                    Ok(Some(DeviceTrustLevel::Seen))
                }
                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, `Ok(false)` when
    /// deduplicated, `Ok(None)`-shaped `Err` when the device doesn't exist.
    #[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 device = match self.store.load(&tenant, &device_id).await? {
                Some(d) => d,
                None => 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);
            }

            device
                .bindings
                .push(crate::device::types::DeviceBinding::WebAuthn {
                    credential_id: credential_id.clone(),
                    attestation_class,
                    bound_at: now,
                    last_used_at: now,
                });
            self.store.save(&device).await?;

            // Emit `DeviceBindingAdded` after the save 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();
            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 or has no `WebAuthn` binding
    /// matching `credential_id`.
    #[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 {
            let mut device = match self.store.load(&tenant, &device_id).await? {
                Some(d) => d,
                None => return Ok(()),
            };

            let mut touched = false;
            for binding in &mut device.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 {
                self.store.save(&device).await?;
            }
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests;

#[cfg(test)]
mod ownership;