Skip to main content

auth_framework/storage/
core.rs

1//! Storage backends for authentication data.
2
3use crate::errors::Result;
4use crate::tokens::AuthToken;
5use async_trait::async_trait;
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use std::sync::{Arc, RwLock};
9use std::time::Duration;
10
11#[cfg(feature = "redis-storage")]
12use crate::errors::StorageError;
13
14/// Trait for authentication data storage backends.
15///
16/// All persistence in `AuthFramework` goes through this trait — tokens,
17/// sessions, and arbitrary key-value data.  Implement it to plug in a
18/// custom database while keeping the rest of the framework unchanged.
19///
20/// # Provided Implementations
21///
22/// | Backend | Type | Feature flag |
23/// |---------|------|-------------|
24/// | In-memory (DashMap) | [`MemoryStorage`] | *(always available)* |
25/// | PostgreSQL | [`PostgresStorage`](crate::storage::postgres::PostgresStorage) | `postgres-storage` |
26/// | Redis | [`RedisStorage`] | `redis-storage` |
27/// | SQLite | [`SqliteStorage`](crate::storage::sqlite::SqliteStorage) | `sqlite-storage` |
28/// | Encrypted wrapper | [`EncryptedStorage`](crate::storage::encryption::EncryptedStorage) | *(always available)* |
29///
30/// # Implementing This Trait
31///
32/// Custom storage backends must:
33///
34/// 1. **Be thread-safe** — the trait requires `Send + Sync`.
35/// 2. **Handle concurrent access** — multiple tasks will read/write
36///    simultaneously. Use connection pooling or interior mutability.
37/// 3. **Honour TTL** — [`store_kv`](Self::store_kv) accepts an optional TTL.
38///    Expired entries must not be returned by [`get_kv`](Self::get_kv).
39/// 4. **Override `list_kv_keys`** — the default returns an error.
40///    Analytics, compliance, and RBAC queries depend on real data.
41/// 5. **Implement `cleanup_expired`** — periodically called to prune stale
42///    tokens and sessions.
43///
44/// # Example (skeleton)
45///
46/// ```rust,no_run
47/// use auth_framework::storage::{AuthStorage, SessionData};
48/// use auth_framework::tokens::AuthToken;
49/// use auth_framework::errors::Result;
50/// use async_trait::async_trait;
51/// use std::time::Duration;
52///
53/// struct MyStorage { /* ... */ }
54///
55/// #[async_trait]
56/// impl AuthStorage for MyStorage {
57///     async fn store_token(&self, token: &AuthToken) -> Result<()> { todo!() }
58///     async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>> { todo!() }
59///     async fn get_token_by_access_token(&self, _: &str) -> Result<Option<AuthToken>> { todo!() }
60///     async fn update_token(&self, token: &AuthToken) -> Result<()> { todo!() }
61///     async fn delete_token(&self, token_id: &str) -> Result<()> { todo!() }
62///     async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> { todo!() }
63///     async fn store_session(&self, id: &str, data: &SessionData) -> Result<()> { todo!() }
64///     async fn get_session(&self, id: &str) -> Result<Option<SessionData>> { todo!() }
65///     async fn delete_session(&self, id: &str) -> Result<()> { todo!() }
66///     async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> { todo!() }
67///     async fn count_active_sessions(&self) -> Result<u64> { todo!() }
68///     async fn store_kv(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()> { todo!() }
69///     async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> { todo!() }
70///     async fn delete_kv(&self, key: &str) -> Result<()> { todo!() }
71///     async fn list_kv_keys(&self, prefix: &str) -> Result<Vec<String>> { todo!() }
72///     async fn cleanup_expired(&self) -> Result<()> { todo!() }
73/// }
74/// ```
75#[async_trait]
76pub trait AuthStorage: Send + Sync {
77    /// Bulk store tokens.
78    async fn store_tokens_bulk(&self, tokens: &[AuthToken]) -> Result<()> {
79        for token in tokens {
80            self.store_token(token).await?;
81        }
82        Ok(())
83    }
84
85    /// Bulk delete tokens by ID.
86    async fn delete_tokens_bulk(&self, token_ids: &[String]) -> Result<()> {
87        for token_id in token_ids {
88            self.delete_token(token_id).await?;
89        }
90        Ok(())
91    }
92
93    /// Bulk store sessions.
94    async fn store_sessions_bulk(&self, sessions: &[(String, SessionData)]) -> Result<()> {
95        for (session_id, data) in sessions {
96            self.store_session(session_id, data).await?;
97        }
98        Ok(())
99    }
100
101    /// Bulk delete sessions by ID.
102    async fn delete_sessions_bulk(&self, session_ids: &[String]) -> Result<()> {
103        for session_id in session_ids {
104            self.delete_session(session_id).await?;
105        }
106        Ok(())
107    }
108    /// Store a token.
109    async fn store_token(&self, token: &AuthToken) -> Result<()>;
110
111    /// Retrieve a token by ID.
112    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>>;
113
114    /// Retrieve a token by access token string.
115    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>>;
116
117    /// Update a token.
118    async fn update_token(&self, token: &AuthToken) -> Result<()>;
119
120    /// Delete a token.
121    async fn delete_token(&self, token_id: &str) -> Result<()>;
122
123    /// List all tokens for a user.
124    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>>;
125
126    /// Store session data.
127    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()>;
128
129    /// Retrieve session data.
130    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>>;
131
132    /// Delete session data.
133    async fn delete_session(&self, session_id: &str) -> Result<()>;
134
135    /// List all sessions for a user.
136    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>>;
137
138    /// Count currently active sessions (non-expired)
139    async fn count_active_sessions(&self) -> Result<u64>;
140
141    /// Store arbitrary key-value data with expiration.
142    async fn store_kv(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()>;
143
144    /// Store `value` under `key` only if no live entry exists. Returns whether it was stored.
145    ///
146    /// This is a compare-and-set: of several simultaneous callers exactly one gets `true`.
147    /// Single-use markers (refresh-token redemption, TOTP steps, WebAuthn sessions, PKCE codes)
148    /// depend on that, so a backend **must** implement it atomically; there is no default that
149    /// could be correct for every store (a `get_kv` followed by `store_kv` is not atomic).
150    /// The default therefore fails with an error, and the paths that need a claim fail with it
151    /// rather than run without the guarantee. The memory, SQLite (both crates), PostgreSQL,
152    /// Redis, unified and encrypted-wrapper backends and the test-only `MockStorage` implement it.
153    async fn store_kv_if_absent(
154        &self,
155        _key: &str,
156        _value: &[u8],
157        _ttl: Option<Duration>,
158    ) -> Result<bool> {
159        Err(crate::errors::AuthError::Storage(
160            crate::errors::StorageError::operation_failed(
161                "this storage backend does not implement store_kv_if_absent, which the \
162                 single-use claims (refresh-token redemption, TOTP steps, WebAuthn sessions, \
163                 PKCE codes) require to be atomic; implement it as a compare-and-set"
164                    .to_string(),
165            ),
166        ))
167    }
168
169    /// Remove keys and store another in ONE atomic step.
170    ///
171    /// Succeeds only if at least one of the `remove` keys is live AND `key` is absent: it then
172    /// deletes every key in `remove`, stores `value` under `key` (with `ttl`) and returns
173    /// `true`. Otherwise it changes nothing and returns `false`. Of several simultaneous swaps
174    /// of one key exactly one succeeds. Key rotation uses it so that an interrupted or racing
175    /// rotation leaves the old key or the new key, never both and never neither.
176    ///
177    /// "Atomic" is the backend's transaction: SQL backends do it in one transaction and Redis in
178    /// one script, so no reader sees a half-done swap. The in-process memory backends are atomic
179    /// with respect to other swaps (and to the claims made with
180    /// [`store_kv_if_absent`](Self::store_kv_if_absent)) but a concurrent reader can observe the
181    /// instant between the removal and the insert.
182    ///
183    /// A backend that implements it must also return `true` from
184    /// [`supports_atomic_swap`](Self::supports_atomic_swap). The default fails with an error;
185    /// callers that can do without check `supports_atomic_swap` first.
186    async fn swap_kv(
187        &self,
188        _remove: &[String],
189        _key: &str,
190        _value: &[u8],
191        _ttl: Option<Duration>,
192    ) -> Result<bool> {
193        Err(crate::errors::AuthError::Storage(
194            crate::errors::StorageError::operation_failed(
195                "this storage backend does not implement swap_kv".to_string(),
196            ),
197        ))
198    }
199
200    /// Whether [`swap_kv`](Self::swap_kv) is implemented (atomically). `false` by default.
201    fn supports_atomic_swap(&self) -> bool {
202        false
203    }
204
205    /// Retrieve arbitrary key-value data.
206    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>>;
207
208    /// Remaining time-to-live of a key-value entry.
209    ///
210    /// Returns `Ok(None)` when the key is absent, has no expiry, **or the
211    /// backend does not track TTLs** (the default). Callers that must carry
212    /// an entry's lifetime across a copy (backup/restore, migration) use
213    /// this together with [`get_kv`](Self::get_kv); a backend that honours
214    /// the TTL passed to [`store_kv`](Self::store_kv) should override it so
215    /// those entries do not silently become non-expiring. An entry that
216    /// `get_kv` would still return but that expires within the backend's
217    /// time resolution reports `Some(Duration::ZERO)`, never `None`.
218    async fn get_kv_ttl(&self, _key: &str) -> Result<Option<Duration>> {
219        Ok(None)
220    }
221
222    /// Whether [`get_kv_ttl`](Self::get_kv_ttl) reports the TTLs given to
223    /// [`store_kv`](Self::store_kv). `false` (the default) means a TTL is
224    /// invisible to callers, so anything that copies entries (migration,
225    /// backup/restore) cannot preserve expiry. A backend that overrides
226    /// [`get_kv_ttl`](Self::get_kv_ttl) must override this too (return
227    /// `true`), otherwise it is treated as TTL-blind.
228    fn tracks_kv_ttl(&self) -> bool {
229        false
230    }
231
232    /// Whether this storage encrypts KV values at rest itself (i.e. it is,
233    /// or wraps, an [`EncryptedStorage`](crate::storage::encryption::EncryptedStorage)).
234    /// `false` (the default) means values reach the backend as given. A
235    /// wrapper around an `EncryptedStorage` must forward this, or startup
236    /// will wrongly report its values as unencrypted.
237    fn encrypts_kv_at_rest(&self) -> bool {
238        false
239    }
240
241    /// Delete arbitrary key-value data.
242    async fn delete_kv(&self, key: &str) -> Result<()>;
243
244    /// List keys with a specific prefix.
245    ///
246    /// **Important:** every storage backend must override this method. The default
247    /// returns an error: an empty list would be indistinguishable from "no keys", and
248    /// analytics, compliance and RBAC queries would silently operate on no data.
249    /// Expired keys are not listed.
250    async fn list_kv_keys(&self, _prefix: &str) -> Result<Vec<String>> {
251        Err(crate::errors::AuthError::Storage(
252            crate::errors::StorageError::operation_failed(
253                "this storage backend does not implement list_kv_keys, which analytics, \
254                 compliance, RBAC and maintenance listing require; implement it to return \
255                 the unexpired KV keys that start with the prefix"
256                    .to_string(),
257            ),
258        ))
259    }
260
261    /// Clean up expired data.
262    async fn cleanup_expired(&self) -> Result<()>;
263}
264
265/// Lets a boxed `Arc<dyn AuthStorage>` coming out of the storage factory be
266/// wrapped in [`crate::storage::encryption::EncryptedStorage`] without
267/// downcasting to a concrete backend type first.
268///
269/// Deliberately scoped to the trait-object case only (`Arc<dyn
270/// AuthStorage>`), not a generic `impl<T: AuthStorage + ?Sized> AuthStorage
271/// for Arc<T>`: a generic impl would apply to every `Arc<ConcreteBackend>`
272/// too, and Rust's method resolution prefers an exact-type impl over
273/// autoderef -- so `some_arc.get_session(..)` would resolve to this impl's
274/// `(**self).get_session(..)` indirection instead of calling
275/// `ConcreteBackend::get_session` directly, adding an extra `async_trait`
276/// boxed-future hop to every storage call made through an `Arc<Concrete>`
277/// anywhere in the crate (including benchmarks and tests), not just the
278/// one factory path that actually needs this. Measured: this cost a real
279/// ~20-30% regression on the `session_operations/get_session` benchmark
280/// before being scoped down to `dyn AuthStorage` here.
281#[async_trait]
282impl AuthStorage for Arc<dyn AuthStorage> {
283    async fn store_tokens_bulk(&self, tokens: &[AuthToken]) -> Result<()> {
284        (**self).store_tokens_bulk(tokens).await
285    }
286
287    async fn delete_tokens_bulk(&self, token_ids: &[String]) -> Result<()> {
288        (**self).delete_tokens_bulk(token_ids).await
289    }
290
291    async fn store_sessions_bulk(&self, sessions: &[(String, SessionData)]) -> Result<()> {
292        (**self).store_sessions_bulk(sessions).await
293    }
294
295    async fn delete_sessions_bulk(&self, session_ids: &[String]) -> Result<()> {
296        (**self).delete_sessions_bulk(session_ids).await
297    }
298
299    async fn store_token(&self, token: &AuthToken) -> Result<()> {
300        (**self).store_token(token).await
301    }
302
303    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>> {
304        (**self).get_token(token_id).await
305    }
306
307    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>> {
308        (**self).get_token_by_access_token(access_token).await
309    }
310
311    async fn update_token(&self, token: &AuthToken) -> Result<()> {
312        (**self).update_token(token).await
313    }
314
315    async fn delete_token(&self, token_id: &str) -> Result<()> {
316        (**self).delete_token(token_id).await
317    }
318
319    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
320        (**self).list_user_tokens(user_id).await
321    }
322
323    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()> {
324        (**self).store_session(session_id, data).await
325    }
326
327    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
328        (**self).get_session(session_id).await
329    }
330
331    async fn delete_session(&self, session_id: &str) -> Result<()> {
332        (**self).delete_session(session_id).await
333    }
334
335    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> {
336        (**self).list_user_sessions(user_id).await
337    }
338
339    async fn count_active_sessions(&self) -> Result<u64> {
340        (**self).count_active_sessions().await
341    }
342
343    async fn store_kv(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()> {
344        (**self).store_kv(key, value, ttl).await
345    }
346
347    async fn store_kv_if_absent(
348        &self,
349        key: &str,
350        value: &[u8],
351        ttl: Option<Duration>,
352    ) -> Result<bool> {
353        (**self).store_kv_if_absent(key, value, ttl).await
354    }
355
356    async fn swap_kv(
357        &self,
358        remove: &[String],
359        key: &str,
360        value: &[u8],
361        ttl: Option<Duration>,
362    ) -> Result<bool> {
363        (**self).swap_kv(remove, key, value, ttl).await
364    }
365
366    fn supports_atomic_swap(&self) -> bool {
367        (**self).supports_atomic_swap()
368    }
369
370    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
371        (**self).get_kv(key).await
372    }
373
374    async fn get_kv_ttl(&self, key: &str) -> Result<Option<Duration>> {
375        (**self).get_kv_ttl(key).await
376    }
377
378    fn tracks_kv_ttl(&self) -> bool {
379        (**self).tracks_kv_ttl()
380    }
381
382    async fn delete_kv(&self, key: &str) -> Result<()> {
383        (**self).delete_kv(key).await
384    }
385
386    fn encrypts_kv_at_rest(&self) -> bool {
387        (**self).encrypts_kv_at_rest()
388    }
389
390    async fn list_kv_keys(&self, prefix: &str) -> Result<Vec<String>> {
391        (**self).list_kv_keys(prefix).await
392    }
393
394    async fn cleanup_expired(&self) -> Result<()> {
395        (**self).cleanup_expired().await
396    }
397}
398
399/// Session data stored in the backend.
400///
401/// All fields are public for serialization flexibility. When constructing
402/// a new session prefer [`SessionData::new`] which initialises timestamps
403/// consistently.
404///
405/// # Chainable construction
406///
407/// ```rust,ignore
408/// let session = SessionData::new("sess-1", "user-1", Duration::from_secs(3600))
409///     .ip_address("127.0.0.1")
410///     .user_agent("Mozilla/5.0")
411///     .with_data("role", json!("admin"));
412/// ```
413///
414/// The older [`SessionData::with_metadata`] helper sets both IP and
415/// user-agent in a single call and remains available.
416///
417/// # Invariants (not enforced at the type level)
418///
419/// * `created_at <= last_activity`
420/// * `created_at < expires_at`
421/// * `last_activity` is updated on every authenticated access.
422/// * `data` may contain arbitrary application-specific key/value pairs
423///   — the framework never reads them.
424#[derive(Clone, Serialize, Deserialize)]
425pub struct SessionData {
426    /// Session ID
427    pub session_id: String,
428
429    /// User ID associated with this session
430    pub user_id: String,
431
432    /// When the session was created
433    pub created_at: chrono::DateTime<chrono::Utc>,
434
435    /// When the session expires
436    pub expires_at: chrono::DateTime<chrono::Utc>,
437
438    /// Last activity timestamp
439    pub last_activity: chrono::DateTime<chrono::Utc>,
440
441    /// IP address of the session
442    pub ip_address: Option<String>,
443
444    /// User agent
445    pub user_agent: Option<String>,
446
447    /// Custom session data
448    pub data: HashMap<String, serde_json::Value>,
449}
450
451impl std::fmt::Debug for SessionData {
452    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
453        let mut d = f.debug_struct("SessionData");
454        d.field(
455            "session_id",
456            &crate::utils::redact::redacted(&self.session_id),
457        );
458        d.field("user_id", &self.user_id);
459        d.field("created_at", &self.created_at);
460        d.field("expires_at", &self.expires_at);
461        d.field("last_activity", &self.last_activity);
462        d.field("ip_address", &self.ip_address);
463        d.field("user_agent", &self.user_agent);
464        d.field("data", &crate::utils::redact::redacted(&self.data));
465        d.finish()
466    }
467}
468
469/// In-memory storage implementation (for development/testing only).
470///
471/// # ⚠️ Production Unsuitability
472///
473/// This implementation is NOT recommended for production use:
474/// - **Data Loss**: All stored tokens and sessions are lost on process restart
475/// - **Memory Growth**: No automatic cleanup; memory usage grows unbounded
476/// - **TTL Ignored**: Expiration times are not enforced; expired tokens may be returned
477/// - **Single Instance**: Cannot be used in multi-instance deployments
478/// - **No Persistence**: No option to back up or export data
479///
480/// Use `PostgresStorage`, `RedisStorage`, or `SqliteStorage` for production.
481///
482/// SECURITY UPDATE: Now uses DashMap for deadlock-free concurrent operations
483#[derive(Debug, Clone)]
484pub struct MemoryStorage {
485    // Primary storage using DashMap for deadlock-free operations
486    inner: crate::storage::dashmap_memory::DashMapMemoryStorage,
487    // RBAC storage still uses RwLock for compatibility (lower concurrency requirements)
488    roles: Arc<RwLock<HashMap<String, crate::authorization::AbacRole>>>,
489    user_roles: Arc<RwLock<Vec<crate::authorization::UserRole>>>,
490}
491
492/// Serialises the in-process swaps below (all instances: swaps are rare, so one lock is enough).
493static IN_PROCESS_SWAP_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
494
495/// [`AuthStorage::swap_kv`] for the in-process backends, which have no transaction: under one lock
496/// shared by every swap it checks that a `remove` key is live, stores the new key if absent (a
497/// refusal or an error leaves the removed keys untouched), then deletes the removed keys.
498///
499/// Atomic with respect to other swaps and to claims made with `store_kv_if_absent`; a concurrent
500/// reader may see both keys in the instant between the store and the deletes.
501pub(crate) async fn swap_kv_in_process<S: AuthStorage + ?Sized>(
502    storage: &S,
503    remove: &[String],
504    key: &str,
505    value: &[u8],
506    ttl: Option<Duration>,
507) -> Result<bool> {
508    let _guard = IN_PROCESS_SWAP_LOCK.lock().await;
509    let mut any_live = false;
510    for name in remove {
511        if storage.get_kv(name).await?.is_some() {
512            any_live = true;
513            break;
514        }
515    }
516    if !any_live || !storage.store_kv_if_absent(key, value, ttl).await? {
517        return Ok(false);
518    }
519    for name in remove {
520        storage.delete_kv(name).await?;
521    }
522    Ok(true)
523}
524
525/// Redis storage implementation.
526#[cfg(feature = "redis-storage")]
527#[derive(Debug, Clone)]
528pub struct RedisStorage {
529    client: redis::Client,
530    key_prefix: String,
531}
532
533impl Default for MemoryStorage {
534    fn default() -> Self {
535        Self::new()
536    }
537}
538
539impl MemoryStorage {
540    /// Create a new in-memory storage.
541    pub fn new() -> Self {
542        Self {
543            inner: crate::storage::dashmap_memory::DashMapMemoryStorage::new(),
544            roles: Arc::new(RwLock::new(HashMap::new())),
545            user_roles: Arc::new(RwLock::new(Vec::new())),
546        }
547    }
548}
549// In-memory AuthorizationStorage implementation for RBAC examples
550#[async_trait::async_trait]
551impl crate::authorization::AuthorizationStorage for MemoryStorage {
552    async fn store_role(&self, role: &crate::authorization::AbacRole) -> crate::errors::Result<()> {
553        let mut roles = self.roles.write().map_err(|_| {
554            crate::errors::AuthError::internal(
555                "Lock poisoned — a prior thread panicked while holding this lock",
556            )
557        })?;
558        roles.insert(role.id.clone(), role.clone());
559        Ok(())
560    }
561
562    async fn get_role(
563        &self,
564        role_id: &str,
565    ) -> crate::errors::Result<Option<crate::authorization::AbacRole>> {
566        let roles = self.roles.read().map_err(|_| {
567            crate::errors::AuthError::internal(
568                "Lock poisoned — a prior thread panicked while holding this lock",
569            )
570        })?;
571        Ok(roles.get(role_id).cloned())
572    }
573
574    async fn update_role(
575        &self,
576        role: &crate::authorization::AbacRole,
577    ) -> crate::errors::Result<()> {
578        let mut roles = self.roles.write().map_err(|_| {
579            crate::errors::AuthError::internal(
580                "Lock poisoned — a prior thread panicked while holding this lock",
581            )
582        })?;
583        roles.insert(role.id.clone(), role.clone());
584        Ok(())
585    }
586
587    async fn delete_role(&self, role_id: &str) -> crate::errors::Result<()> {
588        let mut roles = self.roles.write().map_err(|_| {
589            crate::errors::AuthError::internal(
590                "Lock poisoned — a prior thread panicked while holding this lock",
591            )
592        })?;
593        roles.remove(role_id);
594        Ok(())
595    }
596
597    async fn list_roles(&self) -> crate::errors::Result<Vec<crate::authorization::AbacRole>> {
598        let roles = self.roles.read().map_err(|_| {
599            crate::errors::AuthError::internal(
600                "Lock poisoned — a prior thread panicked while holding this lock",
601            )
602        })?;
603        Ok(roles.values().cloned().collect())
604    }
605
606    async fn assign_role(
607        &self,
608        user_role: &crate::authorization::UserRole,
609    ) -> crate::errors::Result<()> {
610        let mut user_roles = self.user_roles.write().map_err(|_| {
611            crate::errors::AuthError::internal(
612                "Lock poisoned — a prior thread panicked while holding this lock",
613            )
614        })?;
615        user_roles.push(user_role.clone());
616        Ok(())
617    }
618
619    async fn remove_role(&self, user_id: &str, role_id: &str) -> crate::errors::Result<()> {
620        let mut user_roles = self.user_roles.write().map_err(|_| {
621            crate::errors::AuthError::internal(
622                "Lock poisoned — a prior thread panicked while holding this lock",
623            )
624        })?;
625        user_roles.retain(|ur| ur.user_id != user_id || ur.role_id != role_id);
626        Ok(())
627    }
628
629    async fn get_user_roles(
630        &self,
631        user_id: &str,
632    ) -> crate::errors::Result<Vec<crate::authorization::UserRole>> {
633        let user_roles = self.user_roles.read().map_err(|_| {
634            crate::errors::AuthError::internal(
635                "Lock poisoned — a prior thread panicked while holding this lock",
636            )
637        })?;
638        Ok(user_roles
639            .iter()
640            .filter(|ur| ur.user_id == user_id)
641            .cloned()
642            .collect())
643    }
644
645    async fn get_role_users(
646        &self,
647        role_id: &str,
648    ) -> crate::errors::Result<Vec<crate::authorization::UserRole>> {
649        let user_roles = self.user_roles.read().map_err(|_| {
650            crate::errors::AuthError::internal(
651                "Lock poisoned — a prior thread panicked while holding this lock",
652            )
653        })?;
654        Ok(user_roles
655            .iter()
656            .filter(|ur| ur.role_id == role_id)
657            .cloned()
658            .collect())
659    }
660}
661
662#[async_trait]
663impl AuthStorage for MemoryStorage {
664    async fn store_token(&self, token: &AuthToken) -> Result<()> {
665        // Delegate to DashMap implementation for deadlock-free operations
666        self.inner.store_token(token).await
667    }
668
669    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>> {
670        // Delegate to DashMap implementation for deadlock-free operations
671        self.inner.get_token(token_id).await
672    }
673
674    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>> {
675        // Delegate to DashMap implementation for deadlock-free operations
676        self.inner.get_token_by_access_token(access_token).await
677    }
678
679    async fn update_token(&self, token: &AuthToken) -> Result<()> {
680        // Delegate to DashMap implementation for deadlock-free operations
681        self.inner.update_token(token).await
682    }
683
684    async fn delete_token(&self, token_id: &str) -> Result<()> {
685        // Delegate to DashMap implementation for deadlock-free operations
686        self.inner.delete_token(token_id).await
687    }
688
689    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
690        // Delegate to DashMap implementation for deadlock-free operations
691        self.inner.list_user_tokens(user_id).await
692    }
693
694    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()> {
695        // Delegate to DashMap implementation for deadlock-free operations
696        self.inner.store_session(session_id, data).await
697    }
698
699    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
700        // Delegate to DashMap implementation for deadlock-free operations
701        self.inner.get_session(session_id).await
702    }
703
704    async fn delete_session(&self, session_id: &str) -> Result<()> {
705        // Delegate to DashMap implementation for deadlock-free operations
706        self.inner.delete_session(session_id).await
707    }
708
709    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> {
710        // Delegate to DashMap implementation for deadlock-free operations
711        self.inner.list_user_sessions(user_id).await
712    }
713
714    async fn count_active_sessions(&self) -> Result<u64> {
715        // Delegate to DashMap implementation for deadlock-free operations
716        self.inner.count_active_sessions().await
717    }
718
719    async fn store_kv(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()> {
720        // Delegate to DashMap implementation for deadlock-free operations
721        self.inner.store_kv(key, value, ttl).await
722    }
723
724    async fn store_kv_if_absent(
725        &self,
726        key: &str,
727        value: &[u8],
728        ttl: Option<Duration>,
729    ) -> Result<bool> {
730        self.inner.store_kv_if_absent(key, value, ttl).await
731    }
732
733    async fn swap_kv(
734        &self,
735        remove: &[String],
736        key: &str,
737        value: &[u8],
738        ttl: Option<Duration>,
739    ) -> Result<bool> {
740        self.inner.swap_kv(remove, key, value, ttl).await
741    }
742
743    fn supports_atomic_swap(&self) -> bool {
744        self.inner.supports_atomic_swap()
745    }
746
747    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
748        // Delegate to DashMap implementation for deadlock-free operations
749        self.inner.get_kv(key).await
750    }
751
752    async fn get_kv_ttl(&self, key: &str) -> Result<Option<Duration>> {
753        self.inner.get_kv_ttl(key).await
754    }
755
756    fn tracks_kv_ttl(&self) -> bool {
757        self.inner.tracks_kv_ttl()
758    }
759
760    async fn delete_kv(&self, key: &str) -> Result<()> {
761        // Delegate to DashMap implementation for deadlock-free operations
762        self.inner.delete_kv(key).await
763    }
764
765    async fn list_kv_keys(&self, prefix: &str) -> Result<Vec<String>> {
766        Ok(self.inner.list_kv_keys_by_prefix(prefix))
767    }
768
769    async fn cleanup_expired(&self) -> Result<()> {
770        // Delegate to DashMap implementation for deadlock-free operations
771        self.inner.cleanup_expired().await
772    }
773}
774
775#[cfg(feature = "redis-storage")]
776impl RedisStorage {
777    /// Create a new Redis storage.
778    pub fn new(redis_url: &str, key_prefix: impl Into<String>) -> Result<Self> {
779        let client = redis::Client::open(redis_url).map_err(|e| {
780            StorageError::connection_failed(format!("Redis connection failed: {e}"))
781        })?;
782
783        Ok(Self {
784            client,
785            key_prefix: key_prefix.into(),
786        })
787    }
788
789    /// Get a Redis connection.
790    async fn get_connection(&self) -> Result<redis::aio::MultiplexedConnection> {
791        self.client
792            .get_multiplexed_async_connection()
793            .await
794            .map_err(|e| {
795                StorageError::connection_failed(format!("Failed to get Redis connection: {e}"))
796                    .into()
797            })
798    }
799
800    /// Generate a key with the configured prefix.
801    fn key(&self, suffix: &str) -> String {
802        format!("{}{}", self.key_prefix, suffix)
803    }
804
805    /// Key of the access-token -> token-id mapping. The raw access token is a
806    /// bearer credential and is never used as a key name (see
807    /// [`crate::storage::key_names`]).
808    fn access_mapping_key(&self, access_token: &str) -> String {
809        self.key(&format!(
810            "access_token_h:{}",
811            crate::storage::key_names::digest("access_token", access_token)
812        ))
813    }
814
815    /// The pre-fix name, kept only to read-and-migrate or delete old rows.
816    fn legacy_access_mapping_key(&self, access_token: &str) -> String {
817        self.key(&format!("access_token:{access_token}"))
818    }
819
820    /// Key of a session record; the session id is a bearer credential.
821    fn session_key(&self, session_id: &str) -> String {
822        self.key(&format!(
823            "session_h:{}",
824            crate::storage::key_names::digest("session", session_id)
825        ))
826    }
827
828    /// The pre-fix name, kept only to read-and-migrate or delete old rows.
829    fn legacy_session_key(&self, session_id: &str) -> String {
830        self.key(&format!("session:{session_id}"))
831    }
832
833    /// Every session key, under the digest name and under the legacy name.
834    /// Two exact-prefix patterns, so nothing else sharing the key prefix
835    /// matches. A session present under both names (a crash between the two
836    /// writes of a store) is returned under both names; `count_active_sessions`
837    /// counts it once.
838    async fn session_keys(
839        &self,
840        conn: &mut redis::aio::MultiplexedConnection,
841    ) -> Result<Vec<String>> {
842        let mut keys = Vec::new();
843        for pattern in [self.key("session_h:*"), self.key("session:*")] {
844            keys.extend(Self::scan_keys(conn, &pattern, "sessions").await?);
845        }
846        Ok(keys)
847    }
848
849    /// Every key matching `pattern`, by cursor `SCAN` (`KEYS` is O(N) in one
850    /// blocking command). `SCAN` may return a key more than once, so the result
851    /// is de-duplicated; a key that expires mid-scan may be missed or listed,
852    /// as with any non-atomic listing.
853    async fn scan_keys(
854        conn: &mut redis::aio::MultiplexedConnection,
855        pattern: &str,
856        what: &str,
857    ) -> Result<Vec<String>> {
858        let mut seen = std::collections::HashSet::new();
859        let mut keys = Vec::new();
860        let mut cursor: u64 = 0;
861        loop {
862            let (next, batch): (u64, Vec<String>) = redis::cmd("SCAN")
863                .arg(cursor)
864                .arg("MATCH")
865                .arg(pattern)
866                .arg("COUNT")
867                .arg(500)
868                .query_async(&mut *conn)
869                .await
870                .map_err(|e| {
871                    StorageError::operation_failed(format!("Failed to scan {what}: {e}"))
872                })?;
873            for key in batch {
874                if seen.insert(key.clone()) {
875                    keys.push(key);
876                }
877            }
878            if next == 0 {
879                return Ok(keys);
880            }
881            cursor = next;
882        }
883    }
884
885    /// Read `new_key`; on a miss, move a row stored under `legacy_key` (the raw
886    /// credential name used before digest naming) to `new_key`, keeping its
887    /// remaining lifetime, and return it.
888    async fn get_migrating(&self, new_key: &str, legacy_key: &str) -> Result<Option<String>> {
889        let mut conn = self.get_connection().await?;
890        // Plain read first: it needs no scripting permission, and a digest-named
891        // row is the common case.
892        let value: Option<String> = redis::cmd("GET")
893            .arg(new_key)
894            .query_async(&mut conn)
895            .await
896            .map_err(|e| StorageError::operation_failed(format!("Failed to read key: {e}")))?;
897        if value.is_some() {
898            // A legacy twin can only be left by an interrupted write and still
899            // holds the raw id in its name: drop it (best effort).
900            let _ = redis::cmd("DEL")
901                .arg(legacy_key)
902                .query_async::<usize>(&mut conn)
903                .await;
904            return Ok(value);
905        }
906        // One Lua script, so a concurrent store or delete cannot interleave with the
907        // move: it never overwrites a row already at `new_key` and never recreates
908        // a row that was deleted.
909        const MIGRATE: &str = r#"
910            local l = redis.call('GET', KEYS[2])
911            if not l then return redis.call('GET', KEYS[1]) end
912            local v = redis.call('GET', KEYS[1])
913            if v then
914                redis.call('DEL', KEYS[2])
915                return v
916            end
917            local t = redis.call('PTTL', KEYS[2])
918            if t > 0 then
919                redis.call('SET', KEYS[1], l, 'PX', t)
920            elseif t == -1 then
921                redis.call('SET', KEYS[1], l)
922            else
923                return false
924            end
925            redis.call('DEL', KEYS[2])
926            return l
927        "#;
928        match redis::Script::new(MIGRATE)
929            .key(new_key)
930            .key(legacy_key)
931            .invoke_async::<Option<String>>(&mut conn)
932            .await
933        {
934            Ok(value) => Ok(value),
935            Err(script_err) => {
936                // Scripting denied (restricted ACL) or unavailable: serve the row
937                // where it is. It moves once scripts are allowed or the record is
938                // rewritten.
939                tracing::warn!(
940                    error = %script_err,
941                    "legacy-name migration script failed; serving the row unmigrated"
942                );
943                let legacy: Option<String> = redis::cmd("GET")
944                    .arg(legacy_key)
945                    .query_async(&mut conn)
946                    .await
947                    .map_err(|e| {
948                        StorageError::operation_failed(format!("Failed to read key: {e}"))
949                    })?;
950                Ok(legacy)
951            }
952        }
953    }
954
955    /// Delete a key left under a pre-fix (raw credential) name, if any.
956    async fn del_legacy(&self, legacy_key: &str) -> Result<()> {
957        let mut conn = self.get_connection().await?;
958        let _: () = redis::cmd("DEL")
959            .arg(legacy_key)
960            .query_async(&mut conn)
961            .await
962            .map_err(|e| {
963                StorageError::operation_failed(format!("Failed to remove legacy key: {e}"))
964            })?;
965        Ok(())
966    }
967}
968
969#[cfg(feature = "redis-storage")]
970#[async_trait]
971impl AuthStorage for RedisStorage {
972    async fn store_token(&self, token: &AuthToken) -> Result<()> {
973        let mut conn = self.get_connection().await?;
974        let token_json = serde_json::to_string(token)
975            .map_err(|e| StorageError::serialization(format!("Token serialization failed: {e}")))?;
976
977        let token_key = self.key(&format!("token:{}", token.token_id));
978        let access_token_key = self.access_mapping_key(&token.access_token);
979        let user_tokens_key = self.key(&format!("user_tokens:{}", token.user_id));
980
981        // Calculate TTL
982        let ttl = token.time_until_expiry().as_secs().max(1);
983
984        // One script, so a failure between the writes cannot leave a token with no
985        // lookup (or a lookup with no token), and the user's set lives as long as
986        // its longest-lived member (an earlier, longer-lived token is not cut short
987        // by a later, shorter one; a set with no expiry gets one).
988        const STORE: &str = r#"
989            redis.call('SETEX', KEYS[1], ARGV[1], ARGV[2])
990            redis.call('SETEX', KEYS[2], ARGV[1], ARGV[3])
991            redis.call('SADD', KEYS[3], ARGV[3])
992            local t = redis.call('TTL', KEYS[3])
993            if t < tonumber(ARGV[1]) then
994                redis.call('EXPIRE', KEYS[3], ARGV[1])
995            end
996            return 1
997        "#;
998        redis::Script::new(STORE)
999            .key(&token_key)
1000            .key(&access_token_key)
1001            .key(&user_tokens_key)
1002            .arg(ttl)
1003            .arg(&token_json)
1004            .arg(&token.token_id)
1005            .invoke_async::<i64>(&mut conn)
1006            .await
1007            .map_err(|e| StorageError::operation_failed(format!("Failed to store token: {e}")))?;
1008
1009        // Drop a mapping left under the pre-fix name (it held the raw token).
1010        self.del_legacy(&self.legacy_access_mapping_key(&token.access_token))
1011            .await?;
1012
1013        Ok(())
1014    }
1015
1016    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>> {
1017        let mut conn = self.get_connection().await?;
1018        let token_key = self.key(&format!("token:{token_id}"));
1019
1020        let token_json: Option<String> = redis::cmd("GET")
1021            .arg(&token_key)
1022            .query_async(&mut conn)
1023            .await
1024            .map_err(|e| StorageError::operation_failed(format!("Failed to get token: {e}")))?;
1025
1026        if let Some(json) = token_json {
1027            let token: AuthToken = serde_json::from_str(&json).map_err(|e| {
1028                StorageError::serialization(format!("Token deserialization failed: {e}"))
1029            })?;
1030            Ok(Some(token))
1031        } else {
1032            Ok(None)
1033        }
1034    }
1035
1036    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>> {
1037        let token_id = self
1038            .get_migrating(
1039                &self.access_mapping_key(access_token),
1040                &self.legacy_access_mapping_key(access_token),
1041            )
1042            .await?;
1043
1044        if let Some(token_id) = token_id {
1045            self.get_token(&token_id).await
1046        } else {
1047            Ok(None)
1048        }
1049    }
1050
1051    async fn update_token(&self, token: &AuthToken) -> Result<()> {
1052        // Same as store_token for Redis
1053        self.store_token(token).await
1054    }
1055
1056    async fn delete_token(&self, token_id: &str) -> Result<()> {
1057        let mut conn = self.get_connection().await?;
1058
1059        // Get token first to get access token and user ID
1060        if let Some(token) = self.get_token(token_id).await? {
1061            let token_key = self.key(&format!("token:{token_id}"));
1062            let access_token_key = self.access_mapping_key(&token.access_token);
1063            let user_tokens_key = self.key(&format!("user_tokens:{}", token.user_id));
1064            self.del_legacy(&self.legacy_access_mapping_key(&token.access_token))
1065                .await?;
1066
1067            // One transaction: the token, its lookup and its set entry go together.
1068            let _: () = redis::pipe()
1069                .atomic()
1070                .cmd("DEL")
1071                .arg(&token_key)
1072                .ignore()
1073                .cmd("DEL")
1074                .arg(&access_token_key)
1075                .ignore()
1076                .cmd("SREM")
1077                .arg(&user_tokens_key)
1078                .arg(token_id)
1079                .ignore()
1080                .query_async(&mut conn)
1081                .await
1082                .map_err(|e| {
1083                    StorageError::operation_failed(format!("Failed to delete token: {e}"))
1084                })?;
1085        }
1086
1087        Ok(())
1088    }
1089
1090    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
1091        let mut conn = self.get_connection().await?;
1092        let user_tokens_key = self.key(&format!("user_tokens:{user_id}"));
1093
1094        let token_ids: Vec<String> = redis::cmd("SMEMBERS")
1095            .arg(&user_tokens_key)
1096            .query_async(&mut conn)
1097            .await
1098            .map_err(|e| {
1099                StorageError::operation_failed(format!("Failed to get user tokens: {e}"))
1100            })?;
1101
1102        let mut tokens = Vec::new();
1103        for token_id in token_ids {
1104            if let Some(token) = self.get_token(&token_id).await? {
1105                tokens.push(token);
1106            }
1107        }
1108
1109        Ok(tokens)
1110    }
1111
1112    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()> {
1113        let mut conn = self.get_connection().await?;
1114        let session_key = self.session_key(session_id);
1115
1116        let session_json = serde_json::to_string(data).map_err(|e| {
1117            StorageError::serialization(format!("Session serialization failed: {e}"))
1118        })?;
1119
1120        let ttl = (data.expires_at - chrono::Utc::now()).num_seconds().max(1);
1121
1122        let _: () = redis::cmd("SETEX")
1123            .arg(&session_key)
1124            .arg(ttl)
1125            .arg(&session_json)
1126            .query_async(&mut conn)
1127            .await
1128            .map_err(|e| StorageError::operation_failed(format!("Failed to store session: {e}")))?;
1129
1130        // Drop a record left under the pre-fix name (it held the raw session id).
1131        self.del_legacy(&self.legacy_session_key(session_id))
1132            .await?;
1133
1134        Ok(())
1135    }
1136
1137    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
1138        let session_json = self
1139            .get_migrating(
1140                &self.session_key(session_id),
1141                &self.legacy_session_key(session_id),
1142            )
1143            .await?;
1144
1145        if let Some(json) = session_json {
1146            let session: SessionData = serde_json::from_str(&json).map_err(|e| {
1147                StorageError::serialization(format!("Session deserialization failed: {e}"))
1148            })?;
1149            Ok(Some(session))
1150        } else {
1151            Ok(None)
1152        }
1153    }
1154
1155    async fn delete_session(&self, session_id: &str) -> Result<()> {
1156        let mut conn = self.get_connection().await?;
1157        let session_key = self.session_key(session_id);
1158
1159        // Legacy name first: a migration that runs in between then finds no
1160        // legacy row to move, so a deleted session cannot be recreated.
1161        self.del_legacy(&self.legacy_session_key(session_id))
1162            .await?;
1163        let _: () = redis::cmd("DEL")
1164            .arg(&session_key)
1165            .query_async(&mut conn)
1166            .await
1167            .map_err(|e| {
1168                StorageError::operation_failed(format!("Failed to delete session: {e}"))
1169            })?;
1170
1171        Ok(())
1172    }
1173
1174    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> {
1175        let mut conn = self.get_connection().await?;
1176        let keys = self.session_keys(&mut conn).await?;
1177
1178        let mut user_sessions = Vec::new();
1179        let mut seen = std::collections::HashSet::new();
1180
1181        // Check each session to see if it belongs to the user
1182        let legacy_prefix = self.legacy_session_key("");
1183        for key in keys {
1184            // A row still under the pre-fix name is moved to its digest name as
1185            // it is listed, so it stops exposing the raw session id in key names.
1186            let session_json = match key.strip_prefix(&legacy_prefix) {
1187                Some(session_id) => self
1188                    .get_migrating(&self.session_key(session_id), &key)
1189                    .await
1190                    .ok()
1191                    .flatten(),
1192                None => redis::cmd("GET")
1193                    .arg(&key)
1194                    .query_async::<Option<String>>(&mut conn)
1195                    .await
1196                    .ok()
1197                    .flatten(),
1198            };
1199            if let Some(session_json) = session_json
1200                && let Ok(session) = serde_json::from_str::<SessionData>(&session_json)
1201                && session.user_id == user_id
1202                && !session.is_expired()
1203                && seen.insert(session.session_id.clone())
1204            {
1205                user_sessions.push(session);
1206            }
1207        }
1208
1209        Ok(user_sessions)
1210    }
1211
1212    async fn store_kv_if_absent(
1213        &self,
1214        key: &str,
1215        value: &[u8],
1216        ttl: Option<Duration>,
1217    ) -> Result<bool> {
1218        let mut conn = self.get_connection().await?;
1219        let storage_key = self.key(&format!("kv:{key}"));
1220        // SET ... NX [PX ms]: atomic; the reply is OK when set and nil when the key exists.
1221        let mut cmd = redis::cmd("SET");
1222        cmd.arg(&storage_key).arg(value).arg("NX");
1223        if let Some(ttl) = ttl {
1224            let millis = u64::try_from(ttl.as_millis()).unwrap_or(u64::MAX).max(1);
1225            cmd.arg("PX").arg(millis);
1226        }
1227        let reply: Option<String> = cmd.query_async(&mut conn).await.map_err(|e| {
1228            StorageError::operation_failed(format!("Failed to store KV if absent: {e}"))
1229        })?;
1230        Ok(reply.is_some())
1231    }
1232
1233    async fn swap_kv(
1234        &self,
1235        remove: &[String],
1236        key: &str,
1237        value: &[u8],
1238        ttl: Option<Duration>,
1239    ) -> Result<bool> {
1240        if remove.is_empty() {
1241            return Ok(false);
1242        }
1243        let mut conn = self.get_connection().await?;
1244        let script = redis::Script::new(crate::storage::redis::SWAP_KV_SCRIPT);
1245        let mut invocation = script.prepare_invoke();
1246        for name in remove {
1247            invocation.key(self.key(&format!("kv:{name}")));
1248        }
1249        invocation.key(self.key(&format!("kv:{key}")));
1250        let millis = ttl.map_or(0, |d| {
1251            u64::try_from(d.as_millis()).unwrap_or(u64::MAX).max(1)
1252        });
1253        let swapped: i64 = invocation
1254            .arg(value)
1255            .arg(millis)
1256            .invoke_async(&mut conn)
1257            .await
1258            .map_err(|e| StorageError::operation_failed(format!("Failed to swap KV: {e}")))?;
1259        Ok(swapped == 1)
1260    }
1261
1262    fn supports_atomic_swap(&self) -> bool {
1263        true
1264    }
1265
1266    async fn store_kv(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()> {
1267        let mut conn = self.get_connection().await?;
1268        let storage_key = self.key(&format!("kv:{key}"));
1269
1270        if let Some(ttl) = ttl {
1271            // PSETEX, not SETEX: a remaining TTL under one second must not
1272            // become `SETEX key 0 ...`, which Redis rejects.
1273            let millis = u64::try_from(ttl.as_millis()).unwrap_or(u64::MAX).max(1);
1274            let _: () = redis::cmd("PSETEX")
1275                .arg(&storage_key)
1276                .arg(millis)
1277                .arg(value)
1278                .query_async(&mut conn)
1279                .await
1280                .map_err(|e| {
1281                    StorageError::operation_failed(format!("Failed to store KV with TTL: {e}"))
1282                })?;
1283        } else {
1284            let _: () = redis::cmd("SET")
1285                .arg(&storage_key)
1286                .arg(value)
1287                .query_async(&mut conn)
1288                .await
1289                .map_err(|e| StorageError::operation_failed(format!("Failed to store KV: {e}")))?;
1290        }
1291
1292        Ok(())
1293    }
1294
1295    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
1296        let mut conn = self.get_connection().await?;
1297        let storage_key = self.key(&format!("kv:{key}"));
1298
1299        let value: Option<Vec<u8>> = redis::cmd("GET")
1300            .arg(&storage_key)
1301            .query_async(&mut conn)
1302            .await
1303            .map_err(|e| StorageError::operation_failed(format!("Failed to get KV: {e}")))?;
1304
1305        Ok(value)
1306    }
1307
1308    async fn get_kv_ttl(&self, key: &str) -> Result<Option<Duration>> {
1309        let mut conn = self.get_connection().await?;
1310        let storage_key = self.key(&format!("kv:{key}"));
1311
1312        // PTTL: -2 = no such key, -1 = no expiry, otherwise milliseconds left.
1313        let millis: i64 = redis::cmd("PTTL")
1314            .arg(&storage_key)
1315            .query_async(&mut conn)
1316            .await
1317            .map_err(|e| StorageError::operation_failed(format!("Failed to get KV TTL: {e}")))?;
1318
1319        Ok(u64::try_from(millis)
1320            .ok()
1321            .filter(|millis| *millis > 0)
1322            .map(Duration::from_millis))
1323    }
1324
1325    fn tracks_kv_ttl(&self) -> bool {
1326        true
1327    }
1328
1329    async fn delete_kv(&self, key: &str) -> Result<()> {
1330        let mut conn = self.get_connection().await?;
1331        let storage_key = self.key(&format!("kv:{key}"));
1332
1333        let _: () = redis::cmd("DEL")
1334            .arg(&storage_key)
1335            .query_async(&mut conn)
1336            .await
1337            .map_err(|e| StorageError::operation_failed(format!("Failed to delete KV: {e}")))?;
1338
1339        Ok(())
1340    }
1341
1342    async fn list_kv_keys(&self, prefix: &str) -> Result<Vec<String>> {
1343        let mut conn = self.get_connection().await?;
1344        let pattern = self.key(&format!("kv:{prefix}*"));
1345        let keys = Self::scan_keys(&mut conn, &pattern, "KV keys").await?;
1346
1347        Ok(keys
1348            .into_iter()
1349            .filter_map(|key| key.strip_prefix(&self.key_prefix).map(str::to_string))
1350            .filter_map(|key| key.strip_prefix("kv:").map(str::to_string))
1351            .collect())
1352    }
1353
1354    async fn cleanup_expired(&self) -> Result<()> {
1355        // Redis handles expiration automatically, so this is a no-op
1356        Ok(())
1357    }
1358
1359    async fn count_active_sessions(&self) -> Result<u64> {
1360        let mut conn = self.get_connection().await?;
1361
1362        // Cursor-scan for every session key.
1363        let keys = self.session_keys(&mut conn).await?;
1364        // A session present under both names is one session.
1365        let keys = crate::storage::key_names::without_shadowed_legacy(
1366            keys,
1367            &self.legacy_session_key(""),
1368            &self.key("session_h:"),
1369            "session",
1370        );
1371
1372        // Count only non-expired sessions by checking TTL
1373        let mut active_count = 0u64;
1374        for key in keys {
1375            let ttl: i64 = redis::cmd("TTL")
1376                .arg(&key)
1377                .query_async(&mut conn)
1378                .await
1379                .map_err(|e| StorageError::operation_failed(format!("Failed to check TTL: {e}")))?;
1380
1381            // TTL > 0 means key has expiration and is still active
1382            // TTL = -1 means key has no expiration (active)
1383            // TTL = -2 means key doesn't exist (expired)
1384            if ttl > 0 || ttl == -1 {
1385                active_count += 1;
1386            }
1387        }
1388
1389        Ok(active_count)
1390    }
1391}
1392
1393impl SessionData {
1394    /// Create a new session with consistent timestamps.
1395    ///
1396    /// # Arguments
1397    /// * `session_id` - Unique session identifier (typically a UUID)
1398    /// * `user_id` - Associated user ID
1399    /// * `expires_in` - Session lifetime from now
1400    ///
1401    /// Use [`with_metadata`](SessionData::with_metadata) to attach IP and
1402    /// user-agent information after construction.
1403    ///
1404    /// # Panics
1405    /// If `expires_in` conversion to `chrono::Duration` fails catastrophically.
1406    pub fn new(
1407        session_id: impl Into<String>,
1408        user_id: impl Into<String>,
1409        expires_in: Duration,
1410    ) -> Self {
1411        let now = chrono::Utc::now();
1412
1413        Self {
1414            session_id: session_id.into(),
1415            user_id: user_id.into(),
1416            created_at: now,
1417            expires_at: now
1418                + chrono::Duration::from_std(expires_in).unwrap_or(chrono::Duration::hours(1)),
1419            last_activity: now,
1420            ip_address: None,
1421            user_agent: None,
1422            data: HashMap::new(),
1423        }
1424    }
1425
1426    /// Check if the session has expired.
1427    pub fn is_expired(&self) -> bool {
1428        chrono::Utc::now() > self.expires_at
1429    }
1430
1431    /// Return the remaining lifetime of this session.
1432    ///
1433    /// Returns [`Duration::ZERO`](std::time::Duration::ZERO) when the session
1434    /// has already expired.
1435    pub fn time_until_expiry(&self) -> std::time::Duration {
1436        let remaining = self.expires_at - chrono::Utc::now();
1437        remaining.to_std().unwrap_or(std::time::Duration::ZERO)
1438    }
1439
1440    /// Check if the session is still active (not expired).
1441    pub fn is_active(&self) -> bool {
1442        !self.is_expired()
1443    }
1444
1445    /// Update the last activity timestamp.
1446    pub fn update_activity(&mut self) {
1447        self.last_activity = chrono::Utc::now();
1448    }
1449
1450    /// Set session metadata (IP address and user-agent) in one call.
1451    pub fn with_metadata(mut self, ip_address: Option<String>, user_agent: Option<String>) -> Self {
1452        self.ip_address = ip_address;
1453        self.user_agent = user_agent;
1454        self
1455    }
1456
1457    /// Set the client IP address.
1458    pub fn ip_address(mut self, ip: impl Into<String>) -> Self {
1459        self.ip_address = Some(ip.into());
1460        self
1461    }
1462
1463    /// Set the client user-agent string.
1464    pub fn user_agent(mut self, ua: impl Into<String>) -> Self {
1465        self.user_agent = Some(ua.into());
1466        self
1467    }
1468
1469    /// Add a custom data entry (chainable).
1470    pub fn with_data(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
1471        self.data.insert(key.into(), value);
1472        self
1473    }
1474
1475    /// Add custom data to the session.
1476    pub fn set_data(&mut self, key: impl Into<String>, value: serde_json::Value) {
1477        self.data.insert(key.into(), value);
1478    }
1479
1480    /// Get custom data from the session.
1481    pub fn get_data(&self, key: &str) -> Option<&serde_json::Value> {
1482        self.data.get(key)
1483    }
1484}
1485
1486/// Implementation of AuditStorage for MemoryStorage
1487#[async_trait]
1488impl crate::audit::AuditStorage for MemoryStorage {
1489    async fn store_event(&self, event: &crate::audit::AuditEvent) -> Result<()> {
1490        // Store audit event as JSON in KV storage
1491        let json_data = serde_json::to_vec(event).map_err(|e| {
1492            crate::errors::AuthError::internal(format!("Failed to serialize audit event: {}", e))
1493        })?;
1494
1495        let key = format!("audit_event_{}", event.id);
1496        self.store_kv(&key, &json_data, None).await
1497    }
1498
1499    async fn query_events(
1500        &self,
1501        query: &crate::audit::AuditQuery,
1502    ) -> Result<Vec<crate::audit::AuditEvent>> {
1503        // Simple implementation - in production, this would be more efficient
1504        let all_keys = self.list_kv_keys("audit_event_").await?;
1505        let mut events = Vec::new();
1506
1507        for key in all_keys {
1508            if let Some(data) = self.get_kv(&key).await?
1509                && let Ok(event) = serde_json::from_slice::<crate::audit::AuditEvent>(&data)
1510            {
1511                // Apply filters
1512                let mut include = true;
1513
1514                if let Some(ref time_range) = query.time_range
1515                    && (event.timestamp < time_range.start || event.timestamp > time_range.end)
1516                {
1517                    include = false;
1518                }
1519
1520                if let Some(ref event_types) = query.event_types
1521                    && !event_types.contains(&event.event_type)
1522                {
1523                    include = false;
1524                }
1525
1526                if let Some(ref user_id) = query.user_id
1527                    && event.user_id.as_ref() != Some(user_id)
1528                {
1529                    include = false;
1530                }
1531
1532                if include {
1533                    events.push(event);
1534                }
1535            }
1536        }
1537
1538        // Sort and limit
1539        events.sort_by(|a, b| match query.sort_order {
1540            crate::audit::SortOrder::TimestampAsc => a.timestamp.cmp(&b.timestamp),
1541            crate::audit::SortOrder::TimestampDesc => b.timestamp.cmp(&a.timestamp),
1542            crate::audit::SortOrder::RiskLevelDesc => b.risk_level.cmp(&a.risk_level),
1543        });
1544
1545        if let Some(limit) = query.limit {
1546            events.truncate(limit as usize);
1547        }
1548        Ok(events)
1549    }
1550
1551    async fn get_event(&self, event_id: &str) -> Result<Option<crate::audit::AuditEvent>> {
1552        let key = format!("audit_event_{}", event_id);
1553        if let Some(data) = self.get_kv(&key).await? {
1554            let event = serde_json::from_slice(&data).map_err(|e| {
1555                crate::errors::AuthError::internal(format!(
1556                    "Failed to deserialize audit event: {}",
1557                    e
1558                ))
1559            })?;
1560            Ok(Some(event))
1561        } else {
1562            Ok(None)
1563        }
1564    }
1565
1566    async fn count_events(&self, query: &crate::audit::AuditQuery) -> Result<u64> {
1567        let events = self.query_events(query).await?;
1568        Ok(events.len() as u64)
1569    }
1570
1571    async fn delete_old_events(&self, before: std::time::SystemTime) -> Result<u64> {
1572        let all_keys = self.list_kv_keys("audit_event_").await?;
1573        let mut deleted_count = 0;
1574
1575        for key in all_keys {
1576            if let Some(data) = self.get_kv(&key).await?
1577                && let Ok(event) = serde_json::from_slice::<crate::audit::AuditEvent>(&data)
1578                && event.timestamp < before
1579            {
1580                self.delete_kv(&key).await?;
1581                deleted_count += 1;
1582            }
1583        }
1584
1585        Ok(deleted_count)
1586    }
1587
1588    async fn get_statistics(
1589        &self,
1590        query: &crate::audit::StatsQuery,
1591    ) -> Result<crate::audit::AuditStatistics> {
1592        use std::collections::HashMap;
1593
1594        // Pull all events matching the time range in the query.
1595        let audit_query = crate::audit::AuditQuery::builder()
1596            .time_range(query.time_range.start, query.time_range.end)
1597            .sort_order(crate::audit::SortOrder::TimestampAsc)
1598            .build();
1599        let events = self.query_events(&audit_query).await?;
1600        let total_events = events.len() as u64;
1601
1602        let mut event_type_counts: HashMap<String, u64> = HashMap::new();
1603        let mut risk_level_counts: HashMap<String, u64> = HashMap::new();
1604        let mut outcome_counts: HashMap<String, u64> = HashMap::new();
1605
1606        for event in &events {
1607            *event_type_counts
1608                .entry(format!("{:?}", event.event_type))
1609                .or_insert(0) += 1;
1610            *risk_level_counts
1611                .entry(format!("{:?}", event.risk_level))
1612                .or_insert(0) += 1;
1613            *outcome_counts
1614                .entry(format!("{:?}", event.outcome))
1615                .or_insert(0) += 1;
1616        }
1617
1618        Ok(crate::audit::AuditStatistics {
1619            total_events,
1620            event_type_counts,
1621            risk_level_counts,
1622            outcome_counts,
1623            time_series: Vec::new(),
1624            top_users: Vec::new(),
1625            top_ips: Vec::new(),
1626        })
1627    }
1628}
1629
1630impl MemoryStorage {
1631    /// Helper method to list KV keys with a prefix
1632    async fn list_kv_keys(&self, _prefix: &str) -> Result<Vec<String>> {
1633        Ok(self.inner.list_kv_keys_by_prefix(_prefix))
1634    }
1635}
1636
1637/// Implementation of AuditStorage for `Arc<MemoryStorage>`
1638#[async_trait]
1639impl crate::audit::AuditStorage for Arc<MemoryStorage> {
1640    async fn store_event(&self, event: &crate::audit::AuditEvent) -> Result<()> {
1641        self.as_ref().store_event(event).await
1642    }
1643
1644    async fn query_events(
1645        &self,
1646        query: &crate::audit::AuditQuery,
1647    ) -> Result<Vec<crate::audit::AuditEvent>> {
1648        self.as_ref().query_events(query).await
1649    }
1650
1651    async fn get_event(&self, event_id: &str) -> Result<Option<crate::audit::AuditEvent>> {
1652        self.as_ref().get_event(event_id).await
1653    }
1654
1655    async fn count_events(&self, query: &crate::audit::AuditQuery) -> Result<u64> {
1656        self.as_ref().count_events(query).await
1657    }
1658
1659    async fn delete_old_events(&self, before: std::time::SystemTime) -> Result<u64> {
1660        self.as_ref().delete_old_events(before).await
1661    }
1662
1663    async fn get_statistics(
1664        &self,
1665        query: &crate::audit::StatsQuery,
1666    ) -> Result<crate::audit::AuditStatistics> {
1667        self.as_ref().get_statistics(query).await
1668    }
1669}
1670
1671#[cfg(test)]
1672mod tests {
1673    use super::*;
1674    use crate::tokens::AuthToken;
1675
1676    // ── Token CRUD ──────────────────────────────────────────────────
1677
1678    #[tokio::test]
1679    async fn test_memory_storage() {
1680        let storage = MemoryStorage::new();
1681
1682        let token = AuthToken::new("user123", "token123", Duration::from_secs(3600), "test");
1683
1684        storage.store_token(&token).await.unwrap();
1685
1686        let retrieved = storage.get_token(&token.token_id).await.unwrap().unwrap();
1687        assert_eq!(retrieved.user_id, "user123");
1688
1689        let retrieved = storage
1690            .get_token_by_access_token(&token.access_token)
1691            .await
1692            .unwrap()
1693            .unwrap();
1694        assert_eq!(retrieved.token_id, token.token_id);
1695
1696        let user_tokens = storage.list_user_tokens("user123").await.unwrap();
1697        assert_eq!(user_tokens.len(), 1);
1698
1699        storage.delete_token(&token.token_id).await.unwrap();
1700        let retrieved = storage.get_token(&token.token_id).await.unwrap();
1701        assert!(retrieved.is_none());
1702    }
1703
1704    #[tokio::test]
1705    async fn test_token_update() {
1706        let storage = MemoryStorage::new();
1707        let mut token = AuthToken::new("user1", "access_original", Duration::from_secs(3600), "pw");
1708        storage.store_token(&token).await.unwrap();
1709
1710        token.auth_method = "mfa".to_string();
1711        storage.update_token(&token).await.unwrap();
1712
1713        let retrieved = storage.get_token(&token.token_id).await.unwrap().unwrap();
1714        assert_eq!(retrieved.auth_method, "mfa");
1715    }
1716
1717    #[tokio::test]
1718    async fn test_token_get_nonexistent() {
1719        let storage = MemoryStorage::new();
1720        let result = storage.get_token("nonexistent").await.unwrap();
1721        assert!(result.is_none());
1722
1723        let result = storage
1724            .get_token_by_access_token("nonexistent")
1725            .await
1726            .unwrap();
1727        assert!(result.is_none());
1728    }
1729
1730    #[tokio::test]
1731    async fn test_list_user_tokens_multiple() {
1732        let storage = MemoryStorage::new();
1733        let t1 = AuthToken::new("user_a", "at1", Duration::from_secs(3600), "pw");
1734        let t2 = AuthToken::new("user_a", "at2", Duration::from_secs(3600), "pw");
1735        let t3 = AuthToken::new("user_b", "at3", Duration::from_secs(3600), "pw");
1736
1737        storage.store_token(&t1).await.unwrap();
1738        storage.store_token(&t2).await.unwrap();
1739        storage.store_token(&t3).await.unwrap();
1740
1741        let user_a_tokens = storage.list_user_tokens("user_a").await.unwrap();
1742        assert_eq!(user_a_tokens.len(), 2);
1743
1744        let user_b_tokens = storage.list_user_tokens("user_b").await.unwrap();
1745        assert_eq!(user_b_tokens.len(), 1);
1746
1747        let empty = storage.list_user_tokens("nobody").await.unwrap();
1748        assert!(empty.is_empty());
1749    }
1750
1751    #[tokio::test]
1752    async fn test_store_tokens_bulk() {
1753        let storage = MemoryStorage::new();
1754        let tokens = vec![
1755            AuthToken::new("u1", "a1", Duration::from_secs(3600), "pw"),
1756            AuthToken::new("u2", "a2", Duration::from_secs(3600), "pw"),
1757            AuthToken::new("u3", "a3", Duration::from_secs(3600), "pw"),
1758        ];
1759        let ids: Vec<String> = tokens.iter().map(|t| t.token_id.clone()).collect();
1760
1761        storage.store_tokens_bulk(&tokens).await.unwrap();
1762
1763        for id in &ids {
1764            assert!(storage.get_token(id).await.unwrap().is_some());
1765        }
1766
1767        storage.delete_tokens_bulk(&ids).await.unwrap();
1768
1769        for id in &ids {
1770            assert!(storage.get_token(id).await.unwrap().is_none());
1771        }
1772    }
1773
1774    // ── Session CRUD ────────────────────────────────────────────────
1775
1776    #[tokio::test]
1777    async fn test_session_storage() {
1778        let storage = MemoryStorage::new();
1779
1780        let session = SessionData::new("session123", "user123", Duration::from_secs(3600))
1781            .with_metadata(
1782                Some("192.168.1.1".to_string()),
1783                Some("Test Agent".to_string()),
1784            );
1785
1786        storage
1787            .store_session(&session.session_id, &session)
1788            .await
1789            .unwrap();
1790
1791        let retrieved = storage
1792            .get_session(&session.session_id)
1793            .await
1794            .unwrap()
1795            .unwrap();
1796        assert_eq!(retrieved.user_id, "user123");
1797        assert_eq!(retrieved.ip_address, Some("192.168.1.1".to_string()));
1798
1799        storage.delete_session(&session.session_id).await.unwrap();
1800        let retrieved = storage.get_session(&session.session_id).await.unwrap();
1801        assert!(retrieved.is_none());
1802    }
1803
1804    #[tokio::test]
1805    async fn test_session_get_nonexistent() {
1806        let storage = MemoryStorage::new();
1807        let result = storage.get_session("no_such_session").await.unwrap();
1808        assert!(result.is_none());
1809    }
1810
1811    #[tokio::test]
1812    async fn test_list_user_sessions() {
1813        let storage = MemoryStorage::new();
1814
1815        let s1 = SessionData::new("s1", "alice", Duration::from_secs(3600));
1816        let s2 = SessionData::new("s2", "alice", Duration::from_secs(3600));
1817        let s3 = SessionData::new("s3", "bob", Duration::from_secs(3600));
1818
1819        storage.store_session("s1", &s1).await.unwrap();
1820        storage.store_session("s2", &s2).await.unwrap();
1821        storage.store_session("s3", &s3).await.unwrap();
1822
1823        let alice_sessions = storage.list_user_sessions("alice").await.unwrap();
1824        assert_eq!(alice_sessions.len(), 2);
1825
1826        let bob_sessions = storage.list_user_sessions("bob").await.unwrap();
1827        assert_eq!(bob_sessions.len(), 1);
1828    }
1829
1830    #[tokio::test]
1831    async fn test_count_active_sessions() {
1832        let storage = MemoryStorage::new();
1833
1834        let s1 = SessionData::new("cs1", "u1", Duration::from_secs(3600));
1835        let s2 = SessionData::new("cs2", "u2", Duration::from_secs(3600));
1836        storage.store_session("cs1", &s1).await.unwrap();
1837        storage.store_session("cs2", &s2).await.unwrap();
1838
1839        let count = storage.count_active_sessions().await.unwrap();
1840        assert!(count >= 2);
1841    }
1842
1843    #[tokio::test]
1844    async fn test_store_sessions_bulk() {
1845        let storage = MemoryStorage::new();
1846        let sessions = vec![
1847            (
1848                "bs1".to_string(),
1849                SessionData::new("bs1", "u1", Duration::from_secs(3600)),
1850            ),
1851            (
1852                "bs2".to_string(),
1853                SessionData::new("bs2", "u2", Duration::from_secs(3600)),
1854            ),
1855        ];
1856
1857        storage.store_sessions_bulk(&sessions).await.unwrap();
1858        assert!(storage.get_session("bs1").await.unwrap().is_some());
1859        assert!(storage.get_session("bs2").await.unwrap().is_some());
1860
1861        let ids = vec!["bs1".to_string(), "bs2".to_string()];
1862        storage.delete_sessions_bulk(&ids).await.unwrap();
1863        assert!(storage.get_session("bs1").await.unwrap().is_none());
1864        assert!(storage.get_session("bs2").await.unwrap().is_none());
1865    }
1866
1867    #[tokio::test]
1868    async fn test_session_custom_data() {
1869        let storage = MemoryStorage::new();
1870        let mut session = SessionData::new("sd1", "u1", Duration::from_secs(3600));
1871        session.set_data("theme", serde_json::json!("dark"));
1872        session.set_data("lang", serde_json::json!("en"));
1873
1874        storage.store_session("sd1", &session).await.unwrap();
1875
1876        let retrieved = storage.get_session("sd1").await.unwrap().unwrap();
1877        assert_eq!(
1878            retrieved.get_data("theme"),
1879            Some(&serde_json::json!("dark"))
1880        );
1881        assert_eq!(retrieved.get_data("lang"), Some(&serde_json::json!("en")));
1882        assert_eq!(retrieved.get_data("missing"), None);
1883    }
1884
1885    // ── KV Storage ──────────────────────────────────────────────────
1886
1887    #[tokio::test]
1888    async fn test_kv_storage() {
1889        let storage = MemoryStorage::new();
1890
1891        let key = "test_key";
1892        let value = b"test_value";
1893
1894        storage
1895            .store_kv(key, value, Some(Duration::from_secs(3600)))
1896            .await
1897            .unwrap();
1898
1899        let retrieved = storage.get_kv(key).await.unwrap().unwrap();
1900        assert_eq!(retrieved, value);
1901
1902        storage.delete_kv(key).await.unwrap();
1903        let retrieved = storage.get_kv(key).await.unwrap();
1904        assert!(retrieved.is_none());
1905    }
1906
1907    #[tokio::test]
1908    async fn test_kv_no_ttl() {
1909        let storage = MemoryStorage::new();
1910        storage
1911            .store_kv("persistent", b"forever", None)
1912            .await
1913            .unwrap();
1914
1915        let retrieved = storage.get_kv("persistent").await.unwrap().unwrap();
1916        assert_eq!(retrieved, b"forever");
1917    }
1918
1919    #[tokio::test]
1920    async fn test_kv_overwrite() {
1921        let storage = MemoryStorage::new();
1922        storage
1923            .store_kv("k1", b"v1", Some(Duration::from_secs(3600)))
1924            .await
1925            .unwrap();
1926        storage
1927            .store_kv("k1", b"v2", Some(Duration::from_secs(3600)))
1928            .await
1929            .unwrap();
1930
1931        let retrieved = storage.get_kv("k1").await.unwrap().unwrap();
1932        assert_eq!(retrieved, b"v2");
1933    }
1934
1935    #[tokio::test]
1936    async fn test_kv_get_nonexistent() {
1937        let storage = MemoryStorage::new();
1938        let result = storage.get_kv("no_such_key").await.unwrap();
1939        assert!(result.is_none());
1940    }
1941
1942    #[tokio::test]
1943    async fn test_kv_list_keys_prefix() {
1944        let storage = MemoryStorage::new();
1945        storage
1946            .store_kv("user:1:name", b"alice", None)
1947            .await
1948            .unwrap();
1949        storage
1950            .store_kv("user:1:email", b"alice@x.com", None)
1951            .await
1952            .unwrap();
1953        storage.store_kv("user:2:name", b"bob", None).await.unwrap();
1954        storage
1955            .store_kv("session:abc", b"data", None)
1956            .await
1957            .unwrap();
1958
1959        let user1_keys = storage.list_kv_keys("user:1:").await.unwrap();
1960        assert_eq!(user1_keys.len(), 2);
1961
1962        let all_user_keys = storage.list_kv_keys("user:").await.unwrap();
1963        assert_eq!(all_user_keys.len(), 3);
1964
1965        let session_keys = storage.list_kv_keys("session:").await.unwrap();
1966        assert_eq!(session_keys.len(), 1);
1967
1968        let empty = storage.list_kv_keys("nonexistent:").await.unwrap();
1969        assert!(empty.is_empty());
1970    }
1971
1972    #[tokio::test]
1973    async fn test_kv_binary_data() {
1974        let storage = MemoryStorage::new();
1975        let binary = vec![0u8, 1, 2, 255, 254, 253, 0, 128];
1976        storage.store_kv("binary_key", &binary, None).await.unwrap();
1977
1978        let retrieved = storage.get_kv("binary_key").await.unwrap().unwrap();
1979        assert_eq!(retrieved, binary);
1980    }
1981
1982    // ── Cleanup ──────────────────────────────────────────────────────
1983
1984    #[tokio::test]
1985    async fn test_cleanup_expired() {
1986        let storage = MemoryStorage::new();
1987
1988        // Store a KV entry with a very short TTL (already expired by the time
1989        // cleanup runs because DashMap wraps its own expiry clock).
1990        // Note: MemoryStorage cleanup uses TimestampedToken's own expires_at
1991        // (derived from default_ttl), NOT AuthToken.expires_at. We test KV
1992        // cleanup because it respects TTLs directly.
1993        storage
1994            .store_kv("expire_me", b"val", Some(Duration::from_secs(0)))
1995            .await
1996            .unwrap();
1997        storage
1998            .store_kv("keep_me", b"val", Some(Duration::from_secs(3600)))
1999            .await
2000            .unwrap();
2001
2002        // Give a tiny window for the zero-TTL entry to register as expired
2003        tokio::time::sleep(Duration::from_millis(10)).await;
2004
2005        storage.cleanup_expired().await.unwrap();
2006
2007        // Zero-TTL entry should be cleaned up, valid entry remains
2008        assert!(storage.get_kv("expire_me").await.unwrap().is_none());
2009        assert!(storage.get_kv("keep_me").await.unwrap().is_some());
2010    }
2011
2012    // ── Session expiration ──────────────────────────────────────────
2013
2014    #[tokio::test]
2015    async fn test_session_is_expired() {
2016        let mut session = SessionData::new("exp1", "u1", Duration::from_secs(3600));
2017        assert!(!session.is_expired());
2018
2019        session.expires_at = chrono::Utc::now() - chrono::Duration::seconds(1);
2020        assert!(session.is_expired());
2021    }
2022
2023    #[tokio::test]
2024    async fn test_session_update_activity() {
2025        let mut session = SessionData::new("act1", "u1", Duration::from_secs(3600));
2026        let first_activity = session.last_activity;
2027        // Small delay to ensure timestamp changes
2028        session.update_activity();
2029        assert!(session.last_activity >= first_activity);
2030    }
2031
2032    // ── Token upsert semantics ──────────────────────────────────────
2033
2034    #[tokio::test]
2035    async fn test_token_store_twice_overwrites_primary() {
2036        let storage = MemoryStorage::new();
2037        let token = AuthToken::new("u1", "at1", Duration::from_secs(3600), "pw");
2038        let token_id = token.token_id.clone();
2039
2040        storage.store_token(&token).await.unwrap();
2041        storage.store_token(&token).await.unwrap();
2042
2043        // Primary DashMap uses insert() so only one entry with this token_id exists.
2044        let got = storage.get_token(&token_id).await.unwrap();
2045        assert!(got.is_some());
2046    }
2047
2048    // ── Delete idempotency ──────────────────────────────────────────
2049
2050    #[tokio::test]
2051    async fn test_delete_nonexistent_token() {
2052        let storage = MemoryStorage::new();
2053        // Deleting a key that doesn't exist should not error
2054        let result = storage.delete_token("nope").await;
2055        assert!(result.is_ok());
2056    }
2057
2058    #[tokio::test]
2059    async fn test_delete_nonexistent_session() {
2060        let storage = MemoryStorage::new();
2061        let result = storage.delete_session("nope").await;
2062        assert!(result.is_ok());
2063    }
2064
2065    #[tokio::test]
2066    async fn test_delete_nonexistent_kv() {
2067        let storage = MemoryStorage::new();
2068        let result = storage.delete_kv("nope").await;
2069        assert!(result.is_ok());
2070    }
2071}