axess-core 0.8.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
//! Tower middleware layer providing HMAC-signed session cookies and typed session data.
//!
//! # Cookie format
//!
//! `<session_id_base64url>.<hmac_base64url>`
//!
//! The HMAC-SHA256 is computed over the raw 16 bytes of the session UUID.
//! The cookie contains *only* the session ID; session data lives in the store.
//!
//! # Request lifecycle
//!
//! 1. Extract and verify the session cookie (HMAC check with constant-time comparison).
//! 2. Load [`crate::session::SessionData`] from the store (or create an empty default).
//! 3. Insert `SessionHandle` into request extensions.
//! 4. Call the inner service.
//! 5. If the session was modified, save it back to the store (or cycle the ID first).
//! 6. Set the session cookie on the response.

mod handle;
mod lifecycle;
mod service;
mod signing;

pub(crate) use handle::SessionHandle;
// `SessionInner` is `pub(crate)` only so test modules and the
// `testing::*` fixture helpers can construct sessions directly.
// Production callers go through `SessionHandle`, so gate the
// re-export to avoid an unused-import warning in plain prod builds.
#[cfg(any(test, feature = "testing"))]
pub(crate) use handle::SessionInner;
pub use service::SessionService;

#[cfg(feature = "device")]
use crate::device::resolver::{DeviceResolver, ErasedDeviceResolver};
use crate::session::binding::SessionBinding;
use crate::session::config::SessionConfig;
use crate::session::store::SessionStore;
use signing::SigningKeyRing;
use std::{sync::Arc, time::Duration};
use tower_cookies::cookie::SameSite;

/// Tower layer that provides signed session cookies and typed [`crate::session::SessionData`].
///
/// Add this layer to your Axum router. Handlers receive an [`super::extractor::AuthSession`] extractor
/// which wraps the `SessionHandle` stored in request extensions.
///
/// ```text
/// let app = Router::new()
///     .route("/login", post(login_handler))
///     .layer(SessionLayer::new(store, signing_key));
/// ```
///
/// # Configuration
///
/// Cookie attributes and TTL are set via the `with_*` builder methods:
///
/// ```text
/// let layer = SessionLayer::new(store, key)
///     .with_ttl(Duration::from_secs(7200))
///     .with_secure(false)
///     .with_same_site(SameSite::Strict);
/// ```
#[derive(Clone)]
pub struct SessionLayer<S> {
    pub(super) store: S,
    pub(super) signing_keys: Arc<SigningKeyRing>,
    /// Shared via `Arc` so the `Layer::layer` clone (per inner
    /// service) and the per-request `Service::call` clone are both
    /// pointer copies, not full struct copies. `SessionConfig` carries
    /// several `Arc<str>` fields plus a number of small enums; cloning
    /// the whole thing on every request added measurable overhead on
    /// the middleware hot path.
    pub(super) config: Arc<SessionConfig>,
    pub(super) binding: Option<Arc<dyn SessionBinding>>,
    pub(super) metrics: Option<Arc<dyn crate::metrics::AuthnMetrics>>,
    /// Optional device resolver invoked once per request between
    /// session-data load and the inner handler. Stamps
    /// [`SessionData::device_id`](crate::session::SessionData::device_id)
    /// when the resolver returns `Some`.
    #[cfg(feature = "device")]
    pub(super) device_resolver: Option<Arc<dyn ErasedDeviceResolver>>,
}

