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(Debug, 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
451/// In-memory storage implementation (for development/testing only).
452///
453/// # ⚠️ Production Unsuitability
454///
455/// This implementation is NOT recommended for production use:
456/// - **Data Loss**: All stored tokens and sessions are lost on process restart
457/// - **Memory Growth**: No automatic cleanup; memory usage grows unbounded
458/// - **TTL Ignored**: Expiration times are not enforced; expired tokens may be returned
459/// - **Single Instance**: Cannot be used in multi-instance deployments
460/// - **No Persistence**: No option to back up or export data
461///
462/// Use `PostgresStorage`, `RedisStorage`, or `SqliteStorage` for production.
463///
464/// SECURITY UPDATE: Now uses DashMap for deadlock-free concurrent operations
465#[derive(Debug, Clone)]
466pub struct MemoryStorage {
467    // Primary storage using DashMap for deadlock-free operations
468    inner: crate::storage::dashmap_memory::DashMapMemoryStorage,
469    // RBAC storage still uses RwLock for compatibility (lower concurrency requirements)
470    roles: Arc<RwLock<HashMap<String, crate::authorization::AbacRole>>>,
471    user_roles: Arc<RwLock<Vec<crate::authorization::UserRole>>>,
472}
473
474/// Serialises the in-process swaps below (all instances: swaps are rare, so one lock is enough).
475static IN_PROCESS_SWAP_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
476
477/// [`AuthStorage::swap_kv`] for the in-process backends, which have no transaction: under one lock
478/// shared by every swap it checks that a `remove` key is live, stores the new key if absent (a
479/// refusal or an error leaves the removed keys untouched), then deletes the removed keys.
480///
481/// Atomic with respect to other swaps and to claims made with `store_kv_if_absent`; a concurrent
482/// reader may see both keys in the instant between the store and the deletes.
483pub(crate) async fn swap_kv_in_process<S: AuthStorage + ?Sized>(
484    storage: &S,
485    remove: &[String],
486    key: &str,
487    value: &[u8],
488    ttl: Option<Duration>,
489) -> Result<bool> {
490    let _guard = IN_PROCESS_SWAP_LOCK.lock().await;
491    let mut any_live = false;
492    for name in remove {
493        if storage.get_kv(name).await?.is_some() {
494            any_live = true;
495            break;
496        }
497    }
498    if !any_live || !storage.store_kv_if_absent(key, value, ttl).await? {
499        return Ok(false);
500    }
501    for name in remove {
502        storage.delete_kv(name).await?;
503    }
504    Ok(true)
505}
506
507/// Redis storage implementation.
508#[cfg(feature = "redis-storage")]
509#[derive(Debug, Clone)]
510pub struct RedisStorage {
511    client: redis::Client,
512    key_prefix: String,
513}
514
515impl Default for MemoryStorage {
516    fn default() -> Self {
517        Self::new()
518    }
519}
520
521impl MemoryStorage {
522    /// Create a new in-memory storage.
523    pub fn new() -> Self {
524        Self {
525            inner: crate::storage::dashmap_memory::DashMapMemoryStorage::new(),
526            roles: Arc::new(RwLock::new(HashMap::new())),
527            user_roles: Arc::new(RwLock::new(Vec::new())),
528        }
529    }
530}
531// In-memory AuthorizationStorage implementation for RBAC examples
532#[async_trait::async_trait]
533impl crate::authorization::AuthorizationStorage for MemoryStorage {
534    async fn store_role(&self, role: &crate::authorization::AbacRole) -> crate::errors::Result<()> {
535        let mut roles = self.roles.write().map_err(|_| {
536            crate::errors::AuthError::internal(
537                "Lock poisoned — a prior thread panicked while holding this lock",
538            )
539        })?;
540        roles.insert(role.id.clone(), role.clone());
541        Ok(())
542    }
543
544    async fn get_role(
545        &self,
546        role_id: &str,
547    ) -> crate::errors::Result<Option<crate::authorization::AbacRole>> {
548        let roles = self.roles.read().map_err(|_| {
549            crate::errors::AuthError::internal(
550                "Lock poisoned — a prior thread panicked while holding this lock",
551            )
552        })?;
553        Ok(roles.get(role_id).cloned())
554    }
555
556    async fn update_role(
557        &self,
558        role: &crate::authorization::AbacRole,
559    ) -> crate::errors::Result<()> {
560        let mut roles = self.roles.write().map_err(|_| {
561            crate::errors::AuthError::internal(
562                "Lock poisoned — a prior thread panicked while holding this lock",
563            )
564        })?;
565        roles.insert(role.id.clone(), role.clone());
566        Ok(())
567    }
568
569    async fn delete_role(&self, role_id: &str) -> crate::errors::Result<()> {
570        let mut roles = self.roles.write().map_err(|_| {
571            crate::errors::AuthError::internal(
572                "Lock poisoned — a prior thread panicked while holding this lock",
573            )
574        })?;
575        roles.remove(role_id);
576        Ok(())
577    }
578
579    async fn list_roles(&self) -> crate::errors::Result<Vec<crate::authorization::AbacRole>> {
580        let roles = self.roles.read().map_err(|_| {
581            crate::errors::AuthError::internal(
582                "Lock poisoned — a prior thread panicked while holding this lock",
583            )
584        })?;
585        Ok(roles.values().cloned().collect())
586    }
587
588    async fn assign_role(
589        &self,
590        user_role: &crate::authorization::UserRole,
591    ) -> crate::errors::Result<()> {
592        let mut user_roles = self.user_roles.write().map_err(|_| {
593            crate::errors::AuthError::internal(
594                "Lock poisoned — a prior thread panicked while holding this lock",
595            )
596        })?;
597        user_roles.push(user_role.clone());
598        Ok(())
599    }
600
601    async fn remove_role(&self, user_id: &str, role_id: &str) -> crate::errors::Result<()> {
602        let mut user_roles = self.user_roles.write().map_err(|_| {
603            crate::errors::AuthError::internal(
604                "Lock poisoned — a prior thread panicked while holding this lock",
605            )
606        })?;
607        user_roles.retain(|ur| ur.user_id != user_id || ur.role_id != role_id);
608        Ok(())
609    }
610
611    async fn get_user_roles(
612        &self,
613        user_id: &str,
614    ) -> crate::errors::Result<Vec<crate::authorization::UserRole>> {
615        let user_roles = self.user_roles.read().map_err(|_| {
616            crate::errors::AuthError::internal(
617                "Lock poisoned — a prior thread panicked while holding this lock",
618            )
619        })?;
620        Ok(user_roles
621            .iter()
622            .filter(|ur| ur.user_id == user_id)
623            .cloned()
624            .collect())
625    }
626
627    async fn get_role_users(
628        &self,
629        role_id: &str,
630    ) -> crate::errors::Result<Vec<crate::authorization::UserRole>> {
631        let user_roles = self.user_roles.read().map_err(|_| {
632            crate::errors::AuthError::internal(
633                "Lock poisoned — a prior thread panicked while holding this lock",
634            )
635        })?;
636        Ok(user_roles
637            .iter()
638            .filter(|ur| ur.role_id == role_id)
639            .cloned()
640            .collect())
641    }
642}
643
644#[async_trait]
645impl AuthStorage for MemoryStorage {
646    async fn store_token(&self, token: &AuthToken) -> Result<()> {
647        // Delegate to DashMap implementation for deadlock-free operations
648        self.inner.store_token(token).await
649    }
650
651    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>> {
652        // Delegate to DashMap implementation for deadlock-free operations
653        self.inner.get_token(token_id).await
654    }
655
656    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>> {
657        // Delegate to DashMap implementation for deadlock-free operations
658        self.inner.get_token_by_access_token(access_token).await
659    }
660
661    async fn update_token(&self, token: &AuthToken) -> Result<()> {
662        // Delegate to DashMap implementation for deadlock-free operations
663        self.inner.update_token(token).await
664    }
665
666    async fn delete_token(&self, token_id: &str) -> Result<()> {
667        // Delegate to DashMap implementation for deadlock-free operations
668        self.inner.delete_token(token_id).await
669    }
670
671    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
672        // Delegate to DashMap implementation for deadlock-free operations
673        self.inner.list_user_tokens(user_id).await
674    }
675
676    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()> {
677        // Delegate to DashMap implementation for deadlock-free operations
678        self.inner.store_session(session_id, data).await
679    }
680
681    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
682        // Delegate to DashMap implementation for deadlock-free operations
683        self.inner.get_session(session_id).await
684    }
685
686    async fn delete_session(&self, session_id: &str) -> Result<()> {
687        // Delegate to DashMap implementation for deadlock-free operations
688        self.inner.delete_session(session_id).await
689    }
690
691    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> {
692        // Delegate to DashMap implementation for deadlock-free operations
693        self.inner.list_user_sessions(user_id).await
694    }
695
696    async fn count_active_sessions(&self) -> Result<u64> {
697        // Delegate to DashMap implementation for deadlock-free operations
698        self.inner.count_active_sessions().await
699    }
700
701    async fn store_kv(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()> {
702        // Delegate to DashMap implementation for deadlock-free operations
703        self.inner.store_kv(key, value, ttl).await
704    }
705
706    async fn store_kv_if_absent(
707        &self,
708        key: &str,
709        value: &[u8],
710        ttl: Option<Duration>,
711    ) -> Result<bool> {
712        self.inner.store_kv_if_absent(key, value, ttl).await
713    }
714
715    async fn swap_kv(
716        &self,
717        remove: &[String],
718        key: &str,
719        value: &[u8],
720        ttl: Option<Duration>,
721    ) -> Result<bool> {
722        self.inner.swap_kv(remove, key, value, ttl).await
723    }
724
725    fn supports_atomic_swap(&self) -> bool {
726        self.inner.supports_atomic_swap()
727    }
728
729    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
730        // Delegate to DashMap implementation for deadlock-free operations
731        self.inner.get_kv(key).await
732    }
733
734    async fn get_kv_ttl(&self, key: &str) -> Result<Option<Duration>> {
735        self.inner.get_kv_ttl(key).await
736    }
737
738    fn tracks_kv_ttl(&self) -> bool {
739        self.inner.tracks_kv_ttl()
740    }
741
742    async fn delete_kv(&self, key: &str) -> Result<()> {
743        // Delegate to DashMap implementation for deadlock-free operations
744        self.inner.delete_kv(key).await
745    }
746
747    async fn list_kv_keys(&self, prefix: &str) -> Result<Vec<String>> {
748        Ok(self.inner.list_kv_keys_by_prefix(prefix))
749    }
750
751    async fn cleanup_expired(&self) -> Result<()> {
752        // Delegate to DashMap implementation for deadlock-free operations
753        self.inner.cleanup_expired().await
754    }
755}
756
757#[cfg(feature = "redis-storage")]
758impl RedisStorage {
759    /// Create a new Redis storage.
760    pub fn new(redis_url: &str, key_prefix: impl Into<String>) -> Result<Self> {
761        let client = redis::Client::open(redis_url).map_err(|e| {
762            StorageError::connection_failed(format!("Redis connection failed: {e}"))
763        })?;
764
765        Ok(Self {
766            client,
767            key_prefix: key_prefix.into(),
768        })
769    }
770
771    /// Get a Redis connection.
772    async fn get_connection(&self) -> Result<redis::aio::MultiplexedConnection> {
773        self.client
774            .get_multiplexed_async_connection()
775            .await
776            .map_err(|e| {
777                StorageError::connection_failed(format!("Failed to get Redis connection: {e}"))
778                    .into()
779            })
780    }
781
782    /// Generate a key with the configured prefix.
783    fn key(&self, suffix: &str) -> String {
784        format!("{}{}", self.key_prefix, suffix)
785    }
786
787    /// Key of the access-token -> token-id mapping. The raw access token is a
788    /// bearer credential and is never used as a key name (see
789    /// [`crate::storage::key_names`]).
790    fn access_mapping_key(&self, access_token: &str) -> String {
791        self.key(&format!(
792            "access_token_h:{}",
793            crate::storage::key_names::digest("access_token", access_token)
794        ))
795    }
796
797    /// The pre-fix name, kept only to read-and-migrate or delete old rows.
798    fn legacy_access_mapping_key(&self, access_token: &str) -> String {
799        self.key(&format!("access_token:{access_token}"))
800    }
801
802    /// Key of a session record; the session id is a bearer credential.
803    fn session_key(&self, session_id: &str) -> String {
804        self.key(&format!(
805            "session_h:{}",
806            crate::storage::key_names::digest("session", session_id)
807        ))
808    }
809
810    /// The pre-fix name, kept only to read-and-migrate or delete old rows.
811    fn legacy_session_key(&self, session_id: &str) -> String {
812        self.key(&format!("session:{session_id}"))
813    }
814
815    /// Every session key, under the digest name and under the legacy name.
816    /// Two exact-prefix patterns, so nothing else sharing the key prefix
817    /// matches. A session present under both names (a crash between the two
818    /// writes of a store) is returned under both names; `count_active_sessions`
819    /// counts it once.
820    async fn session_keys(
821        &self,
822        conn: &mut redis::aio::MultiplexedConnection,
823    ) -> Result<Vec<String>> {
824        let mut keys = Vec::new();
825        for pattern in [self.key("session_h:*"), self.key("session:*")] {
826            let found: Vec<String> = redis::cmd("KEYS")
827                .arg(&pattern)
828                .query_async(&mut *conn)
829                .await
830                .map_err(|e| {
831                    StorageError::operation_failed(format!("Failed to scan sessions: {e}"))
832                })?;
833            keys.extend(found);
834        }
835        Ok(keys)
836    }
837
838    /// Read `new_key`; on a miss, move a row stored under `legacy_key` (the raw
839    /// credential name used before digest naming) to `new_key`, keeping its
840    /// remaining lifetime, and return it.
841    async fn get_migrating(&self, new_key: &str, legacy_key: &str) -> Result<Option<String>> {
842        let mut conn = self.get_connection().await?;
843        // Plain read first: it needs no scripting permission, and a digest-named
844        // row is the common case.
845        let value: Option<String> = redis::cmd("GET")
846            .arg(new_key)
847            .query_async(&mut conn)
848            .await
849            .map_err(|e| StorageError::operation_failed(format!("Failed to read key: {e}")))?;
850        if value.is_some() {
851            // A legacy twin can only be left by an interrupted write and still
852            // holds the raw id in its name: drop it (best effort).
853            let _ = redis::cmd("DEL")
854                .arg(legacy_key)
855                .query_async::<usize>(&mut conn)
856                .await;
857            return Ok(value);
858        }
859        // One Lua script, so a concurrent store or delete cannot interleave with the
860        // move: it never overwrites a row already at `new_key` and never recreates
861        // a row that was deleted.
862        const MIGRATE: &str = r#"
863            local l = redis.call('GET', KEYS[2])
864            if not l then return redis.call('GET', KEYS[1]) end
865            local v = redis.call('GET', KEYS[1])
866            if v then
867                redis.call('DEL', KEYS[2])
868                return v
869            end
870            local t = redis.call('PTTL', KEYS[2])
871            if t > 0 then
872                redis.call('SET', KEYS[1], l, 'PX', t)
873            elseif t == -1 then
874                redis.call('SET', KEYS[1], l)
875            else
876                return false
877            end
878            redis.call('DEL', KEYS[2])
879            return l
880        "#;
881        match redis::Script::new(MIGRATE)
882            .key(new_key)
883            .key(legacy_key)
884            .invoke_async::<Option<String>>(&mut conn)
885            .await
886        {
887            Ok(value) => Ok(value),
888            Err(script_err) => {
889                // Scripting denied (restricted ACL) or unavailable: serve the row
890                // where it is. It moves once scripts are allowed or the record is
891                // rewritten.
892                tracing::warn!(
893                    error = %script_err,
894                    "legacy-name migration script failed; serving the row unmigrated"
895                );
896                let legacy: Option<String> = redis::cmd("GET")
897                    .arg(legacy_key)
898                    .query_async(&mut conn)
899                    .await
900                    .map_err(|e| {
901                        StorageError::operation_failed(format!("Failed to read key: {e}"))
902                    })?;
903                Ok(legacy)
904            }
905        }
906    }
907
908    /// Delete a key left under a pre-fix (raw credential) name, if any.
909    async fn del_legacy(&self, legacy_key: &str) -> Result<()> {
910        let mut conn = self.get_connection().await?;
911        let _: () = redis::cmd("DEL")
912            .arg(legacy_key)
913            .query_async(&mut conn)
914            .await
915            .map_err(|e| {
916                StorageError::operation_failed(format!("Failed to remove legacy key: {e}"))
917            })?;
918        Ok(())
919    }
920}
921
922#[cfg(feature = "redis-storage")]
923#[async_trait]
924impl AuthStorage for RedisStorage {
925    async fn store_token(&self, token: &AuthToken) -> Result<()> {
926        let mut conn = self.get_connection().await?;
927        let token_json = serde_json::to_string(token)
928            .map_err(|e| StorageError::serialization(format!("Token serialization failed: {e}")))?;
929
930        let token_key = self.key(&format!("token:{}", token.token_id));
931        let access_token_key = self.access_mapping_key(&token.access_token);
932        let user_tokens_key = self.key(&format!("user_tokens:{}", token.user_id));
933
934        // Calculate TTL
935        let ttl = token.time_until_expiry().as_secs().max(1);
936
937        // Store token data
938        let _: () = redis::cmd("SETEX")
939            .arg(&token_key)
940            .arg(ttl)
941            .arg(&token_json)
942            .query_async(&mut conn)
943            .await
944            .map_err(|e| StorageError::operation_failed(format!("Failed to store token: {e}")))?;
945
946        // Store access token mapping
947        let _: () = redis::cmd("SETEX")
948            .arg(&access_token_key)
949            .arg(ttl)
950            .arg(&token.token_id)
951            .query_async(&mut conn)
952            .await
953            .map_err(|e| {
954                StorageError::operation_failed(format!("Failed to store access token mapping: {e}"))
955            })?;
956
957        // Drop a mapping left under the pre-fix name (it held the raw token).
958        self.del_legacy(&self.legacy_access_mapping_key(&token.access_token))
959            .await?;
960
961        // Add to user tokens set
962        let _: () = redis::cmd("SADD")
963            .arg(&user_tokens_key)
964            .arg(&token.token_id)
965            .query_async(&mut conn)
966            .await
967            .map_err(|e| {
968                StorageError::operation_failed(format!("Failed to add token to user set: {e}"))
969            })?;
970
971        Ok(())
972    }
973
974    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>> {
975        let mut conn = self.get_connection().await?;
976        let token_key = self.key(&format!("token:{token_id}"));
977
978        let token_json: Option<String> = redis::cmd("GET")
979            .arg(&token_key)
980            .query_async(&mut conn)
981            .await
982            .map_err(|e| StorageError::operation_failed(format!("Failed to get token: {e}")))?;
983
984        if let Some(json) = token_json {
985            let token: AuthToken = serde_json::from_str(&json).map_err(|e| {
986                StorageError::serialization(format!("Token deserialization failed: {e}"))
987            })?;
988            Ok(Some(token))
989        } else {
990            Ok(None)
991        }
992    }
993
994    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>> {
995        let token_id = self
996            .get_migrating(
997                &self.access_mapping_key(access_token),
998                &self.legacy_access_mapping_key(access_token),
999            )
1000            .await?;
1001
1002        if let Some(token_id) = token_id {
1003            self.get_token(&token_id).await
1004        } else {
1005            Ok(None)
1006        }
1007    }
1008
1009    async fn update_token(&self, token: &AuthToken) -> Result<()> {
1010        // Same as store_token for Redis
1011        self.store_token(token).await
1012    }
1013
1014    async fn delete_token(&self, token_id: &str) -> Result<()> {
1015        let mut conn = self.get_connection().await?;
1016
1017        // Get token first to get access token and user ID
1018        if let Some(token) = self.get_token(token_id).await? {
1019            let token_key = self.key(&format!("token:{token_id}"));
1020            let access_token_key = self.access_mapping_key(&token.access_token);
1021            let user_tokens_key = self.key(&format!("user_tokens:{}", token.user_id));
1022            self.del_legacy(&self.legacy_access_mapping_key(&token.access_token))
1023                .await?;
1024
1025            // Delete token data
1026            let _: () = redis::cmd("DEL")
1027                .arg(&token_key)
1028                .query_async(&mut conn)
1029                .await
1030                .map_err(|e| {
1031                    StorageError::operation_failed(format!("Failed to delete token: {e}"))
1032                })?;
1033
1034            // Delete access token mapping
1035            let _: () = redis::cmd("DEL")
1036                .arg(&access_token_key)
1037                .query_async(&mut conn)
1038                .await
1039                .map_err(|e| {
1040                    StorageError::operation_failed(format!(
1041                        "Failed to delete access token mapping: {e}"
1042                    ))
1043                })?;
1044
1045            // Remove from user tokens set
1046            let _: () = redis::cmd("SREM")
1047                .arg(&user_tokens_key)
1048                .arg(token_id)
1049                .query_async(&mut conn)
1050                .await
1051                .map_err(|e| {
1052                    StorageError::operation_failed(format!(
1053                        "Failed to remove token from user set: {e}"
1054                    ))
1055                })?;
1056        }
1057
1058        Ok(())
1059    }
1060
1061    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
1062        let mut conn = self.get_connection().await?;
1063        let user_tokens_key = self.key(&format!("user_tokens:{user_id}"));
1064
1065        let token_ids: Vec<String> = redis::cmd("SMEMBERS")
1066            .arg(&user_tokens_key)
1067            .query_async(&mut conn)
1068            .await
1069            .map_err(|e| {
1070                StorageError::operation_failed(format!("Failed to get user tokens: {e}"))
1071            })?;
1072
1073        let mut tokens = Vec::new();
1074        for token_id in token_ids {
1075            if let Some(token) = self.get_token(&token_id).await? {
1076                tokens.push(token);
1077            }
1078        }
1079
1080        Ok(tokens)
1081    }
1082
1083    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()> {
1084        let mut conn = self.get_connection().await?;
1085        let session_key = self.session_key(session_id);
1086
1087        let session_json = serde_json::to_string(data).map_err(|e| {
1088            StorageError::serialization(format!("Session serialization failed: {e}"))
1089        })?;
1090
1091        let ttl = (data.expires_at - chrono::Utc::now()).num_seconds().max(1);
1092
1093        let _: () = redis::cmd("SETEX")
1094            .arg(&session_key)
1095            .arg(ttl)
1096            .arg(&session_json)
1097            .query_async(&mut conn)
1098            .await
1099            .map_err(|e| StorageError::operation_failed(format!("Failed to store session: {e}")))?;
1100
1101        // Drop a record left under the pre-fix name (it held the raw session id).
1102        self.del_legacy(&self.legacy_session_key(session_id))
1103            .await?;
1104
1105        Ok(())
1106    }
1107
1108    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
1109        let session_json = self
1110            .get_migrating(
1111                &self.session_key(session_id),
1112                &self.legacy_session_key(session_id),
1113            )
1114            .await?;
1115
1116        if let Some(json) = session_json {
1117            let session: SessionData = serde_json::from_str(&json).map_err(|e| {
1118                StorageError::serialization(format!("Session deserialization failed: {e}"))
1119            })?;
1120            Ok(Some(session))
1121        } else {
1122            Ok(None)
1123        }
1124    }
1125
1126    async fn delete_session(&self, session_id: &str) -> Result<()> {
1127        let mut conn = self.get_connection().await?;
1128        let session_key = self.session_key(session_id);
1129
1130        // Legacy name first: a migration that runs in between then finds no
1131        // legacy row to move, so a deleted session cannot be recreated.
1132        self.del_legacy(&self.legacy_session_key(session_id))
1133            .await?;
1134        let _: () = redis::cmd("DEL")
1135            .arg(&session_key)
1136            .query_async(&mut conn)
1137            .await
1138            .map_err(|e| {
1139                StorageError::operation_failed(format!("Failed to delete session: {e}"))
1140            })?;
1141
1142        Ok(())
1143    }
1144
1145    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> {
1146        let mut conn = self.get_connection().await?;
1147        let keys = self.session_keys(&mut conn).await?;
1148
1149        let mut user_sessions = Vec::new();
1150        let mut seen = std::collections::HashSet::new();
1151
1152        // Check each session to see if it belongs to the user
1153        let legacy_prefix = self.legacy_session_key("");
1154        for key in keys {
1155            // A row still under the pre-fix name is moved to its digest name as
1156            // it is listed, so it stops exposing the raw session id in key names.
1157            let session_json = match key.strip_prefix(&legacy_prefix) {
1158                Some(session_id) => self
1159                    .get_migrating(&self.session_key(session_id), &key)
1160                    .await
1161                    .ok()
1162                    .flatten(),
1163                None => redis::cmd("GET")
1164                    .arg(&key)
1165                    .query_async::<Option<String>>(&mut conn)
1166                    .await
1167                    .ok()
1168                    .flatten(),
1169            };
1170            if let Some(session_json) = session_json
1171                && let Ok(session) = serde_json::from_str::<SessionData>(&session_json)
1172                && session.user_id == user_id
1173                && !session.is_expired()
1174                && seen.insert(session.session_id.clone())
1175            {
1176                user_sessions.push(session);
1177            }
1178        }
1179
1180        Ok(user_sessions)
1181    }
1182
1183    async fn store_kv_if_absent(
1184        &self,
1185        key: &str,
1186        value: &[u8],
1187        ttl: Option<Duration>,
1188    ) -> Result<bool> {
1189        let mut conn = self.get_connection().await?;
1190        let storage_key = self.key(&format!("kv:{key}"));
1191        // SET ... NX [PX ms]: atomic; the reply is OK when set and nil when the key exists.
1192        let mut cmd = redis::cmd("SET");
1193        cmd.arg(&storage_key).arg(value).arg("NX");
1194        if let Some(ttl) = ttl {
1195            let millis = u64::try_from(ttl.as_millis()).unwrap_or(u64::MAX).max(1);
1196            cmd.arg("PX").arg(millis);
1197        }
1198        let reply: Option<String> = cmd.query_async(&mut conn).await.map_err(|e| {
1199            StorageError::operation_failed(format!("Failed to store KV if absent: {e}"))
1200        })?;
1201        Ok(reply.is_some())
1202    }
1203
1204    async fn swap_kv(
1205        &self,
1206        remove: &[String],
1207        key: &str,
1208        value: &[u8],
1209        ttl: Option<Duration>,
1210    ) -> Result<bool> {
1211        if remove.is_empty() {
1212            return Ok(false);
1213        }
1214        let mut conn = self.get_connection().await?;
1215        let script = redis::Script::new(crate::storage::redis::SWAP_KV_SCRIPT);
1216        let mut invocation = script.prepare_invoke();
1217        for name in remove {
1218            invocation.key(self.key(&format!("kv:{name}")));
1219        }
1220        invocation.key(self.key(&format!("kv:{key}")));
1221        let millis = ttl.map_or(0, |d| {
1222            u64::try_from(d.as_millis()).unwrap_or(u64::MAX).max(1)
1223        });
1224        let swapped: i64 = invocation
1225            .arg(value)
1226            .arg(millis)
1227            .invoke_async(&mut conn)
1228            .await
1229            .map_err(|e| StorageError::operation_failed(format!("Failed to swap KV: {e}")))?;
1230        Ok(swapped == 1)
1231    }
1232
1233    fn supports_atomic_swap(&self) -> bool {
1234        true
1235    }
1236
1237    async fn store_kv(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()> {
1238        let mut conn = self.get_connection().await?;
1239        let storage_key = self.key(&format!("kv:{key}"));
1240
1241        if let Some(ttl) = ttl {
1242            // PSETEX, not SETEX: a remaining TTL under one second must not
1243            // become `SETEX key 0 ...`, which Redis rejects.
1244            let millis = u64::try_from(ttl.as_millis()).unwrap_or(u64::MAX).max(1);
1245            let _: () = redis::cmd("PSETEX")
1246                .arg(&storage_key)
1247                .arg(millis)
1248                .arg(value)
1249                .query_async(&mut conn)
1250                .await
1251                .map_err(|e| {
1252                    StorageError::operation_failed(format!("Failed to store KV with TTL: {e}"))
1253                })?;
1254        } else {
1255            let _: () = redis::cmd("SET")
1256                .arg(&storage_key)
1257                .arg(value)
1258                .query_async(&mut conn)
1259                .await
1260                .map_err(|e| StorageError::operation_failed(format!("Failed to store KV: {e}")))?;
1261        }
1262
1263        Ok(())
1264    }
1265
1266    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
1267        let mut conn = self.get_connection().await?;
1268        let storage_key = self.key(&format!("kv:{key}"));
1269
1270        let value: Option<Vec<u8>> = redis::cmd("GET")
1271            .arg(&storage_key)
1272            .query_async(&mut conn)
1273            .await
1274            .map_err(|e| StorageError::operation_failed(format!("Failed to get KV: {e}")))?;
1275
1276        Ok(value)
1277    }
1278
1279    async fn get_kv_ttl(&self, key: &str) -> Result<Option<Duration>> {
1280        let mut conn = self.get_connection().await?;
1281        let storage_key = self.key(&format!("kv:{key}"));
1282
1283        // PTTL: -2 = no such key, -1 = no expiry, otherwise milliseconds left.
1284        let millis: i64 = redis::cmd("PTTL")
1285            .arg(&storage_key)
1286            .query_async(&mut conn)
1287            .await
1288            .map_err(|e| StorageError::operation_failed(format!("Failed to get KV TTL: {e}")))?;
1289
1290        Ok(u64::try_from(millis)
1291            .ok()
1292            .filter(|millis| *millis > 0)
1293            .map(Duration::from_millis))
1294    }
1295
1296    fn tracks_kv_ttl(&self) -> bool {
1297        true
1298    }
1299
1300    async fn delete_kv(&self, key: &str) -> Result<()> {
1301        let mut conn = self.get_connection().await?;
1302        let storage_key = self.key(&format!("kv:{key}"));
1303
1304        let _: () = redis::cmd("DEL")
1305            .arg(&storage_key)
1306            .query_async(&mut conn)
1307            .await
1308            .map_err(|e| StorageError::operation_failed(format!("Failed to delete KV: {e}")))?;
1309
1310        Ok(())
1311    }
1312
1313    async fn list_kv_keys(&self, prefix: &str) -> Result<Vec<String>> {
1314        let mut conn = self.get_connection().await?;
1315        let pattern = self.key(&format!("kv:{prefix}*"));
1316        let keys: Vec<String> = redis::cmd("KEYS")
1317            .arg(&pattern)
1318            .query_async(&mut conn)
1319            .await
1320            .map_err(|e| StorageError::operation_failed(format!("Failed to list KV keys: {e}")))?;
1321
1322        Ok(keys
1323            .into_iter()
1324            .filter_map(|key| key.strip_prefix(&self.key_prefix).map(str::to_string))
1325            .filter_map(|key| key.strip_prefix("kv:").map(str::to_string))
1326            .collect())
1327    }
1328
1329    async fn cleanup_expired(&self) -> Result<()> {
1330        // Redis handles expiration automatically, so this is a no-op
1331        Ok(())
1332    }
1333
1334    async fn count_active_sessions(&self) -> Result<u64> {
1335        let mut conn = self.get_connection().await?;
1336
1337        // Use KEYS to find all session keys (consider SCAN for production with many keys)
1338        let keys = self.session_keys(&mut conn).await?;
1339        // A session present under both names is one session.
1340        let keys = crate::storage::key_names::without_shadowed_legacy(
1341            keys,
1342            &self.legacy_session_key(""),
1343            &self.key("session_h:"),
1344            "session",
1345        );
1346
1347        // Count only non-expired sessions by checking TTL
1348        let mut active_count = 0u64;
1349        for key in keys {
1350            let ttl: i64 = redis::cmd("TTL")
1351                .arg(&key)
1352                .query_async(&mut conn)
1353                .await
1354                .map_err(|e| StorageError::operation_failed(format!("Failed to check TTL: {e}")))?;
1355
1356            // TTL > 0 means key has expiration and is still active
1357            // TTL = -1 means key has no expiration (active)
1358            // TTL = -2 means key doesn't exist (expired)
1359            if ttl > 0 || ttl == -1 {
1360                active_count += 1;
1361            }
1362        }
1363
1364        Ok(active_count)
1365    }
1366}
1367
1368impl SessionData {
1369    /// Create a new session with consistent timestamps.
1370    ///
1371    /// # Arguments
1372    /// * `session_id` - Unique session identifier (typically a UUID)
1373    /// * `user_id` - Associated user ID
1374    /// * `expires_in` - Session lifetime from now
1375    ///
1376    /// Use [`with_metadata`](SessionData::with_metadata) to attach IP and
1377    /// user-agent information after construction.
1378    ///
1379    /// # Panics
1380    /// If `expires_in` conversion to `chrono::Duration` fails catastrophically.
1381    pub fn new(
1382        session_id: impl Into<String>,
1383        user_id: impl Into<String>,
1384        expires_in: Duration,
1385    ) -> Self {
1386        let now = chrono::Utc::now();
1387
1388        Self {
1389            session_id: session_id.into(),
1390            user_id: user_id.into(),
1391            created_at: now,
1392            expires_at: now
1393                + chrono::Duration::from_std(expires_in).unwrap_or(chrono::Duration::hours(1)),
1394            last_activity: now,
1395            ip_address: None,
1396            user_agent: None,
1397            data: HashMap::new(),
1398        }
1399    }
1400
1401    /// Check if the session has expired.
1402    pub fn is_expired(&self) -> bool {
1403        chrono::Utc::now() > self.expires_at
1404    }
1405
1406    /// Return the remaining lifetime of this session.
1407    ///
1408    /// Returns [`Duration::ZERO`](std::time::Duration::ZERO) when the session
1409    /// has already expired.
1410    pub fn time_until_expiry(&self) -> std::time::Duration {
1411        let remaining = self.expires_at - chrono::Utc::now();
1412        remaining.to_std().unwrap_or(std::time::Duration::ZERO)
1413    }
1414
1415    /// Check if the session is still active (not expired).
1416    pub fn is_active(&self) -> bool {
1417        !self.is_expired()
1418    }
1419
1420    /// Update the last activity timestamp.
1421    pub fn update_activity(&mut self) {
1422        self.last_activity = chrono::Utc::now();
1423    }
1424
1425    /// Set session metadata (IP address and user-agent) in one call.
1426    pub fn with_metadata(mut self, ip_address: Option<String>, user_agent: Option<String>) -> Self {
1427        self.ip_address = ip_address;
1428        self.user_agent = user_agent;
1429        self
1430    }
1431
1432    /// Set the client IP address.
1433    pub fn ip_address(mut self, ip: impl Into<String>) -> Self {
1434        self.ip_address = Some(ip.into());
1435        self
1436    }
1437
1438    /// Set the client user-agent string.
1439    pub fn user_agent(mut self, ua: impl Into<String>) -> Self {
1440        self.user_agent = Some(ua.into());
1441        self
1442    }
1443
1444    /// Add a custom data entry (chainable).
1445    pub fn with_data(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
1446        self.data.insert(key.into(), value);
1447        self
1448    }
1449
1450    /// Add custom data to the session.
1451    pub fn set_data(&mut self, key: impl Into<String>, value: serde_json::Value) {
1452        self.data.insert(key.into(), value);
1453    }
1454
1455    /// Get custom data from the session.
1456    pub fn get_data(&self, key: &str) -> Option<&serde_json::Value> {
1457        self.data.get(key)
1458    }
1459}
1460
1461/// Implementation of AuditStorage for MemoryStorage
1462#[async_trait]
1463impl crate::audit::AuditStorage for MemoryStorage {
1464    async fn store_event(&self, event: &crate::audit::AuditEvent) -> Result<()> {
1465        // Store audit event as JSON in KV storage
1466        let json_data = serde_json::to_vec(event).map_err(|e| {
1467            crate::errors::AuthError::internal(format!("Failed to serialize audit event: {}", e))
1468        })?;
1469
1470        let key = format!("audit_event_{}", event.id);
1471        self.store_kv(&key, &json_data, None).await
1472    }
1473
1474    async fn query_events(
1475        &self,
1476        query: &crate::audit::AuditQuery,
1477    ) -> Result<Vec<crate::audit::AuditEvent>> {
1478        // Simple implementation - in production, this would be more efficient
1479        let all_keys = self.list_kv_keys("audit_event_").await?;
1480        let mut events = Vec::new();
1481
1482        for key in all_keys {
1483            if let Some(data) = self.get_kv(&key).await?
1484                && let Ok(event) = serde_json::from_slice::<crate::audit::AuditEvent>(&data)
1485            {
1486                // Apply filters
1487                let mut include = true;
1488
1489                if let Some(ref time_range) = query.time_range
1490                    && (event.timestamp < time_range.start || event.timestamp > time_range.end)
1491                {
1492                    include = false;
1493                }
1494
1495                if let Some(ref event_types) = query.event_types
1496                    && !event_types.contains(&event.event_type)
1497                {
1498                    include = false;
1499                }
1500
1501                if let Some(ref user_id) = query.user_id
1502                    && event.user_id.as_ref() != Some(user_id)
1503                {
1504                    include = false;
1505                }
1506
1507                if include {
1508                    events.push(event);
1509                }
1510            }
1511        }
1512
1513        // Sort and limit
1514        events.sort_by(|a, b| match query.sort_order {
1515            crate::audit::SortOrder::TimestampAsc => a.timestamp.cmp(&b.timestamp),
1516            crate::audit::SortOrder::TimestampDesc => b.timestamp.cmp(&a.timestamp),
1517            crate::audit::SortOrder::RiskLevelDesc => b.risk_level.cmp(&a.risk_level),
1518        });
1519
1520        if let Some(limit) = query.limit {
1521            events.truncate(limit as usize);
1522        }
1523        Ok(events)
1524    }
1525
1526    async fn get_event(&self, event_id: &str) -> Result<Option<crate::audit::AuditEvent>> {
1527        let key = format!("audit_event_{}", event_id);
1528        if let Some(data) = self.get_kv(&key).await? {
1529            let event = serde_json::from_slice(&data).map_err(|e| {
1530                crate::errors::AuthError::internal(format!(
1531                    "Failed to deserialize audit event: {}",
1532                    e
1533                ))
1534            })?;
1535            Ok(Some(event))
1536        } else {
1537            Ok(None)
1538        }
1539    }
1540
1541    async fn count_events(&self, query: &crate::audit::AuditQuery) -> Result<u64> {
1542        let events = self.query_events(query).await?;
1543        Ok(events.len() as u64)
1544    }
1545
1546    async fn delete_old_events(&self, before: std::time::SystemTime) -> Result<u64> {
1547        let all_keys = self.list_kv_keys("audit_event_").await?;
1548        let mut deleted_count = 0;
1549
1550        for key in all_keys {
1551            if let Some(data) = self.get_kv(&key).await?
1552                && let Ok(event) = serde_json::from_slice::<crate::audit::AuditEvent>(&data)
1553                && event.timestamp < before
1554            {
1555                self.delete_kv(&key).await?;
1556                deleted_count += 1;
1557            }
1558        }
1559
1560        Ok(deleted_count)
1561    }
1562
1563    async fn get_statistics(
1564        &self,
1565        query: &crate::audit::StatsQuery,
1566    ) -> Result<crate::audit::AuditStatistics> {
1567        use std::collections::HashMap;
1568
1569        // Pull all events matching the time range in the query.
1570        let audit_query = crate::audit::AuditQuery::builder()
1571            .time_range(query.time_range.start, query.time_range.end)
1572            .sort_order(crate::audit::SortOrder::TimestampAsc)
1573            .build();
1574        let events = self.query_events(&audit_query).await?;
1575        let total_events = events.len() as u64;
1576
1577        let mut event_type_counts: HashMap<String, u64> = HashMap::new();
1578        let mut risk_level_counts: HashMap<String, u64> = HashMap::new();
1579        let mut outcome_counts: HashMap<String, u64> = HashMap::new();
1580
1581        for event in &events {
1582            *event_type_counts
1583                .entry(format!("{:?}", event.event_type))
1584                .or_insert(0) += 1;
1585            *risk_level_counts
1586                .entry(format!("{:?}", event.risk_level))
1587                .or_insert(0) += 1;
1588            *outcome_counts
1589                .entry(format!("{:?}", event.outcome))
1590                .or_insert(0) += 1;
1591        }
1592
1593        Ok(crate::audit::AuditStatistics {
1594            total_events,
1595            event_type_counts,
1596            risk_level_counts,
1597            outcome_counts,
1598            time_series: Vec::new(),
1599            top_users: Vec::new(),
1600            top_ips: Vec::new(),
1601        })
1602    }
1603}
1604
1605impl MemoryStorage {
1606    /// Helper method to list KV keys with a prefix
1607    async fn list_kv_keys(&self, _prefix: &str) -> Result<Vec<String>> {
1608        Ok(self.inner.list_kv_keys_by_prefix(_prefix))
1609    }
1610}
1611
1612/// Implementation of AuditStorage for `Arc<MemoryStorage>`
1613#[async_trait]
1614impl crate::audit::AuditStorage for Arc<MemoryStorage> {
1615    async fn store_event(&self, event: &crate::audit::AuditEvent) -> Result<()> {
1616        self.as_ref().store_event(event).await
1617    }
1618
1619    async fn query_events(
1620        &self,
1621        query: &crate::audit::AuditQuery,
1622    ) -> Result<Vec<crate::audit::AuditEvent>> {
1623        self.as_ref().query_events(query).await
1624    }
1625
1626    async fn get_event(&self, event_id: &str) -> Result<Option<crate::audit::AuditEvent>> {
1627        self.as_ref().get_event(event_id).await
1628    }
1629
1630    async fn count_events(&self, query: &crate::audit::AuditQuery) -> Result<u64> {
1631        self.as_ref().count_events(query).await
1632    }
1633
1634    async fn delete_old_events(&self, before: std::time::SystemTime) -> Result<u64> {
1635        self.as_ref().delete_old_events(before).await
1636    }
1637
1638    async fn get_statistics(
1639        &self,
1640        query: &crate::audit::StatsQuery,
1641    ) -> Result<crate::audit::AuditStatistics> {
1642        self.as_ref().get_statistics(query).await
1643    }
1644}
1645
1646#[cfg(test)]
1647mod tests {
1648    use super::*;
1649    use crate::tokens::AuthToken;
1650
1651    // ── Token CRUD ──────────────────────────────────────────────────
1652
1653    #[tokio::test]
1654    async fn test_memory_storage() {
1655        let storage = MemoryStorage::new();
1656
1657        let token = AuthToken::new("user123", "token123", Duration::from_secs(3600), "test");
1658
1659        storage.store_token(&token).await.unwrap();
1660
1661        let retrieved = storage.get_token(&token.token_id).await.unwrap().unwrap();
1662        assert_eq!(retrieved.user_id, "user123");
1663
1664        let retrieved = storage
1665            .get_token_by_access_token(&token.access_token)
1666            .await
1667            .unwrap()
1668            .unwrap();
1669        assert_eq!(retrieved.token_id, token.token_id);
1670
1671        let user_tokens = storage.list_user_tokens("user123").await.unwrap();
1672        assert_eq!(user_tokens.len(), 1);
1673
1674        storage.delete_token(&token.token_id).await.unwrap();
1675        let retrieved = storage.get_token(&token.token_id).await.unwrap();
1676        assert!(retrieved.is_none());
1677    }
1678
1679    #[tokio::test]
1680    async fn test_token_update() {
1681        let storage = MemoryStorage::new();
1682        let mut token = AuthToken::new("user1", "access_original", Duration::from_secs(3600), "pw");
1683        storage.store_token(&token).await.unwrap();
1684
1685        token.auth_method = "mfa".to_string();
1686        storage.update_token(&token).await.unwrap();
1687
1688        let retrieved = storage.get_token(&token.token_id).await.unwrap().unwrap();
1689        assert_eq!(retrieved.auth_method, "mfa");
1690    }
1691
1692    #[tokio::test]
1693    async fn test_token_get_nonexistent() {
1694        let storage = MemoryStorage::new();
1695        let result = storage.get_token("nonexistent").await.unwrap();
1696        assert!(result.is_none());
1697
1698        let result = storage
1699            .get_token_by_access_token("nonexistent")
1700            .await
1701            .unwrap();
1702        assert!(result.is_none());
1703    }
1704
1705    #[tokio::test]
1706    async fn test_list_user_tokens_multiple() {
1707        let storage = MemoryStorage::new();
1708        let t1 = AuthToken::new("user_a", "at1", Duration::from_secs(3600), "pw");
1709        let t2 = AuthToken::new("user_a", "at2", Duration::from_secs(3600), "pw");
1710        let t3 = AuthToken::new("user_b", "at3", Duration::from_secs(3600), "pw");
1711
1712        storage.store_token(&t1).await.unwrap();
1713        storage.store_token(&t2).await.unwrap();
1714        storage.store_token(&t3).await.unwrap();
1715
1716        let user_a_tokens = storage.list_user_tokens("user_a").await.unwrap();
1717        assert_eq!(user_a_tokens.len(), 2);
1718
1719        let user_b_tokens = storage.list_user_tokens("user_b").await.unwrap();
1720        assert_eq!(user_b_tokens.len(), 1);
1721
1722        let empty = storage.list_user_tokens("nobody").await.unwrap();
1723        assert!(empty.is_empty());
1724    }
1725
1726    #[tokio::test]
1727    async fn test_store_tokens_bulk() {
1728        let storage = MemoryStorage::new();
1729        let tokens = vec![
1730            AuthToken::new("u1", "a1", Duration::from_secs(3600), "pw"),
1731            AuthToken::new("u2", "a2", Duration::from_secs(3600), "pw"),
1732            AuthToken::new("u3", "a3", Duration::from_secs(3600), "pw"),
1733        ];
1734        let ids: Vec<String> = tokens.iter().map(|t| t.token_id.clone()).collect();
1735
1736        storage.store_tokens_bulk(&tokens).await.unwrap();
1737
1738        for id in &ids {
1739            assert!(storage.get_token(id).await.unwrap().is_some());
1740        }
1741
1742        storage.delete_tokens_bulk(&ids).await.unwrap();
1743
1744        for id in &ids {
1745            assert!(storage.get_token(id).await.unwrap().is_none());
1746        }
1747    }
1748
1749    // ── Session CRUD ────────────────────────────────────────────────
1750
1751    #[tokio::test]
1752    async fn test_session_storage() {
1753        let storage = MemoryStorage::new();
1754
1755        let session = SessionData::new("session123", "user123", Duration::from_secs(3600))
1756            .with_metadata(
1757                Some("192.168.1.1".to_string()),
1758                Some("Test Agent".to_string()),
1759            );
1760
1761        storage
1762            .store_session(&session.session_id, &session)
1763            .await
1764            .unwrap();
1765
1766        let retrieved = storage
1767            .get_session(&session.session_id)
1768            .await
1769            .unwrap()
1770            .unwrap();
1771        assert_eq!(retrieved.user_id, "user123");
1772        assert_eq!(retrieved.ip_address, Some("192.168.1.1".to_string()));
1773
1774        storage.delete_session(&session.session_id).await.unwrap();
1775        let retrieved = storage.get_session(&session.session_id).await.unwrap();
1776        assert!(retrieved.is_none());
1777    }
1778
1779    #[tokio::test]
1780    async fn test_session_get_nonexistent() {
1781        let storage = MemoryStorage::new();
1782        let result = storage.get_session("no_such_session").await.unwrap();
1783        assert!(result.is_none());
1784    }
1785
1786    #[tokio::test]
1787    async fn test_list_user_sessions() {
1788        let storage = MemoryStorage::new();
1789
1790        let s1 = SessionData::new("s1", "alice", Duration::from_secs(3600));
1791        let s2 = SessionData::new("s2", "alice", Duration::from_secs(3600));
1792        let s3 = SessionData::new("s3", "bob", Duration::from_secs(3600));
1793
1794        storage.store_session("s1", &s1).await.unwrap();
1795        storage.store_session("s2", &s2).await.unwrap();
1796        storage.store_session("s3", &s3).await.unwrap();
1797
1798        let alice_sessions = storage.list_user_sessions("alice").await.unwrap();
1799        assert_eq!(alice_sessions.len(), 2);
1800
1801        let bob_sessions = storage.list_user_sessions("bob").await.unwrap();
1802        assert_eq!(bob_sessions.len(), 1);
1803    }
1804
1805    #[tokio::test]
1806    async fn test_count_active_sessions() {
1807        let storage = MemoryStorage::new();
1808
1809        let s1 = SessionData::new("cs1", "u1", Duration::from_secs(3600));
1810        let s2 = SessionData::new("cs2", "u2", Duration::from_secs(3600));
1811        storage.store_session("cs1", &s1).await.unwrap();
1812        storage.store_session("cs2", &s2).await.unwrap();
1813
1814        let count = storage.count_active_sessions().await.unwrap();
1815        assert!(count >= 2);
1816    }
1817
1818    #[tokio::test]
1819    async fn test_store_sessions_bulk() {
1820        let storage = MemoryStorage::new();
1821        let sessions = vec![
1822            (
1823                "bs1".to_string(),
1824                SessionData::new("bs1", "u1", Duration::from_secs(3600)),
1825            ),
1826            (
1827                "bs2".to_string(),
1828                SessionData::new("bs2", "u2", Duration::from_secs(3600)),
1829            ),
1830        ];
1831
1832        storage.store_sessions_bulk(&sessions).await.unwrap();
1833        assert!(storage.get_session("bs1").await.unwrap().is_some());
1834        assert!(storage.get_session("bs2").await.unwrap().is_some());
1835
1836        let ids = vec!["bs1".to_string(), "bs2".to_string()];
1837        storage.delete_sessions_bulk(&ids).await.unwrap();
1838        assert!(storage.get_session("bs1").await.unwrap().is_none());
1839        assert!(storage.get_session("bs2").await.unwrap().is_none());
1840    }
1841
1842    #[tokio::test]
1843    async fn test_session_custom_data() {
1844        let storage = MemoryStorage::new();
1845        let mut session = SessionData::new("sd1", "u1", Duration::from_secs(3600));
1846        session.set_data("theme", serde_json::json!("dark"));
1847        session.set_data("lang", serde_json::json!("en"));
1848
1849        storage.store_session("sd1", &session).await.unwrap();
1850
1851        let retrieved = storage.get_session("sd1").await.unwrap().unwrap();
1852        assert_eq!(
1853            retrieved.get_data("theme"),
1854            Some(&serde_json::json!("dark"))
1855        );
1856        assert_eq!(retrieved.get_data("lang"), Some(&serde_json::json!("en")));
1857        assert_eq!(retrieved.get_data("missing"), None);
1858    }
1859
1860    // ── KV Storage ──────────────────────────────────────────────────
1861
1862    #[tokio::test]
1863    async fn test_kv_storage() {
1864        let storage = MemoryStorage::new();
1865
1866        let key = "test_key";
1867        let value = b"test_value";
1868
1869        storage
1870            .store_kv(key, value, Some(Duration::from_secs(3600)))
1871            .await
1872            .unwrap();
1873
1874        let retrieved = storage.get_kv(key).await.unwrap().unwrap();
1875        assert_eq!(retrieved, value);
1876
1877        storage.delete_kv(key).await.unwrap();
1878        let retrieved = storage.get_kv(key).await.unwrap();
1879        assert!(retrieved.is_none());
1880    }
1881
1882    #[tokio::test]
1883    async fn test_kv_no_ttl() {
1884        let storage = MemoryStorage::new();
1885        storage
1886            .store_kv("persistent", b"forever", None)
1887            .await
1888            .unwrap();
1889
1890        let retrieved = storage.get_kv("persistent").await.unwrap().unwrap();
1891        assert_eq!(retrieved, b"forever");
1892    }
1893
1894    #[tokio::test]
1895    async fn test_kv_overwrite() {
1896        let storage = MemoryStorage::new();
1897        storage
1898            .store_kv("k1", b"v1", Some(Duration::from_secs(3600)))
1899            .await
1900            .unwrap();
1901        storage
1902            .store_kv("k1", b"v2", Some(Duration::from_secs(3600)))
1903            .await
1904            .unwrap();
1905
1906        let retrieved = storage.get_kv("k1").await.unwrap().unwrap();
1907        assert_eq!(retrieved, b"v2");
1908    }
1909
1910    #[tokio::test]
1911    async fn test_kv_get_nonexistent() {
1912        let storage = MemoryStorage::new();
1913        let result = storage.get_kv("no_such_key").await.unwrap();
1914        assert!(result.is_none());
1915    }
1916
1917    #[tokio::test]
1918    async fn test_kv_list_keys_prefix() {
1919        let storage = MemoryStorage::new();
1920        storage
1921            .store_kv("user:1:name", b"alice", None)
1922            .await
1923            .unwrap();
1924        storage
1925            .store_kv("user:1:email", b"alice@x.com", None)
1926            .await
1927            .unwrap();
1928        storage.store_kv("user:2:name", b"bob", None).await.unwrap();
1929        storage
1930            .store_kv("session:abc", b"data", None)
1931            .await
1932            .unwrap();
1933
1934        let user1_keys = storage.list_kv_keys("user:1:").await.unwrap();
1935        assert_eq!(user1_keys.len(), 2);
1936
1937        let all_user_keys = storage.list_kv_keys("user:").await.unwrap();
1938        assert_eq!(all_user_keys.len(), 3);
1939
1940        let session_keys = storage.list_kv_keys("session:").await.unwrap();
1941        assert_eq!(session_keys.len(), 1);
1942
1943        let empty = storage.list_kv_keys("nonexistent:").await.unwrap();
1944        assert!(empty.is_empty());
1945    }
1946
1947    #[tokio::test]
1948    async fn test_kv_binary_data() {
1949        let storage = MemoryStorage::new();
1950        let binary = vec![0u8, 1, 2, 255, 254, 253, 0, 128];
1951        storage.store_kv("binary_key", &binary, None).await.unwrap();
1952
1953        let retrieved = storage.get_kv("binary_key").await.unwrap().unwrap();
1954        assert_eq!(retrieved, binary);
1955    }
1956
1957    // ── Cleanup ──────────────────────────────────────────────────────
1958
1959    #[tokio::test]
1960    async fn test_cleanup_expired() {
1961        let storage = MemoryStorage::new();
1962
1963        // Store a KV entry with a very short TTL (already expired by the time
1964        // cleanup runs because DashMap wraps its own expiry clock).
1965        // Note: MemoryStorage cleanup uses TimestampedToken's own expires_at
1966        // (derived from default_ttl), NOT AuthToken.expires_at. We test KV
1967        // cleanup because it respects TTLs directly.
1968        storage
1969            .store_kv("expire_me", b"val", Some(Duration::from_secs(0)))
1970            .await
1971            .unwrap();
1972        storage
1973            .store_kv("keep_me", b"val", Some(Duration::from_secs(3600)))
1974            .await
1975            .unwrap();
1976
1977        // Give a tiny window for the zero-TTL entry to register as expired
1978        tokio::time::sleep(Duration::from_millis(10)).await;
1979
1980        storage.cleanup_expired().await.unwrap();
1981
1982        // Zero-TTL entry should be cleaned up, valid entry remains
1983        assert!(storage.get_kv("expire_me").await.unwrap().is_none());
1984        assert!(storage.get_kv("keep_me").await.unwrap().is_some());
1985    }
1986
1987    // ── Session expiration ──────────────────────────────────────────
1988
1989    #[tokio::test]
1990    async fn test_session_is_expired() {
1991        let mut session = SessionData::new("exp1", "u1", Duration::from_secs(3600));
1992        assert!(!session.is_expired());
1993
1994        session.expires_at = chrono::Utc::now() - chrono::Duration::seconds(1);
1995        assert!(session.is_expired());
1996    }
1997
1998    #[tokio::test]
1999    async fn test_session_update_activity() {
2000        let mut session = SessionData::new("act1", "u1", Duration::from_secs(3600));
2001        let first_activity = session.last_activity;
2002        // Small delay to ensure timestamp changes
2003        session.update_activity();
2004        assert!(session.last_activity >= first_activity);
2005    }
2006
2007    // ── Token upsert semantics ──────────────────────────────────────
2008
2009    #[tokio::test]
2010    async fn test_token_store_twice_overwrites_primary() {
2011        let storage = MemoryStorage::new();
2012        let token = AuthToken::new("u1", "at1", Duration::from_secs(3600), "pw");
2013        let token_id = token.token_id.clone();
2014
2015        storage.store_token(&token).await.unwrap();
2016        storage.store_token(&token).await.unwrap();
2017
2018        // Primary DashMap uses insert() so only one entry with this token_id exists.
2019        let got = storage.get_token(&token_id).await.unwrap();
2020        assert!(got.is_some());
2021    }
2022
2023    // ── Delete idempotency ──────────────────────────────────────────
2024
2025    #[tokio::test]
2026    async fn test_delete_nonexistent_token() {
2027        let storage = MemoryStorage::new();
2028        // Deleting a key that doesn't exist should not error
2029        let result = storage.delete_token("nope").await;
2030        assert!(result.is_ok());
2031    }
2032
2033    #[tokio::test]
2034    async fn test_delete_nonexistent_session() {
2035        let storage = MemoryStorage::new();
2036        let result = storage.delete_session("nope").await;
2037        assert!(result.is_ok());
2038    }
2039
2040    #[tokio::test]
2041    async fn test_delete_nonexistent_kv() {
2042        let storage = MemoryStorage::new();
2043        let result = storage.delete_kv("nope").await;
2044        assert!(result.is_ok());
2045    }
2046}