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", &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            let found: Vec<String> = redis::cmd("KEYS")
845                .arg(&pattern)
846                .query_async(&mut *conn)
847                .await
848                .map_err(|e| {
849                    StorageError::operation_failed(format!("Failed to scan sessions: {e}"))
850                })?;
851            keys.extend(found);
852        }
853        Ok(keys)
854    }
855
856    /// Read `new_key`; on a miss, move a row stored under `legacy_key` (the raw
857    /// credential name used before digest naming) to `new_key`, keeping its
858    /// remaining lifetime, and return it.
859    async fn get_migrating(&self, new_key: &str, legacy_key: &str) -> Result<Option<String>> {
860        let mut conn = self.get_connection().await?;
861        // Plain read first: it needs no scripting permission, and a digest-named
862        // row is the common case.
863        let value: Option<String> = redis::cmd("GET")
864            .arg(new_key)
865            .query_async(&mut conn)
866            .await
867            .map_err(|e| StorageError::operation_failed(format!("Failed to read key: {e}")))?;
868        if value.is_some() {
869            // A legacy twin can only be left by an interrupted write and still
870            // holds the raw id in its name: drop it (best effort).
871            let _ = redis::cmd("DEL")
872                .arg(legacy_key)
873                .query_async::<usize>(&mut conn)
874                .await;
875            return Ok(value);
876        }
877        // One Lua script, so a concurrent store or delete cannot interleave with the
878        // move: it never overwrites a row already at `new_key` and never recreates
879        // a row that was deleted.
880        const MIGRATE: &str = r#"
881            local l = redis.call('GET', KEYS[2])
882            if not l then return redis.call('GET', KEYS[1]) end
883            local v = redis.call('GET', KEYS[1])
884            if v then
885                redis.call('DEL', KEYS[2])
886                return v
887            end
888            local t = redis.call('PTTL', KEYS[2])
889            if t > 0 then
890                redis.call('SET', KEYS[1], l, 'PX', t)
891            elseif t == -1 then
892                redis.call('SET', KEYS[1], l)
893            else
894                return false
895            end
896            redis.call('DEL', KEYS[2])
897            return l
898        "#;
899        match redis::Script::new(MIGRATE)
900            .key(new_key)
901            .key(legacy_key)
902            .invoke_async::<Option<String>>(&mut conn)
903            .await
904        {
905            Ok(value) => Ok(value),
906            Err(script_err) => {
907                // Scripting denied (restricted ACL) or unavailable: serve the row
908                // where it is. It moves once scripts are allowed or the record is
909                // rewritten.
910                tracing::warn!(
911                    error = %script_err,
912                    "legacy-name migration script failed; serving the row unmigrated"
913                );
914                let legacy: Option<String> = redis::cmd("GET")
915                    .arg(legacy_key)
916                    .query_async(&mut conn)
917                    .await
918                    .map_err(|e| {
919                        StorageError::operation_failed(format!("Failed to read key: {e}"))
920                    })?;
921                Ok(legacy)
922            }
923        }
924    }
925
926    /// Delete a key left under a pre-fix (raw credential) name, if any.
927    async fn del_legacy(&self, legacy_key: &str) -> Result<()> {
928        let mut conn = self.get_connection().await?;
929        let _: () = redis::cmd("DEL")
930            .arg(legacy_key)
931            .query_async(&mut conn)
932            .await
933            .map_err(|e| {
934                StorageError::operation_failed(format!("Failed to remove legacy key: {e}"))
935            })?;
936        Ok(())
937    }
938}
939
940#[cfg(feature = "redis-storage")]
941#[async_trait]
942impl AuthStorage for RedisStorage {
943    async fn store_token(&self, token: &AuthToken) -> Result<()> {
944        let mut conn = self.get_connection().await?;
945        let token_json = serde_json::to_string(token)
946            .map_err(|e| StorageError::serialization(format!("Token serialization failed: {e}")))?;
947
948        let token_key = self.key(&format!("token:{}", token.token_id));
949        let access_token_key = self.access_mapping_key(&token.access_token);
950        let user_tokens_key = self.key(&format!("user_tokens:{}", token.user_id));
951
952        // Calculate TTL
953        let ttl = token.time_until_expiry().as_secs().max(1);
954
955        // Store token data
956        let _: () = redis::cmd("SETEX")
957            .arg(&token_key)
958            .arg(ttl)
959            .arg(&token_json)
960            .query_async(&mut conn)
961            .await
962            .map_err(|e| StorageError::operation_failed(format!("Failed to store token: {e}")))?;
963
964        // Store access token mapping
965        let _: () = redis::cmd("SETEX")
966            .arg(&access_token_key)
967            .arg(ttl)
968            .arg(&token.token_id)
969            .query_async(&mut conn)
970            .await
971            .map_err(|e| {
972                StorageError::operation_failed(format!("Failed to store access token mapping: {e}"))
973            })?;
974
975        // Drop a mapping left under the pre-fix name (it held the raw token).
976        self.del_legacy(&self.legacy_access_mapping_key(&token.access_token))
977            .await?;
978
979        // Add to user tokens set
980        let _: () = redis::cmd("SADD")
981            .arg(&user_tokens_key)
982            .arg(&token.token_id)
983            .query_async(&mut conn)
984            .await
985            .map_err(|e| {
986                StorageError::operation_failed(format!("Failed to add token to user set: {e}"))
987            })?;
988
989        Ok(())
990    }
991
992    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>> {
993        let mut conn = self.get_connection().await?;
994        let token_key = self.key(&format!("token:{token_id}"));
995
996        let token_json: Option<String> = redis::cmd("GET")
997            .arg(&token_key)
998            .query_async(&mut conn)
999            .await
1000            .map_err(|e| StorageError::operation_failed(format!("Failed to get token: {e}")))?;
1001
1002        if let Some(json) = token_json {
1003            let token: AuthToken = serde_json::from_str(&json).map_err(|e| {
1004                StorageError::serialization(format!("Token deserialization failed: {e}"))
1005            })?;
1006            Ok(Some(token))
1007        } else {
1008            Ok(None)
1009        }
1010    }
1011
1012    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>> {
1013        let token_id = self
1014            .get_migrating(
1015                &self.access_mapping_key(access_token),
1016                &self.legacy_access_mapping_key(access_token),
1017            )
1018            .await?;
1019
1020        if let Some(token_id) = token_id {
1021            self.get_token(&token_id).await
1022        } else {
1023            Ok(None)
1024        }
1025    }
1026
1027    async fn update_token(&self, token: &AuthToken) -> Result<()> {
1028        // Same as store_token for Redis
1029        self.store_token(token).await
1030    }
1031
1032    async fn delete_token(&self, token_id: &str) -> Result<()> {
1033        let mut conn = self.get_connection().await?;
1034
1035        // Get token first to get access token and user ID
1036        if let Some(token) = self.get_token(token_id).await? {
1037            let token_key = self.key(&format!("token:{token_id}"));
1038            let access_token_key = self.access_mapping_key(&token.access_token);
1039            let user_tokens_key = self.key(&format!("user_tokens:{}", token.user_id));
1040            self.del_legacy(&self.legacy_access_mapping_key(&token.access_token))
1041                .await?;
1042
1043            // Delete token data
1044            let _: () = redis::cmd("DEL")
1045                .arg(&token_key)
1046                .query_async(&mut conn)
1047                .await
1048                .map_err(|e| {
1049                    StorageError::operation_failed(format!("Failed to delete token: {e}"))
1050                })?;
1051
1052            // Delete access token mapping
1053            let _: () = redis::cmd("DEL")
1054                .arg(&access_token_key)
1055                .query_async(&mut conn)
1056                .await
1057                .map_err(|e| {
1058                    StorageError::operation_failed(format!(
1059                        "Failed to delete access token mapping: {e}"
1060                    ))
1061                })?;
1062
1063            // Remove from user tokens set
1064            let _: () = redis::cmd("SREM")
1065                .arg(&user_tokens_key)
1066                .arg(token_id)
1067                .query_async(&mut conn)
1068                .await
1069                .map_err(|e| {
1070                    StorageError::operation_failed(format!(
1071                        "Failed to remove token from user set: {e}"
1072                    ))
1073                })?;
1074        }
1075
1076        Ok(())
1077    }
1078
1079    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
1080        let mut conn = self.get_connection().await?;
1081        let user_tokens_key = self.key(&format!("user_tokens:{user_id}"));
1082
1083        let token_ids: Vec<String> = redis::cmd("SMEMBERS")
1084            .arg(&user_tokens_key)
1085            .query_async(&mut conn)
1086            .await
1087            .map_err(|e| {
1088                StorageError::operation_failed(format!("Failed to get user tokens: {e}"))
1089            })?;
1090
1091        let mut tokens = Vec::new();
1092        for token_id in token_ids {
1093            if let Some(token) = self.get_token(&token_id).await? {
1094                tokens.push(token);
1095            }
1096        }
1097
1098        Ok(tokens)
1099    }
1100
1101    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()> {
1102        let mut conn = self.get_connection().await?;
1103        let session_key = self.session_key(session_id);
1104
1105        let session_json = serde_json::to_string(data).map_err(|e| {
1106            StorageError::serialization(format!("Session serialization failed: {e}"))
1107        })?;
1108
1109        let ttl = (data.expires_at - chrono::Utc::now()).num_seconds().max(1);
1110
1111        let _: () = redis::cmd("SETEX")
1112            .arg(&session_key)
1113            .arg(ttl)
1114            .arg(&session_json)
1115            .query_async(&mut conn)
1116            .await
1117            .map_err(|e| StorageError::operation_failed(format!("Failed to store session: {e}")))?;
1118
1119        // Drop a record left under the pre-fix name (it held the raw session id).
1120        self.del_legacy(&self.legacy_session_key(session_id))
1121            .await?;
1122
1123        Ok(())
1124    }
1125
1126    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
1127        let session_json = self
1128            .get_migrating(
1129                &self.session_key(session_id),
1130                &self.legacy_session_key(session_id),
1131            )
1132            .await?;
1133
1134        if let Some(json) = session_json {
1135            let session: SessionData = serde_json::from_str(&json).map_err(|e| {
1136                StorageError::serialization(format!("Session deserialization failed: {e}"))
1137            })?;
1138            Ok(Some(session))
1139        } else {
1140            Ok(None)
1141        }
1142    }
1143
1144    async fn delete_session(&self, session_id: &str) -> Result<()> {
1145        let mut conn = self.get_connection().await?;
1146        let session_key = self.session_key(session_id);
1147
1148        // Legacy name first: a migration that runs in between then finds no
1149        // legacy row to move, so a deleted session cannot be recreated.
1150        self.del_legacy(&self.legacy_session_key(session_id))
1151            .await?;
1152        let _: () = redis::cmd("DEL")
1153            .arg(&session_key)
1154            .query_async(&mut conn)
1155            .await
1156            .map_err(|e| {
1157                StorageError::operation_failed(format!("Failed to delete session: {e}"))
1158            })?;
1159
1160        Ok(())
1161    }
1162
1163    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> {
1164        let mut conn = self.get_connection().await?;
1165        let keys = self.session_keys(&mut conn).await?;
1166
1167        let mut user_sessions = Vec::new();
1168        let mut seen = std::collections::HashSet::new();
1169
1170        // Check each session to see if it belongs to the user
1171        let legacy_prefix = self.legacy_session_key("");
1172        for key in keys {
1173            // A row still under the pre-fix name is moved to its digest name as
1174            // it is listed, so it stops exposing the raw session id in key names.
1175            let session_json = match key.strip_prefix(&legacy_prefix) {
1176                Some(session_id) => self
1177                    .get_migrating(&self.session_key(session_id), &key)
1178                    .await
1179                    .ok()
1180                    .flatten(),
1181                None => redis::cmd("GET")
1182                    .arg(&key)
1183                    .query_async::<Option<String>>(&mut conn)
1184                    .await
1185                    .ok()
1186                    .flatten(),
1187            };
1188            if let Some(session_json) = session_json
1189                && let Ok(session) = serde_json::from_str::<SessionData>(&session_json)
1190                && session.user_id == user_id
1191                && !session.is_expired()
1192                && seen.insert(session.session_id.clone())
1193            {
1194                user_sessions.push(session);
1195            }
1196        }
1197
1198        Ok(user_sessions)
1199    }
1200
1201    async fn store_kv_if_absent(
1202        &self,
1203        key: &str,
1204        value: &[u8],
1205        ttl: Option<Duration>,
1206    ) -> Result<bool> {
1207        let mut conn = self.get_connection().await?;
1208        let storage_key = self.key(&format!("kv:{key}"));
1209        // SET ... NX [PX ms]: atomic; the reply is OK when set and nil when the key exists.
1210        let mut cmd = redis::cmd("SET");
1211        cmd.arg(&storage_key).arg(value).arg("NX");
1212        if let Some(ttl) = ttl {
1213            let millis = u64::try_from(ttl.as_millis()).unwrap_or(u64::MAX).max(1);
1214            cmd.arg("PX").arg(millis);
1215        }
1216        let reply: Option<String> = cmd.query_async(&mut conn).await.map_err(|e| {
1217            StorageError::operation_failed(format!("Failed to store KV if absent: {e}"))
1218        })?;
1219        Ok(reply.is_some())
1220    }
1221
1222    async fn swap_kv(
1223        &self,
1224        remove: &[String],
1225        key: &str,
1226        value: &[u8],
1227        ttl: Option<Duration>,
1228    ) -> Result<bool> {
1229        if remove.is_empty() {
1230            return Ok(false);
1231        }
1232        let mut conn = self.get_connection().await?;
1233        let script = redis::Script::new(crate::storage::redis::SWAP_KV_SCRIPT);
1234        let mut invocation = script.prepare_invoke();
1235        for name in remove {
1236            invocation.key(self.key(&format!("kv:{name}")));
1237        }
1238        invocation.key(self.key(&format!("kv:{key}")));
1239        let millis = ttl.map_or(0, |d| {
1240            u64::try_from(d.as_millis()).unwrap_or(u64::MAX).max(1)
1241        });
1242        let swapped: i64 = invocation
1243            .arg(value)
1244            .arg(millis)
1245            .invoke_async(&mut conn)
1246            .await
1247            .map_err(|e| StorageError::operation_failed(format!("Failed to swap KV: {e}")))?;
1248        Ok(swapped == 1)
1249    }
1250
1251    fn supports_atomic_swap(&self) -> bool {
1252        true
1253    }
1254
1255    async fn store_kv(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()> {
1256        let mut conn = self.get_connection().await?;
1257        let storage_key = self.key(&format!("kv:{key}"));
1258
1259        if let Some(ttl) = ttl {
1260            // PSETEX, not SETEX: a remaining TTL under one second must not
1261            // become `SETEX key 0 ...`, which Redis rejects.
1262            let millis = u64::try_from(ttl.as_millis()).unwrap_or(u64::MAX).max(1);
1263            let _: () = redis::cmd("PSETEX")
1264                .arg(&storage_key)
1265                .arg(millis)
1266                .arg(value)
1267                .query_async(&mut conn)
1268                .await
1269                .map_err(|e| {
1270                    StorageError::operation_failed(format!("Failed to store KV with TTL: {e}"))
1271                })?;
1272        } else {
1273            let _: () = redis::cmd("SET")
1274                .arg(&storage_key)
1275                .arg(value)
1276                .query_async(&mut conn)
1277                .await
1278                .map_err(|e| StorageError::operation_failed(format!("Failed to store KV: {e}")))?;
1279        }
1280
1281        Ok(())
1282    }
1283
1284    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
1285        let mut conn = self.get_connection().await?;
1286        let storage_key = self.key(&format!("kv:{key}"));
1287
1288        let value: Option<Vec<u8>> = redis::cmd("GET")
1289            .arg(&storage_key)
1290            .query_async(&mut conn)
1291            .await
1292            .map_err(|e| StorageError::operation_failed(format!("Failed to get KV: {e}")))?;
1293
1294        Ok(value)
1295    }
1296
1297    async fn get_kv_ttl(&self, key: &str) -> Result<Option<Duration>> {
1298        let mut conn = self.get_connection().await?;
1299        let storage_key = self.key(&format!("kv:{key}"));
1300
1301        // PTTL: -2 = no such key, -1 = no expiry, otherwise milliseconds left.
1302        let millis: i64 = redis::cmd("PTTL")
1303            .arg(&storage_key)
1304            .query_async(&mut conn)
1305            .await
1306            .map_err(|e| StorageError::operation_failed(format!("Failed to get KV TTL: {e}")))?;
1307
1308        Ok(u64::try_from(millis)
1309            .ok()
1310            .filter(|millis| *millis > 0)
1311            .map(Duration::from_millis))
1312    }
1313
1314    fn tracks_kv_ttl(&self) -> bool {
1315        true
1316    }
1317
1318    async fn delete_kv(&self, key: &str) -> Result<()> {
1319        let mut conn = self.get_connection().await?;
1320        let storage_key = self.key(&format!("kv:{key}"));
1321
1322        let _: () = redis::cmd("DEL")
1323            .arg(&storage_key)
1324            .query_async(&mut conn)
1325            .await
1326            .map_err(|e| StorageError::operation_failed(format!("Failed to delete KV: {e}")))?;
1327
1328        Ok(())
1329    }
1330
1331    async fn list_kv_keys(&self, prefix: &str) -> Result<Vec<String>> {
1332        let mut conn = self.get_connection().await?;
1333        let pattern = self.key(&format!("kv:{prefix}*"));
1334        let keys: Vec<String> = redis::cmd("KEYS")
1335            .arg(&pattern)
1336            .query_async(&mut conn)
1337            .await
1338            .map_err(|e| StorageError::operation_failed(format!("Failed to list KV keys: {e}")))?;
1339
1340        Ok(keys
1341            .into_iter()
1342            .filter_map(|key| key.strip_prefix(&self.key_prefix).map(str::to_string))
1343            .filter_map(|key| key.strip_prefix("kv:").map(str::to_string))
1344            .collect())
1345    }
1346
1347    async fn cleanup_expired(&self) -> Result<()> {
1348        // Redis handles expiration automatically, so this is a no-op
1349        Ok(())
1350    }
1351
1352    async fn count_active_sessions(&self) -> Result<u64> {
1353        let mut conn = self.get_connection().await?;
1354
1355        // Use KEYS to find all session keys (consider SCAN for production with many keys)
1356        let keys = self.session_keys(&mut conn).await?;
1357        // A session present under both names is one session.
1358        let keys = crate::storage::key_names::without_shadowed_legacy(
1359            keys,
1360            &self.legacy_session_key(""),
1361            &self.key("session_h:"),
1362            "session",
1363        );
1364
1365        // Count only non-expired sessions by checking TTL
1366        let mut active_count = 0u64;
1367        for key in keys {
1368            let ttl: i64 = redis::cmd("TTL")
1369                .arg(&key)
1370                .query_async(&mut conn)
1371                .await
1372                .map_err(|e| StorageError::operation_failed(format!("Failed to check TTL: {e}")))?;
1373
1374            // TTL > 0 means key has expiration and is still active
1375            // TTL = -1 means key has no expiration (active)
1376            // TTL = -2 means key doesn't exist (expired)
1377            if ttl > 0 || ttl == -1 {
1378                active_count += 1;
1379            }
1380        }
1381
1382        Ok(active_count)
1383    }
1384}
1385
1386impl SessionData {
1387    /// Create a new session with consistent timestamps.
1388    ///
1389    /// # Arguments
1390    /// * `session_id` - Unique session identifier (typically a UUID)
1391    /// * `user_id` - Associated user ID
1392    /// * `expires_in` - Session lifetime from now
1393    ///
1394    /// Use [`with_metadata`](SessionData::with_metadata) to attach IP and
1395    /// user-agent information after construction.
1396    ///
1397    /// # Panics
1398    /// If `expires_in` conversion to `chrono::Duration` fails catastrophically.
1399    pub fn new(
1400        session_id: impl Into<String>,
1401        user_id: impl Into<String>,
1402        expires_in: Duration,
1403    ) -> Self {
1404        let now = chrono::Utc::now();
1405
1406        Self {
1407            session_id: session_id.into(),
1408            user_id: user_id.into(),
1409            created_at: now,
1410            expires_at: now
1411                + chrono::Duration::from_std(expires_in).unwrap_or(chrono::Duration::hours(1)),
1412            last_activity: now,
1413            ip_address: None,
1414            user_agent: None,
1415            data: HashMap::new(),
1416        }
1417    }
1418
1419    /// Check if the session has expired.
1420    pub fn is_expired(&self) -> bool {
1421        chrono::Utc::now() > self.expires_at
1422    }
1423
1424    /// Return the remaining lifetime of this session.
1425    ///
1426    /// Returns [`Duration::ZERO`](std::time::Duration::ZERO) when the session
1427    /// has already expired.
1428    pub fn time_until_expiry(&self) -> std::time::Duration {
1429        let remaining = self.expires_at - chrono::Utc::now();
1430        remaining.to_std().unwrap_or(std::time::Duration::ZERO)
1431    }
1432
1433    /// Check if the session is still active (not expired).
1434    pub fn is_active(&self) -> bool {
1435        !self.is_expired()
1436    }
1437
1438    /// Update the last activity timestamp.
1439    pub fn update_activity(&mut self) {
1440        self.last_activity = chrono::Utc::now();
1441    }
1442
1443    /// Set session metadata (IP address and user-agent) in one call.
1444    pub fn with_metadata(mut self, ip_address: Option<String>, user_agent: Option<String>) -> Self {
1445        self.ip_address = ip_address;
1446        self.user_agent = user_agent;
1447        self
1448    }
1449
1450    /// Set the client IP address.
1451    pub fn ip_address(mut self, ip: impl Into<String>) -> Self {
1452        self.ip_address = Some(ip.into());
1453        self
1454    }
1455
1456    /// Set the client user-agent string.
1457    pub fn user_agent(mut self, ua: impl Into<String>) -> Self {
1458        self.user_agent = Some(ua.into());
1459        self
1460    }
1461
1462    /// Add a custom data entry (chainable).
1463    pub fn with_data(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
1464        self.data.insert(key.into(), value);
1465        self
1466    }
1467
1468    /// Add custom data to the session.
1469    pub fn set_data(&mut self, key: impl Into<String>, value: serde_json::Value) {
1470        self.data.insert(key.into(), value);
1471    }
1472
1473    /// Get custom data from the session.
1474    pub fn get_data(&self, key: &str) -> Option<&serde_json::Value> {
1475        self.data.get(key)
1476    }
1477}
1478
1479/// Implementation of AuditStorage for MemoryStorage
1480#[async_trait]
1481impl crate::audit::AuditStorage for MemoryStorage {
1482    async fn store_event(&self, event: &crate::audit::AuditEvent) -> Result<()> {
1483        // Store audit event as JSON in KV storage
1484        let json_data = serde_json::to_vec(event).map_err(|e| {
1485            crate::errors::AuthError::internal(format!("Failed to serialize audit event: {}", e))
1486        })?;
1487
1488        let key = format!("audit_event_{}", event.id);
1489        self.store_kv(&key, &json_data, None).await
1490    }
1491
1492    async fn query_events(
1493        &self,
1494        query: &crate::audit::AuditQuery,
1495    ) -> Result<Vec<crate::audit::AuditEvent>> {
1496        // Simple implementation - in production, this would be more efficient
1497        let all_keys = self.list_kv_keys("audit_event_").await?;
1498        let mut events = Vec::new();
1499
1500        for key in all_keys {
1501            if let Some(data) = self.get_kv(&key).await?
1502                && let Ok(event) = serde_json::from_slice::<crate::audit::AuditEvent>(&data)
1503            {
1504                // Apply filters
1505                let mut include = true;
1506
1507                if let Some(ref time_range) = query.time_range
1508                    && (event.timestamp < time_range.start || event.timestamp > time_range.end)
1509                {
1510                    include = false;
1511                }
1512
1513                if let Some(ref event_types) = query.event_types
1514                    && !event_types.contains(&event.event_type)
1515                {
1516                    include = false;
1517                }
1518
1519                if let Some(ref user_id) = query.user_id
1520                    && event.user_id.as_ref() != Some(user_id)
1521                {
1522                    include = false;
1523                }
1524
1525                if include {
1526                    events.push(event);
1527                }
1528            }
1529        }
1530
1531        // Sort and limit
1532        events.sort_by(|a, b| match query.sort_order {
1533            crate::audit::SortOrder::TimestampAsc => a.timestamp.cmp(&b.timestamp),
1534            crate::audit::SortOrder::TimestampDesc => b.timestamp.cmp(&a.timestamp),
1535            crate::audit::SortOrder::RiskLevelDesc => b.risk_level.cmp(&a.risk_level),
1536        });
1537
1538        if let Some(limit) = query.limit {
1539            events.truncate(limit as usize);
1540        }
1541        Ok(events)
1542    }
1543
1544    async fn get_event(&self, event_id: &str) -> Result<Option<crate::audit::AuditEvent>> {
1545        let key = format!("audit_event_{}", event_id);
1546        if let Some(data) = self.get_kv(&key).await? {
1547            let event = serde_json::from_slice(&data).map_err(|e| {
1548                crate::errors::AuthError::internal(format!(
1549                    "Failed to deserialize audit event: {}",
1550                    e
1551                ))
1552            })?;
1553            Ok(Some(event))
1554        } else {
1555            Ok(None)
1556        }
1557    }
1558
1559    async fn count_events(&self, query: &crate::audit::AuditQuery) -> Result<u64> {
1560        let events = self.query_events(query).await?;
1561        Ok(events.len() as u64)
1562    }
1563
1564    async fn delete_old_events(&self, before: std::time::SystemTime) -> Result<u64> {
1565        let all_keys = self.list_kv_keys("audit_event_").await?;
1566        let mut deleted_count = 0;
1567
1568        for key in all_keys {
1569            if let Some(data) = self.get_kv(&key).await?
1570                && let Ok(event) = serde_json::from_slice::<crate::audit::AuditEvent>(&data)
1571                && event.timestamp < before
1572            {
1573                self.delete_kv(&key).await?;
1574                deleted_count += 1;
1575            }
1576        }
1577
1578        Ok(deleted_count)
1579    }
1580
1581    async fn get_statistics(
1582        &self,
1583        query: &crate::audit::StatsQuery,
1584    ) -> Result<crate::audit::AuditStatistics> {
1585        use std::collections::HashMap;
1586
1587        // Pull all events matching the time range in the query.
1588        let audit_query = crate::audit::AuditQuery::builder()
1589            .time_range(query.time_range.start, query.time_range.end)
1590            .sort_order(crate::audit::SortOrder::TimestampAsc)
1591            .build();
1592        let events = self.query_events(&audit_query).await?;
1593        let total_events = events.len() as u64;
1594
1595        let mut event_type_counts: HashMap<String, u64> = HashMap::new();
1596        let mut risk_level_counts: HashMap<String, u64> = HashMap::new();
1597        let mut outcome_counts: HashMap<String, u64> = HashMap::new();
1598
1599        for event in &events {
1600            *event_type_counts
1601                .entry(format!("{:?}", event.event_type))
1602                .or_insert(0) += 1;
1603            *risk_level_counts
1604                .entry(format!("{:?}", event.risk_level))
1605                .or_insert(0) += 1;
1606            *outcome_counts
1607                .entry(format!("{:?}", event.outcome))
1608                .or_insert(0) += 1;
1609        }
1610
1611        Ok(crate::audit::AuditStatistics {
1612            total_events,
1613            event_type_counts,
1614            risk_level_counts,
1615            outcome_counts,
1616            time_series: Vec::new(),
1617            top_users: Vec::new(),
1618            top_ips: Vec::new(),
1619        })
1620    }
1621}
1622
1623impl MemoryStorage {
1624    /// Helper method to list KV keys with a prefix
1625    async fn list_kv_keys(&self, _prefix: &str) -> Result<Vec<String>> {
1626        Ok(self.inner.list_kv_keys_by_prefix(_prefix))
1627    }
1628}
1629
1630/// Implementation of AuditStorage for `Arc<MemoryStorage>`
1631#[async_trait]
1632impl crate::audit::AuditStorage for Arc<MemoryStorage> {
1633    async fn store_event(&self, event: &crate::audit::AuditEvent) -> Result<()> {
1634        self.as_ref().store_event(event).await
1635    }
1636
1637    async fn query_events(
1638        &self,
1639        query: &crate::audit::AuditQuery,
1640    ) -> Result<Vec<crate::audit::AuditEvent>> {
1641        self.as_ref().query_events(query).await
1642    }
1643
1644    async fn get_event(&self, event_id: &str) -> Result<Option<crate::audit::AuditEvent>> {
1645        self.as_ref().get_event(event_id).await
1646    }
1647
1648    async fn count_events(&self, query: &crate::audit::AuditQuery) -> Result<u64> {
1649        self.as_ref().count_events(query).await
1650    }
1651
1652    async fn delete_old_events(&self, before: std::time::SystemTime) -> Result<u64> {
1653        self.as_ref().delete_old_events(before).await
1654    }
1655
1656    async fn get_statistics(
1657        &self,
1658        query: &crate::audit::StatsQuery,
1659    ) -> Result<crate::audit::AuditStatistics> {
1660        self.as_ref().get_statistics(query).await
1661    }
1662}
1663
1664#[cfg(test)]
1665mod tests {
1666    use super::*;
1667    use crate::tokens::AuthToken;
1668
1669    // ── Token CRUD ──────────────────────────────────────────────────
1670
1671    #[tokio::test]
1672    async fn test_memory_storage() {
1673        let storage = MemoryStorage::new();
1674
1675        let token = AuthToken::new("user123", "token123", Duration::from_secs(3600), "test");
1676
1677        storage.store_token(&token).await.unwrap();
1678
1679        let retrieved = storage.get_token(&token.token_id).await.unwrap().unwrap();
1680        assert_eq!(retrieved.user_id, "user123");
1681
1682        let retrieved = storage
1683            .get_token_by_access_token(&token.access_token)
1684            .await
1685            .unwrap()
1686            .unwrap();
1687        assert_eq!(retrieved.token_id, token.token_id);
1688
1689        let user_tokens = storage.list_user_tokens("user123").await.unwrap();
1690        assert_eq!(user_tokens.len(), 1);
1691
1692        storage.delete_token(&token.token_id).await.unwrap();
1693        let retrieved = storage.get_token(&token.token_id).await.unwrap();
1694        assert!(retrieved.is_none());
1695    }
1696
1697    #[tokio::test]
1698    async fn test_token_update() {
1699        let storage = MemoryStorage::new();
1700        let mut token = AuthToken::new("user1", "access_original", Duration::from_secs(3600), "pw");
1701        storage.store_token(&token).await.unwrap();
1702
1703        token.auth_method = "mfa".to_string();
1704        storage.update_token(&token).await.unwrap();
1705
1706        let retrieved = storage.get_token(&token.token_id).await.unwrap().unwrap();
1707        assert_eq!(retrieved.auth_method, "mfa");
1708    }
1709
1710    #[tokio::test]
1711    async fn test_token_get_nonexistent() {
1712        let storage = MemoryStorage::new();
1713        let result = storage.get_token("nonexistent").await.unwrap();
1714        assert!(result.is_none());
1715
1716        let result = storage
1717            .get_token_by_access_token("nonexistent")
1718            .await
1719            .unwrap();
1720        assert!(result.is_none());
1721    }
1722
1723    #[tokio::test]
1724    async fn test_list_user_tokens_multiple() {
1725        let storage = MemoryStorage::new();
1726        let t1 = AuthToken::new("user_a", "at1", Duration::from_secs(3600), "pw");
1727        let t2 = AuthToken::new("user_a", "at2", Duration::from_secs(3600), "pw");
1728        let t3 = AuthToken::new("user_b", "at3", Duration::from_secs(3600), "pw");
1729
1730        storage.store_token(&t1).await.unwrap();
1731        storage.store_token(&t2).await.unwrap();
1732        storage.store_token(&t3).await.unwrap();
1733
1734        let user_a_tokens = storage.list_user_tokens("user_a").await.unwrap();
1735        assert_eq!(user_a_tokens.len(), 2);
1736
1737        let user_b_tokens = storage.list_user_tokens("user_b").await.unwrap();
1738        assert_eq!(user_b_tokens.len(), 1);
1739
1740        let empty = storage.list_user_tokens("nobody").await.unwrap();
1741        assert!(empty.is_empty());
1742    }
1743
1744    #[tokio::test]
1745    async fn test_store_tokens_bulk() {
1746        let storage = MemoryStorage::new();
1747        let tokens = vec![
1748            AuthToken::new("u1", "a1", Duration::from_secs(3600), "pw"),
1749            AuthToken::new("u2", "a2", Duration::from_secs(3600), "pw"),
1750            AuthToken::new("u3", "a3", Duration::from_secs(3600), "pw"),
1751        ];
1752        let ids: Vec<String> = tokens.iter().map(|t| t.token_id.clone()).collect();
1753
1754        storage.store_tokens_bulk(&tokens).await.unwrap();
1755
1756        for id in &ids {
1757            assert!(storage.get_token(id).await.unwrap().is_some());
1758        }
1759
1760        storage.delete_tokens_bulk(&ids).await.unwrap();
1761
1762        for id in &ids {
1763            assert!(storage.get_token(id).await.unwrap().is_none());
1764        }
1765    }
1766
1767    // ── Session CRUD ────────────────────────────────────────────────
1768
1769    #[tokio::test]
1770    async fn test_session_storage() {
1771        let storage = MemoryStorage::new();
1772
1773        let session = SessionData::new("session123", "user123", Duration::from_secs(3600))
1774            .with_metadata(
1775                Some("192.168.1.1".to_string()),
1776                Some("Test Agent".to_string()),
1777            );
1778
1779        storage
1780            .store_session(&session.session_id, &session)
1781            .await
1782            .unwrap();
1783
1784        let retrieved = storage
1785            .get_session(&session.session_id)
1786            .await
1787            .unwrap()
1788            .unwrap();
1789        assert_eq!(retrieved.user_id, "user123");
1790        assert_eq!(retrieved.ip_address, Some("192.168.1.1".to_string()));
1791
1792        storage.delete_session(&session.session_id).await.unwrap();
1793        let retrieved = storage.get_session(&session.session_id).await.unwrap();
1794        assert!(retrieved.is_none());
1795    }
1796
1797    #[tokio::test]
1798    async fn test_session_get_nonexistent() {
1799        let storage = MemoryStorage::new();
1800        let result = storage.get_session("no_such_session").await.unwrap();
1801        assert!(result.is_none());
1802    }
1803
1804    #[tokio::test]
1805    async fn test_list_user_sessions() {
1806        let storage = MemoryStorage::new();
1807
1808        let s1 = SessionData::new("s1", "alice", Duration::from_secs(3600));
1809        let s2 = SessionData::new("s2", "alice", Duration::from_secs(3600));
1810        let s3 = SessionData::new("s3", "bob", Duration::from_secs(3600));
1811
1812        storage.store_session("s1", &s1).await.unwrap();
1813        storage.store_session("s2", &s2).await.unwrap();
1814        storage.store_session("s3", &s3).await.unwrap();
1815
1816        let alice_sessions = storage.list_user_sessions("alice").await.unwrap();
1817        assert_eq!(alice_sessions.len(), 2);
1818
1819        let bob_sessions = storage.list_user_sessions("bob").await.unwrap();
1820        assert_eq!(bob_sessions.len(), 1);
1821    }
1822
1823    #[tokio::test]
1824    async fn test_count_active_sessions() {
1825        let storage = MemoryStorage::new();
1826
1827        let s1 = SessionData::new("cs1", "u1", Duration::from_secs(3600));
1828        let s2 = SessionData::new("cs2", "u2", Duration::from_secs(3600));
1829        storage.store_session("cs1", &s1).await.unwrap();
1830        storage.store_session("cs2", &s2).await.unwrap();
1831
1832        let count = storage.count_active_sessions().await.unwrap();
1833        assert!(count >= 2);
1834    }
1835
1836    #[tokio::test]
1837    async fn test_store_sessions_bulk() {
1838        let storage = MemoryStorage::new();
1839        let sessions = vec![
1840            (
1841                "bs1".to_string(),
1842                SessionData::new("bs1", "u1", Duration::from_secs(3600)),
1843            ),
1844            (
1845                "bs2".to_string(),
1846                SessionData::new("bs2", "u2", Duration::from_secs(3600)),
1847            ),
1848        ];
1849
1850        storage.store_sessions_bulk(&sessions).await.unwrap();
1851        assert!(storage.get_session("bs1").await.unwrap().is_some());
1852        assert!(storage.get_session("bs2").await.unwrap().is_some());
1853
1854        let ids = vec!["bs1".to_string(), "bs2".to_string()];
1855        storage.delete_sessions_bulk(&ids).await.unwrap();
1856        assert!(storage.get_session("bs1").await.unwrap().is_none());
1857        assert!(storage.get_session("bs2").await.unwrap().is_none());
1858    }
1859
1860    #[tokio::test]
1861    async fn test_session_custom_data() {
1862        let storage = MemoryStorage::new();
1863        let mut session = SessionData::new("sd1", "u1", Duration::from_secs(3600));
1864        session.set_data("theme", serde_json::json!("dark"));
1865        session.set_data("lang", serde_json::json!("en"));
1866
1867        storage.store_session("sd1", &session).await.unwrap();
1868
1869        let retrieved = storage.get_session("sd1").await.unwrap().unwrap();
1870        assert_eq!(
1871            retrieved.get_data("theme"),
1872            Some(&serde_json::json!("dark"))
1873        );
1874        assert_eq!(retrieved.get_data("lang"), Some(&serde_json::json!("en")));
1875        assert_eq!(retrieved.get_data("missing"), None);
1876    }
1877
1878    // ── KV Storage ──────────────────────────────────────────────────
1879
1880    #[tokio::test]
1881    async fn test_kv_storage() {
1882        let storage = MemoryStorage::new();
1883
1884        let key = "test_key";
1885        let value = b"test_value";
1886
1887        storage
1888            .store_kv(key, value, Some(Duration::from_secs(3600)))
1889            .await
1890            .unwrap();
1891
1892        let retrieved = storage.get_kv(key).await.unwrap().unwrap();
1893        assert_eq!(retrieved, value);
1894
1895        storage.delete_kv(key).await.unwrap();
1896        let retrieved = storage.get_kv(key).await.unwrap();
1897        assert!(retrieved.is_none());
1898    }
1899
1900    #[tokio::test]
1901    async fn test_kv_no_ttl() {
1902        let storage = MemoryStorage::new();
1903        storage
1904            .store_kv("persistent", b"forever", None)
1905            .await
1906            .unwrap();
1907
1908        let retrieved = storage.get_kv("persistent").await.unwrap().unwrap();
1909        assert_eq!(retrieved, b"forever");
1910    }
1911
1912    #[tokio::test]
1913    async fn test_kv_overwrite() {
1914        let storage = MemoryStorage::new();
1915        storage
1916            .store_kv("k1", b"v1", Some(Duration::from_secs(3600)))
1917            .await
1918            .unwrap();
1919        storage
1920            .store_kv("k1", b"v2", Some(Duration::from_secs(3600)))
1921            .await
1922            .unwrap();
1923
1924        let retrieved = storage.get_kv("k1").await.unwrap().unwrap();
1925        assert_eq!(retrieved, b"v2");
1926    }
1927
1928    #[tokio::test]
1929    async fn test_kv_get_nonexistent() {
1930        let storage = MemoryStorage::new();
1931        let result = storage.get_kv("no_such_key").await.unwrap();
1932        assert!(result.is_none());
1933    }
1934
1935    #[tokio::test]
1936    async fn test_kv_list_keys_prefix() {
1937        let storage = MemoryStorage::new();
1938        storage
1939            .store_kv("user:1:name", b"alice", None)
1940            .await
1941            .unwrap();
1942        storage
1943            .store_kv("user:1:email", b"alice@x.com", None)
1944            .await
1945            .unwrap();
1946        storage.store_kv("user:2:name", b"bob", None).await.unwrap();
1947        storage
1948            .store_kv("session:abc", b"data", None)
1949            .await
1950            .unwrap();
1951
1952        let user1_keys = storage.list_kv_keys("user:1:").await.unwrap();
1953        assert_eq!(user1_keys.len(), 2);
1954
1955        let all_user_keys = storage.list_kv_keys("user:").await.unwrap();
1956        assert_eq!(all_user_keys.len(), 3);
1957
1958        let session_keys = storage.list_kv_keys("session:").await.unwrap();
1959        assert_eq!(session_keys.len(), 1);
1960
1961        let empty = storage.list_kv_keys("nonexistent:").await.unwrap();
1962        assert!(empty.is_empty());
1963    }
1964
1965    #[tokio::test]
1966    async fn test_kv_binary_data() {
1967        let storage = MemoryStorage::new();
1968        let binary = vec![0u8, 1, 2, 255, 254, 253, 0, 128];
1969        storage.store_kv("binary_key", &binary, None).await.unwrap();
1970
1971        let retrieved = storage.get_kv("binary_key").await.unwrap().unwrap();
1972        assert_eq!(retrieved, binary);
1973    }
1974
1975    // ── Cleanup ──────────────────────────────────────────────────────
1976
1977    #[tokio::test]
1978    async fn test_cleanup_expired() {
1979        let storage = MemoryStorage::new();
1980
1981        // Store a KV entry with a very short TTL (already expired by the time
1982        // cleanup runs because DashMap wraps its own expiry clock).
1983        // Note: MemoryStorage cleanup uses TimestampedToken's own expires_at
1984        // (derived from default_ttl), NOT AuthToken.expires_at. We test KV
1985        // cleanup because it respects TTLs directly.
1986        storage
1987            .store_kv("expire_me", b"val", Some(Duration::from_secs(0)))
1988            .await
1989            .unwrap();
1990        storage
1991            .store_kv("keep_me", b"val", Some(Duration::from_secs(3600)))
1992            .await
1993            .unwrap();
1994
1995        // Give a tiny window for the zero-TTL entry to register as expired
1996        tokio::time::sleep(Duration::from_millis(10)).await;
1997
1998        storage.cleanup_expired().await.unwrap();
1999
2000        // Zero-TTL entry should be cleaned up, valid entry remains
2001        assert!(storage.get_kv("expire_me").await.unwrap().is_none());
2002        assert!(storage.get_kv("keep_me").await.unwrap().is_some());
2003    }
2004
2005    // ── Session expiration ──────────────────────────────────────────
2006
2007    #[tokio::test]
2008    async fn test_session_is_expired() {
2009        let mut session = SessionData::new("exp1", "u1", Duration::from_secs(3600));
2010        assert!(!session.is_expired());
2011
2012        session.expires_at = chrono::Utc::now() - chrono::Duration::seconds(1);
2013        assert!(session.is_expired());
2014    }
2015
2016    #[tokio::test]
2017    async fn test_session_update_activity() {
2018        let mut session = SessionData::new("act1", "u1", Duration::from_secs(3600));
2019        let first_activity = session.last_activity;
2020        // Small delay to ensure timestamp changes
2021        session.update_activity();
2022        assert!(session.last_activity >= first_activity);
2023    }
2024
2025    // ── Token upsert semantics ──────────────────────────────────────
2026
2027    #[tokio::test]
2028    async fn test_token_store_twice_overwrites_primary() {
2029        let storage = MemoryStorage::new();
2030        let token = AuthToken::new("u1", "at1", Duration::from_secs(3600), "pw");
2031        let token_id = token.token_id.clone();
2032
2033        storage.store_token(&token).await.unwrap();
2034        storage.store_token(&token).await.unwrap();
2035
2036        // Primary DashMap uses insert() so only one entry with this token_id exists.
2037        let got = storage.get_token(&token_id).await.unwrap();
2038        assert!(got.is_some());
2039    }
2040
2041    // ── Delete idempotency ──────────────────────────────────────────
2042
2043    #[tokio::test]
2044    async fn test_delete_nonexistent_token() {
2045        let storage = MemoryStorage::new();
2046        // Deleting a key that doesn't exist should not error
2047        let result = storage.delete_token("nope").await;
2048        assert!(result.is_ok());
2049    }
2050
2051    #[tokio::test]
2052    async fn test_delete_nonexistent_session() {
2053        let storage = MemoryStorage::new();
2054        let result = storage.delete_session("nope").await;
2055        assert!(result.is_ok());
2056    }
2057
2058    #[tokio::test]
2059    async fn test_delete_nonexistent_kv() {
2060        let storage = MemoryStorage::new();
2061        let result = storage.delete_kv("nope").await;
2062        assert!(result.is_ok());
2063    }
2064}