impl<S: SessionStore> SessionLayer<S> {
    /// Create a session layer with the given store and 32-byte HMAC signing key.
    ///
    /// Uses [`SessionConfig::default()`]: production-safe defaults (24-hour TTL,
    /// `Secure`, `HttpOnly`, `SameSite=Lax`).
    ///
    /// The signing key derives sub-keys via HKDF for cookie HMAC,
    /// fingerprint HMAC, and CSRF; keep it in a secret store and rotate
    /// per your key-management policy (a fresh layer is required on
    /// rotation since the derived keys are cached).
    ///
    /// # Example
    ///
    /// ```no_run
    /// use axess_core::{MemorySessionStore, session::SessionLayer};
    /// use std::time::Duration;
    ///
    /// // Production: load the master key from a secret store (KMS, Vault, …).
    /// // Below uses a fixed value purely for the construction example.
    /// let signing_key: [u8; 32] = [0u8; 32];
    /// let store = MemorySessionStore::default();
    ///
    /// let layer = SessionLayer::new(store, signing_key)
    ///     .with_ttl(Duration::from_secs(3600))
    ///     .with_cookie_name("myapp.sid");
    ///
    /// // Attach to your router:
    /// //     let app = axum::Router::new().layer(layer);
    /// # let _ = layer;
    /// ```
    pub fn new(store: S, signing_key: [u8; 32]) -> Self {
        Self {
            store,
            // Derive distinct cookie / fingerprint HMAC sub-keys
            // from the master so a side-channel on one path cannot be
            // replayed against the other. Rotation slot starts empty;
            // adopters opt in via
            // [`with_previous_signing_key`](Self::with_previous_signing_key).
            signing_keys: Arc::new(SigningKeyRing::from_master(signing_key)),
            config: Arc::new(SessionConfig::default()),
            binding: None,
            metrics: None,
            #[cfg(feature = "device")]
            device_resolver: None,
        }
    }

    /// Configure a previous signing master key for zero-downtime
    /// rotation.
    ///
    /// On every request, cookie and fingerprint verification tries the
    /// CURRENT key first; on mismatch, falls back to this PREVIOUS key.
    /// When the previous key produces the match, the response re-issues
    /// the cookie under the current key and (for fingerprint fallback)
    /// updates the stored fingerprint in the session data so subsequent
    /// requests hit the fast path without falling back.
    ///
    /// Mirrors [`SessionCrypto::with_previous_key`](crate::session::SessionCrypto::with_previous_key)
    /// for the at-rest encryption side. The two rotations are
    /// independent: rotate the signing key without touching encryption,
    /// or vice versa, or plan both to overlap.
    ///
    /// # Operational rule
    ///
    /// **Only one previous slot is maintained.** Plan rotations so at
    /// most one is in flight per session-TTL window. A chained rotation
    /// (rotate again while the previous slot is still populated) drops
    /// the pre-first-rotation key entirely; cookies signed under it
    /// then fail both current and previous verification and their
    /// holders are forced to re-authenticate. This is the correct
    /// security behavior for an emergency-rotate-again scenario
    /// (compromised previous key must not remain valid): see
    /// `OPERATIONS.md#signing-key-rotation`.
    pub fn with_previous_signing_key(mut self, previous_master: [u8; 32]) -> Self {
        // Same "mutate before cloning" contract as `config_mut`. When
        // the Arc has been shared, `Arc::make_mut` deep-copies the
        // ring (key material included) into a fresh Arc and mutates
        // that; the previously-cloned service keeps the un-rotated
        // ring: usually not what the caller intended, and it also
        // means the master key bytes exist in two places briefly.
        // The debug_assert catches this in dev; release builds allow
        // it (matches SessionConfig setter behavior).
        debug_assert!(
            Arc::strong_count(&self.signing_keys) == 1,
            "SessionLayer::with_previous_signing_key called after the layer was cloned \
             (strong_count = {}). The rotation slot will only affect this clone; the \
             previously-cloned service keeps its original ring. Configure the layer fully \
             before passing it to `tower::Layer` / `Router::layer`.",
            Arc::strong_count(&self.signing_keys),
        );
        Arc::make_mut(&mut self.signing_keys).set_previous(previous_master);
        self
    }

    /// `true` when a previous signing key is configured, i.e. the
    /// layer is currently in a signing-key rotation window. Adopters
    /// building admin / status endpoints can use this to surface
    /// "rotation in progress" state without inspecting the master
    /// directly.
    pub fn has_previous_signing_key(&self) -> bool {
        self.signing_keys.has_previous()
    }

    /// Clear the previous signing key, ending the rotation window.
    ///
    /// Companion to [`with_previous_signing_key`](Self::with_previous_signing_key):
    /// after one session TTL has elapsed since the rotation began, no
    /// unexpired cookie can still be signed under the previous master,
    /// so retiring the slot is safe and prevents the previous key
    /// material from being validated against indefinitely. See
    /// `OPERATIONS.md#signing-key-rotation` for the procedure.
    ///
    /// Same "mutate before cloning" contract as
    /// [`with_previous_signing_key`](Self::with_previous_signing_key):
    /// invoke on the freshly-built layer, before it is handed to
    /// `tower::Layer` / `Router::layer`; a debug build asserts on the
    /// footgun. Calling this when no previous key is set is a no-op.
    pub fn remove_previous_signing_key(mut self) -> Self {
        debug_assert!(
            Arc::strong_count(&self.signing_keys) == 1,
            "SessionLayer::remove_previous_signing_key called after the layer was cloned \
             (strong_count = {}). The rotation slot will only clear on this clone; the \
             previously-cloned service keeps its previous key. Configure the layer fully \
             before passing it to `tower::Layer` / `Router::layer`.",
            Arc::strong_count(&self.signing_keys),
        );
        Arc::make_mut(&mut self.signing_keys).clear_previous();
        self
    }

    /// Borrow the per-request `SessionConfig`. Mutating
    /// setters take a fresh copy via `Arc::make_mut`, so production
    /// builds that only mutate during the construction phase share a
    /// single `Arc` across every cloned service.
    ///
    /// # Footgun
    ///
    /// **Mutate before cloning.** If you call `.clone()` on the layer
    /// (or pass it through `tower::Layer`) and *then* invoke a `with_*`
    /// setter, `Arc::make_mut` deep-copies the `SessionConfig` so your
    /// edit only affects the new clone; the previously-cloned service
    /// still holds the original. Always finish configuration before
    /// the layer enters the router. Debug builds catch the surprising
    /// case below.
    fn config_mut(&mut self) -> &mut SessionConfig {
        debug_assert!(
            Arc::strong_count(&self.config) == 1,
            "SessionLayer setter called after the layer was cloned (strong_count = {}). \
             The mutation will deep-copy SessionConfig and only affect this clone. Configure \
             the layer fully before passing it to `tower::Layer` / `Router::layer`.",
            Arc::strong_count(&self.config),
        );
        Arc::make_mut(&mut self.config)
    }

    /// Derive a 32-byte sub-key from this layer's master signing
    /// key using a caller-supplied `info` label. Use this to feed
    /// CSRF token signing, push-notification HMAC, or any other HMAC
    /// site that would otherwise be tempted to reuse the raw master
    /// key. Pick a stable byte-string label per use site (e.g.
    /// `b"my-app.v1.csrf"`); changing the label invalidates every
    /// value previously derived under it.
    ///
    /// The returned bytes are wrapped in [`zeroize::Zeroizing`] so they
    /// are wiped on drop: a compromise of any derived sub-key with a
    /// known label lets an attacker forge against that path, so the
    /// material is held under the same drop discipline as the master
    /// key. Deref through `*` or `as_ref()` to access the raw `[u8; 32]`.
    pub fn derive_subkey(&self, info: &'static [u8]) -> zeroize::Zeroizing<[u8; 32]> {
        // Derives from the CURRENT master only. Adopters using
        // `derive_subkey` to feed their own HMAC sites (CSRF, push
        // tokens, etc.) do NOT get rotation-aware verify-with-fallback
        // for free; if they need it, they hold their own previous key
        // and try-current-then-previous themselves. Wiring rotation
        // into every downstream sub-key derivation would leak the
        // rotation state through an otherwise-simple API.
        zeroize::Zeroizing::new(self.signing_keys.derive_subkey(info))
    }

    /// Override the session TTL (default: 24 hours).
    pub fn with_ttl(mut self, ttl: Duration) -> Self {
        self.config_mut().ttl = ttl;
        self
    }

    /// Override the cookie name (default: `"axess.sid"`).
    pub fn with_cookie_name(mut self, name: impl Into<Arc<str>>) -> Self {
        self.config_mut().cookie_name = name.into();
        self
    }

    /// Set the `Secure` flag on the session cookie (default: `true`).
    ///
    /// Set to `false` only for local HTTP development. In production,
    /// cookies without the `Secure` flag can be intercepted on the network.
    pub fn with_secure(mut self, secure: bool) -> Self {
        if !secure {
            tracing::warn!(
                "SessionLayer: Secure cookie flag disabled; session cookies \
                 will be sent over plain HTTP. Do not use in production."
            );
        }
        self.config_mut().secure = secure;
        self
    }

    /// Set the `SameSite` policy (default: `Lax`).
    pub fn with_same_site(mut self, same_site: SameSite) -> Self {
        self.config_mut().same_site = same_site;
        self
    }

    /// Set the `HttpOnly` flag on the session cookie (default: `true`).
    pub fn with_http_only(mut self, http_only: bool) -> Self {
        self.config_mut().http_only = http_only;
        self
    }

    /// Override the maximum size (in bytes) of the JSON-encoded
    /// custom-data payload. Default: 64 KiB. Set to `0` to disable
    /// the clamp entirely (do this only if you have your own size
    /// guarding upstream of the session layer).
    ///
    /// When the clamp fires, the offending custom payload is
    /// dropped to `Value::Null` and a `tracing::warn!` is emitted;
    /// the session itself is preserved.
    pub fn with_max_custom_bytes(mut self, max: usize) -> Self {
        self.config_mut().max_custom_bytes = max;
        self
    }

    /// Set the cookie `Path` attribute (default: `"/"`).
    pub fn with_path(mut self, path: impl Into<Arc<str>>) -> Self {
        self.config_mut().path = path.into();
        self
    }

    /// Enable session-to-client binding for hijacking detection.
    ///
    /// When enabled, the library hashes client-specific request properties
    /// (determined by the [`SessionBinding`] implementation) and stores the
    /// hash in the session upon authentication. On every subsequent request
    /// the hash is recomputed and compared; a mismatch resets the session
    /// to `Guest` (the cookie may have been stolen by a different client).
    ///
    /// ```text
    /// use axess::session::UserAgentBinding;
    ///
    /// let layer = SessionLayer::new(store, key)
    ///     .with_binding(UserAgentBinding);
    /// ```
    pub fn with_binding(mut self, binding: impl SessionBinding) -> Self {
        self.binding = Some(Arc::new(binding));
        self
    }

    /// Attach a metrics hook for session-level observability.
    pub fn with_metrics(mut self, metrics: impl crate::metrics::AuthnMetrics) -> Self {
        self.metrics = Some(Arc::new(metrics));
        self
    }

    /// Configure a [`DeviceResolver`] to stamp
    /// [`SessionData::device_id`](crate::session::SessionData::device_id)
    /// on every request before the inner handler runs.
    ///
    /// Errors returned by the resolver are logged via `tracing::warn!`
    /// and treated as `None`; device resolution never fails the request.
    /// When unset (the default), `device_id` stays at whatever the loaded
    /// session carried, which for new sessions is `None`.
    ///
    /// See [`docs/identity/device.md`](https://github.com/GnomesOfZurich/axess/blob/main/docs/identity/device.md)
    /// for the full design.
    #[cfg(feature = "device")]
    pub fn with_device_resolver<R>(mut self, resolver: R) -> Self
    where
        R: DeviceResolver,
    {
        self.device_resolver = Some(Arc::new(resolver));
        self
    }
}

// Regression: confirm the `config_mut` debug_assert
// actually fires when a `SessionLayer` is cloned and *then* mutated.
// The Arc<SessionConfig> deep-copy in `Arc::make_mut` would otherwise
// silently divorce the two layers' configs. The assertion is a debug-only
// guard so the test is gated behind `debug_assertions`.
#[cfg(all(test, debug_assertions))]
mod make_mut_tests {
    use super::*;
    use crate::session::store::MemorySessionStore;

    #[test]
    #[should_panic(expected = "SessionLayer setter called after the layer was cloned")]
    fn setter_after_clone_panics_in_debug() {
        let store = MemorySessionStore::new();
        let layer = SessionLayer::new(store, [0u8; 32]);
        let cloned = layer.clone();
        // Cloning bumps the Arc strong count to 2; the next `with_ttl`
        // will trip the assertion before `Arc::make_mut` deep-copies.
        layer.with_ttl(Duration::from_secs(60));
        drop(cloned);
    }

    #[test]
    fn setter_before_clone_does_not_panic() {
        let store = MemorySessionStore::new();
        let layer = SessionLayer::new(store, [0u8; 32])
            .with_ttl(Duration::from_secs(60))
            .with_secure(false);
        // Clone after setters is fine; the configuration is already finalised.
        drop(layer.clone());
    }
}

/// `with_secure(false)` MUST emit a tracing warning so an
/// operator running on plain HTTP cannot miss the implication
/// of disabling the cookie's `Secure` flag in production.
/// `with_secure(true)` MUST stay silent: a warning on the safe
/// configuration trains operators to ignore the channel.
///
/// Pins `delete !` on the `if !secure` guard in `with_secure`:
/// with the `!` removed the predicate inverts, the warning fires
/// for `secure=true` (every production deployment) and stays silent
/// for `secure=false` (the actually-dangerous configuration).
#[cfg(test)]
mod with_secure_warning_tests {
    use super::*;
    use crate::session::store::MemorySessionStore;
    use crate::testing::mock_tracing::TracingCapture;

    #[test]
    fn with_secure_false_emits_warning() {
        let capture = TracingCapture::install();
        let store = MemorySessionStore::new();
        drop(SessionLayer::new(store, [0u8; 32]).with_secure(false));
        assert!(
            capture.contains_at_level(tracing::Level::WARN, "Secure cookie flag disabled"),
            "with_secure(false) must warn about plain-HTTP cookies"
        );
    }

    #[test]
    fn with_secure_true_does_not_emit_warning() {
        let capture = TracingCapture::install();
        let store = MemorySessionStore::new();
        drop(SessionLayer::new(store, [0u8; 32]).with_secure(true));
        assert!(
            !capture.contains_at_level(tracing::Level::WARN, "Secure cookie flag disabled"),
            "with_secure(true) must NOT warn; `delete !` mutation would invert this"
        );
    }
}

/// Layer-level coverage for the signing-key rotation retire path.
///
/// `SigningKeyRing::clear_previous` is exercised at the ring level in
/// `session::layer::signing::rotation_tests::ring_clear_previous_ends_rotation_window`;
/// these tests pin the layer's `with_*` / `remove_*` orchestration
/// (the `Arc::make_mut` step + `has_previous_signing_key` predicate)
/// so an accidental short-circuit of the retire method surfaces here
/// instead of silently keeping the previous slot alive.
#[cfg(test)]
mod signing_key_retire_tests {
    use super::*;
    use crate::session::store::MemorySessionStore;

    #[test]
    fn remove_previous_signing_key_retires_the_slot() {
        let store = MemorySessionStore::new();
        let layer = SessionLayer::new(store, [0xBB; 32]).with_previous_signing_key([0xAA; 32]);
        assert!(
            layer.has_previous_signing_key(),
            "with_previous_signing_key must install a slot the predicate observes"
        );

        let after = layer.remove_previous_signing_key();
        assert!(
            !after.has_previous_signing_key(),
            "remove_previous_signing_key must retire the slot"
        );
    }

    /// Idempotency: calling the retire method on a layer that has no
    /// previous key must be a no-op, not a panic. Operators sometimes
    /// invoke the retire step unconditionally at startup after a
    /// scheduled rotation window; a panic would take down the process.
    #[test]
    fn remove_previous_signing_key_on_fresh_layer_is_noop() {
        let store = MemorySessionStore::new();
        let layer = SessionLayer::new(store, [0xBB; 32]);
        assert!(!layer.has_previous_signing_key());
        let after = layer.remove_previous_signing_key();
        assert!(!after.has_previous_signing_key());
    }
}