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.
15#[async_trait]
16pub trait AuthStorage: Send + Sync {
17    /// Bulk store tokens.
18    async fn store_tokens_bulk(&self, tokens: &[AuthToken]) -> Result<()> {
19        for token in tokens {
20            self.store_token(token).await?;
21        }
22        Ok(())
23    }
24
25    /// Bulk delete tokens by ID.
26    async fn delete_tokens_bulk(&self, token_ids: &[String]) -> Result<()> {
27        for token_id in token_ids {
28            self.delete_token(token_id).await?;
29        }
30        Ok(())
31    }
32
33    /// Bulk store sessions.
34    async fn store_sessions_bulk(&self, sessions: &[(String, SessionData)]) -> Result<()> {
35        for (session_id, data) in sessions {
36            self.store_session(session_id, data).await?;
37        }
38        Ok(())
39    }
40
41    /// Bulk delete sessions by ID.
42    async fn delete_sessions_bulk(&self, session_ids: &[String]) -> Result<()> {
43        for session_id in session_ids {
44            self.delete_session(session_id).await?;
45        }
46        Ok(())
47    }
48    /// Store a token.
49    async fn store_token(&self, token: &AuthToken) -> Result<()>;
50
51    /// Retrieve a token by ID.
52    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>>;
53
54    /// Retrieve a token by access token string.
55    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>>;
56
57    /// Update a token.
58    async fn update_token(&self, token: &AuthToken) -> Result<()>;
59
60    /// Delete a token.
61    async fn delete_token(&self, token_id: &str) -> Result<()>;
62
63    /// List all tokens for a user.
64    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>>;
65
66    /// Store session data.
67    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()>;
68
69    /// Retrieve session data.
70    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>>;
71
72    /// Delete session data.
73    async fn delete_session(&self, session_id: &str) -> Result<()>;
74
75    /// List all sessions for a user.
76    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>>;
77
78    /// Count currently active sessions (non-expired)
79    async fn count_active_sessions(&self) -> Result<u64>;
80
81    /// Store arbitrary key-value data with expiration.
82    async fn store_kv(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()>;
83
84    /// Retrieve arbitrary key-value data.
85    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>>;
86
87    /// Delete arbitrary key-value data.
88    async fn delete_kv(&self, key: &str) -> Result<()>;
89
90    /// Clean up expired data.
91    async fn cleanup_expired(&self) -> Result<()>;
92}
93
94/// Session data stored in the backend.
95#[derive(Clone, Serialize, Deserialize)]
96pub struct SessionData {
97    /// Session ID
98    pub session_id: String,
99
100    /// User ID associated with this session
101    pub user_id: String,
102
103    /// When the session was created
104    pub created_at: chrono::DateTime<chrono::Utc>,
105
106    /// When the session expires
107    pub expires_at: chrono::DateTime<chrono::Utc>,
108
109    /// Last activity timestamp
110    pub last_activity: chrono::DateTime<chrono::Utc>,
111
112    /// IP address of the session
113    pub ip_address: Option<String>,
114
115    /// User agent
116    pub user_agent: Option<String>,
117
118    /// Custom session data
119    pub data: HashMap<String, serde_json::Value>,
120}
121
122impl std::fmt::Debug for SessionData {
123    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124        let mut d = f.debug_struct("SessionData");
125        d.field(
126            "session_id",
127            &crate::utils::redact::redacted(&self.session_id),
128        );
129        d.field("user_id", &self.user_id);
130        d.field("created_at", &self.created_at);
131        d.field("expires_at", &self.expires_at);
132        d.field("last_activity", &self.last_activity);
133        d.field("ip_address", &self.ip_address);
134        d.field("user_agent", &self.user_agent);
135        d.field("data", &crate::utils::redact::redacted(&self.data));
136        d.finish()
137    }
138}
139
140/// In-memory storage implementation (for development/testing).
141/// SECURITY UPDATE: Now uses DashMap for deadlock-free concurrent operations
142#[derive(Debug, Clone)]
143pub struct MemoryStorage {
144    // Primary storage using DashMap for deadlock-free operations
145    inner: crate::storage::dashmap_memory::DashMapMemoryStorage,
146    // RBAC storage still uses RwLock for compatibility (lower concurrency requirements)
147    roles: Arc<RwLock<HashMap<String, crate::authorization::Role>>>,
148    user_roles: Arc<RwLock<Vec<crate::authorization::UserRole>>>,
149}
150
151/// Redis storage implementation.
152#[cfg(feature = "redis-storage")]
153#[derive(Debug, Clone)]
154pub struct RedisStorage {
155    client: redis::Client,
156    key_prefix: String,
157}
158
159impl Default for MemoryStorage {
160    fn default() -> Self {
161        Self::new()
162    }
163}
164
165impl MemoryStorage {
166    /// Create a new in-memory storage.
167    pub fn new() -> Self {
168        Self {
169            inner: crate::storage::dashmap_memory::DashMapMemoryStorage::new(),
170            roles: Arc::new(RwLock::new(HashMap::new())),
171            user_roles: Arc::new(RwLock::new(Vec::new())),
172        }
173    }
174}
175// In-memory AuthorizationStorage implementation for RBAC examples
176#[async_trait::async_trait]
177impl crate::authorization::AuthorizationStorage for MemoryStorage {
178    async fn store_role(&self, role: &crate::authorization::Role) -> crate::errors::Result<()> {
179        let mut roles = self.roles.write().unwrap();
180        roles.insert(role.id.clone(), role.clone());
181        Ok(())
182    }
183
184    async fn get_role(
185        &self,
186        role_id: &str,
187    ) -> crate::errors::Result<Option<crate::authorization::Role>> {
188        let roles = self.roles.read().unwrap();
189        Ok(roles.get(role_id).cloned())
190    }
191
192    async fn update_role(&self, role: &crate::authorization::Role) -> crate::errors::Result<()> {
193        let mut roles = self.roles.write().unwrap();
194        roles.insert(role.id.clone(), role.clone());
195        Ok(())
196    }
197
198    async fn delete_role(&self, role_id: &str) -> crate::errors::Result<()> {
199        let mut roles = self.roles.write().unwrap();
200        roles.remove(role_id);
201        Ok(())
202    }
203
204    async fn list_roles(&self) -> crate::errors::Result<Vec<crate::authorization::Role>> {
205        let roles = self.roles.read().unwrap();
206        Ok(roles.values().cloned().collect())
207    }
208
209    async fn assign_role(
210        &self,
211        user_role: &crate::authorization::UserRole,
212    ) -> crate::errors::Result<()> {
213        let mut user_roles = self.user_roles.write().unwrap();
214        user_roles.push(user_role.clone());
215        Ok(())
216    }
217
218    async fn remove_role(&self, user_id: &str, role_id: &str) -> crate::errors::Result<()> {
219        let mut user_roles = self.user_roles.write().unwrap();
220        user_roles.retain(|ur| ur.user_id != user_id || ur.role_id != role_id);
221        Ok(())
222    }
223
224    async fn get_user_roles(
225        &self,
226        user_id: &str,
227    ) -> crate::errors::Result<Vec<crate::authorization::UserRole>> {
228        let user_roles = self.user_roles.read().unwrap();
229        Ok(user_roles
230            .iter()
231            .filter(|ur| ur.user_id == user_id)
232            .cloned()
233            .collect())
234    }
235
236    async fn get_role_users(
237        &self,
238        role_id: &str,
239    ) -> crate::errors::Result<Vec<crate::authorization::UserRole>> {
240        let user_roles = self.user_roles.read().unwrap();
241        Ok(user_roles
242            .iter()
243            .filter(|ur| ur.role_id == role_id)
244            .cloned()
245            .collect())
246    }
247}
248
249#[async_trait]
250impl AuthStorage for MemoryStorage {
251    async fn store_token(&self, token: &AuthToken) -> Result<()> {
252        // Delegate to DashMap implementation for deadlock-free operations
253        self.inner.store_token(token).await
254    }
255
256    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>> {
257        // Delegate to DashMap implementation for deadlock-free operations
258        self.inner.get_token(token_id).await
259    }
260
261    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>> {
262        // Delegate to DashMap implementation for deadlock-free operations
263        self.inner.get_token_by_access_token(access_token).await
264    }
265
266    async fn update_token(&self, token: &AuthToken) -> Result<()> {
267        // Delegate to DashMap implementation for deadlock-free operations
268        self.inner.update_token(token).await
269    }
270
271    async fn delete_token(&self, token_id: &str) -> Result<()> {
272        // Delegate to DashMap implementation for deadlock-free operations
273        self.inner.delete_token(token_id).await
274    }
275
276    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
277        // Delegate to DashMap implementation for deadlock-free operations
278        self.inner.list_user_tokens(user_id).await
279    }
280
281    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()> {
282        // Delegate to DashMap implementation for deadlock-free operations
283        self.inner.store_session(session_id, data).await
284    }
285
286    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
287        // Delegate to DashMap implementation for deadlock-free operations
288        self.inner.get_session(session_id).await
289    }
290
291    async fn delete_session(&self, session_id: &str) -> Result<()> {
292        // Delegate to DashMap implementation for deadlock-free operations
293        self.inner.delete_session(session_id).await
294    }
295
296    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> {
297        // Delegate to DashMap implementation for deadlock-free operations
298        self.inner.list_user_sessions(user_id).await
299    }
300
301    async fn count_active_sessions(&self) -> Result<u64> {
302        // Delegate to DashMap implementation for deadlock-free operations
303        self.inner.count_active_sessions().await
304    }
305
306    async fn store_kv(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()> {
307        // Delegate to DashMap implementation for deadlock-free operations
308        self.inner.store_kv(key, value, ttl).await
309    }
310
311    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
312        // Delegate to DashMap implementation for deadlock-free operations
313        self.inner.get_kv(key).await
314    }
315
316    async fn delete_kv(&self, key: &str) -> Result<()> {
317        // Delegate to DashMap implementation for deadlock-free operations
318        self.inner.delete_kv(key).await
319    }
320
321    async fn cleanup_expired(&self) -> Result<()> {
322        // Delegate to DashMap implementation for deadlock-free operations
323        self.inner.cleanup_expired().await
324    }
325}
326
327#[cfg(feature = "redis-storage")]
328impl RedisStorage {
329    /// Create a new Redis storage.
330    pub fn new(redis_url: &str, key_prefix: impl Into<String>) -> Result<Self> {
331        let client = redis::Client::open(redis_url).map_err(|e| {
332            StorageError::connection_failed(format!("Redis connection failed: {e}"))
333        })?;
334
335        Ok(Self {
336            client,
337            key_prefix: key_prefix.into(),
338        })
339    }
340
341    /// Get a Redis connection.
342    async fn get_connection(&self) -> Result<redis::aio::MultiplexedConnection> {
343        self.client
344            .get_multiplexed_tokio_connection()
345            .await
346            .map_err(|e| {
347                StorageError::connection_failed(format!("Failed to get Redis connection: {e}"))
348                    .into()
349            })
350    }
351
352    /// Generate a key with the configured prefix.
353    fn key(&self, suffix: &str) -> String {
354        format!("{}{}", self.key_prefix, suffix)
355    }
356
357    /// Key of the access-token -> token-id mapping. The raw access token is a
358    /// bearer credential and is never used as a key name (see
359    /// [`crate::storage::key_names`]).
360    fn access_mapping_key(&self, access_token: &str) -> String {
361        self.key(&format!(
362            "access_token_h:{}",
363            crate::storage::key_names::digest("access_token", access_token)
364        ))
365    }
366
367    /// The pre-fix name, kept only to read-and-migrate or delete old rows.
368    fn legacy_access_mapping_key(&self, access_token: &str) -> String {
369        self.key(&format!("access_token:{access_token}"))
370    }
371
372    /// Key of a session record; the session id is a bearer credential.
373    fn session_key(&self, session_id: &str) -> String {
374        self.key(&format!(
375            "session_h:{}",
376            crate::storage::key_names::digest("session", session_id)
377        ))
378    }
379
380    /// The pre-fix name, kept only to read-and-migrate or delete old rows.
381    fn legacy_session_key(&self, session_id: &str) -> String {
382        self.key(&format!("session:{session_id}"))
383    }
384
385    /// Every session key, under the digest name and under the legacy name.
386    /// Two exact-prefix patterns, so nothing else sharing the key prefix
387    /// matches. A session present under both names (a crash between the two
388    /// writes of a store) is returned under both names; `count_active_sessions`
389    /// counts it once.
390    async fn session_keys(
391        &self,
392        conn: &mut redis::aio::MultiplexedConnection,
393    ) -> Result<Vec<String>> {
394        let mut keys = Vec::new();
395        for pattern in [self.key("session_h:*"), self.key("session:*")] {
396            let found: Vec<String> = redis::cmd("KEYS")
397                .arg(&pattern)
398                .query_async(&mut *conn)
399                .await
400                .map_err(|e| {
401                    StorageError::operation_failed(format!("Failed to scan sessions: {e}"))
402                })?;
403            keys.extend(found);
404        }
405        Ok(keys)
406    }
407
408    /// Read `new_key`; on a miss, move a row stored under `legacy_key` (the raw
409    /// credential name used before digest naming) to `new_key`, keeping its
410    /// remaining lifetime, and return it.
411    async fn get_migrating(&self, new_key: &str, legacy_key: &str) -> Result<Option<String>> {
412        let mut conn = self.get_connection().await?;
413        // Plain read first: it needs no scripting permission, and a digest-named
414        // row is the common case.
415        let value: Option<String> = redis::cmd("GET")
416            .arg(new_key)
417            .query_async(&mut conn)
418            .await
419            .map_err(|e| StorageError::operation_failed(format!("Failed to read key: {e}")))?;
420        if value.is_some() {
421            // A legacy twin can only be left by an interrupted write and still
422            // holds the raw id in its name: drop it (best effort).
423            let _ = redis::cmd("DEL")
424                .arg(legacy_key)
425                .query_async::<usize>(&mut conn)
426                .await;
427            return Ok(value);
428        }
429        // One Lua script, so a concurrent store or delete cannot interleave with the
430        // move: it never overwrites a row already at `new_key` and never recreates
431        // a row that was deleted.
432        const MIGRATE: &str = r#"
433            local l = redis.call('GET', KEYS[2])
434            if not l then return redis.call('GET', KEYS[1]) end
435            local v = redis.call('GET', KEYS[1])
436            if v then
437                redis.call('DEL', KEYS[2])
438                return v
439            end
440            local t = redis.call('PTTL', KEYS[2])
441            if t > 0 then
442                redis.call('SET', KEYS[1], l, 'PX', t)
443            elseif t == -1 then
444                redis.call('SET', KEYS[1], l)
445            else
446                return false
447            end
448            redis.call('DEL', KEYS[2])
449            return l
450        "#;
451        match redis::Script::new(MIGRATE)
452            .key(new_key)
453            .key(legacy_key)
454            .invoke_async::<Option<String>>(&mut conn)
455            .await
456        {
457            Ok(value) => Ok(value),
458            Err(script_err) => {
459                // Scripting denied (restricted ACL) or unavailable: serve the row
460                // where it is. It moves once scripts are allowed or the record is
461                // rewritten.
462                tracing::warn!(
463                    error = %script_err,
464                    "legacy-name migration script failed; serving the row unmigrated"
465                );
466                let legacy: Option<String> = redis::cmd("GET")
467                    .arg(legacy_key)
468                    .query_async(&mut conn)
469                    .await
470                    .map_err(|e| {
471                        StorageError::operation_failed(format!("Failed to read key: {e}"))
472                    })?;
473                Ok(legacy)
474            }
475        }
476    }
477
478    /// Delete a key left under a pre-fix (raw credential) name, if any.
479    async fn del_legacy(&self, legacy_key: &str) -> Result<()> {
480        let mut conn = self.get_connection().await?;
481        let _: () = redis::cmd("DEL")
482            .arg(legacy_key)
483            .query_async(&mut conn)
484            .await
485            .map_err(|e| {
486                StorageError::operation_failed(format!("Failed to remove legacy key: {e}"))
487            })?;
488        Ok(())
489    }
490}
491
492#[cfg(feature = "redis-storage")]
493#[async_trait]
494impl AuthStorage for RedisStorage {
495    async fn store_token(&self, token: &AuthToken) -> Result<()> {
496        let mut conn = self.get_connection().await?;
497        let token_json = serde_json::to_string(token)
498            .map_err(|e| StorageError::serialization(format!("Token serialization failed: {e}")))?;
499
500        let token_key = self.key(&format!("token:{}", token.token_id));
501        let access_token_key = self.access_mapping_key(&token.access_token);
502        let user_tokens_key = self.key(&format!("user_tokens:{}", token.user_id));
503
504        // Calculate TTL
505        let ttl = token.time_until_expiry().as_secs().max(1);
506
507        // Store token data
508        let _: () = redis::cmd("SETEX")
509            .arg(&token_key)
510            .arg(ttl)
511            .arg(&token_json)
512            .query_async(&mut conn)
513            .await
514            .map_err(|e| StorageError::operation_failed(format!("Failed to store token: {e}")))?;
515
516        // Store access token mapping
517        let _: () = redis::cmd("SETEX")
518            .arg(&access_token_key)
519            .arg(ttl)
520            .arg(&token.token_id)
521            .query_async(&mut conn)
522            .await
523            .map_err(|e| {
524                StorageError::operation_failed(format!("Failed to store access token mapping: {e}"))
525            })?;
526
527        // Drop a mapping left under the pre-fix name (it held the raw token).
528        self.del_legacy(&self.legacy_access_mapping_key(&token.access_token))
529            .await?;
530
531        // Add to user tokens set
532        let _: () = redis::cmd("SADD")
533            .arg(&user_tokens_key)
534            .arg(&token.token_id)
535            .query_async(&mut conn)
536            .await
537            .map_err(|e| {
538                StorageError::operation_failed(format!("Failed to add token to user set: {e}"))
539            })?;
540
541        Ok(())
542    }
543
544    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>> {
545        let mut conn = self.get_connection().await?;
546        let token_key = self.key(&format!("token:{token_id}"));
547
548        let token_json: Option<String> = redis::cmd("GET")
549            .arg(&token_key)
550            .query_async(&mut conn)
551            .await
552            .map_err(|e| StorageError::operation_failed(format!("Failed to get token: {e}")))?;
553
554        if let Some(json) = token_json {
555            let token: AuthToken = serde_json::from_str(&json).map_err(|e| {
556                StorageError::serialization(format!("Token deserialization failed: {e}"))
557            })?;
558            Ok(Some(token))
559        } else {
560            Ok(None)
561        }
562    }
563
564    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>> {
565        let token_id = self
566            .get_migrating(
567                &self.access_mapping_key(access_token),
568                &self.legacy_access_mapping_key(access_token),
569            )
570            .await?;
571
572        if let Some(token_id) = token_id {
573            self.get_token(&token_id).await
574        } else {
575            Ok(None)
576        }
577    }
578
579    async fn update_token(&self, token: &AuthToken) -> Result<()> {
580        // Same as store_token for Redis
581        self.store_token(token).await
582    }
583
584    async fn delete_token(&self, token_id: &str) -> Result<()> {
585        let mut conn = self.get_connection().await?;
586
587        // Get token first to get access token and user ID
588        if let Some(token) = self.get_token(token_id).await? {
589            let token_key = self.key(&format!("token:{token_id}"));
590            let access_token_key = self.access_mapping_key(&token.access_token);
591            let user_tokens_key = self.key(&format!("user_tokens:{}", token.user_id));
592            self.del_legacy(&self.legacy_access_mapping_key(&token.access_token))
593                .await?;
594
595            // Delete token data
596            let _: () = redis::cmd("DEL")
597                .arg(&token_key)
598                .query_async(&mut conn)
599                .await
600                .map_err(|e| {
601                    StorageError::operation_failed(format!("Failed to delete token: {e}"))
602                })?;
603
604            // Delete access token mapping
605            let _: () = redis::cmd("DEL")
606                .arg(&access_token_key)
607                .query_async(&mut conn)
608                .await
609                .map_err(|e| {
610                    StorageError::operation_failed(format!(
611                        "Failed to delete access token mapping: {e}"
612                    ))
613                })?;
614
615            // Remove from user tokens set
616            let _: () = redis::cmd("SREM")
617                .arg(&user_tokens_key)
618                .arg(token_id)
619                .query_async(&mut conn)
620                .await
621                .map_err(|e| {
622                    StorageError::operation_failed(format!(
623                        "Failed to remove token from user set: {e}"
624                    ))
625                })?;
626        }
627
628        Ok(())
629    }
630
631    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
632        let mut conn = self.get_connection().await?;
633        let user_tokens_key = self.key(&format!("user_tokens:{user_id}"));
634
635        let token_ids: Vec<String> = redis::cmd("SMEMBERS")
636            .arg(&user_tokens_key)
637            .query_async(&mut conn)
638            .await
639            .map_err(|e| {
640                StorageError::operation_failed(format!("Failed to get user tokens: {e}"))
641            })?;
642
643        let mut tokens = Vec::new();
644        for token_id in token_ids {
645            if let Some(token) = self.get_token(&token_id).await? {
646                tokens.push(token);
647            }
648        }
649
650        Ok(tokens)
651    }
652
653    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()> {
654        let mut conn = self.get_connection().await?;
655        let session_key = self.session_key(session_id);
656
657        let session_json = serde_json::to_string(data).map_err(|e| {
658            StorageError::serialization(format!("Session serialization failed: {e}"))
659        })?;
660
661        let ttl = (data.expires_at - chrono::Utc::now()).num_seconds().max(1);
662
663        let _: () = redis::cmd("SETEX")
664            .arg(&session_key)
665            .arg(ttl)
666            .arg(&session_json)
667            .query_async(&mut conn)
668            .await
669            .map_err(|e| StorageError::operation_failed(format!("Failed to store session: {e}")))?;
670
671        // Drop a record left under the pre-fix name (it held the raw session id).
672        self.del_legacy(&self.legacy_session_key(session_id))
673            .await?;
674
675        Ok(())
676    }
677
678    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
679        let session_json = self
680            .get_migrating(
681                &self.session_key(session_id),
682                &self.legacy_session_key(session_id),
683            )
684            .await?;
685
686        if let Some(json) = session_json {
687            let session: SessionData = serde_json::from_str(&json).map_err(|e| {
688                StorageError::serialization(format!("Session deserialization failed: {e}"))
689            })?;
690            Ok(Some(session))
691        } else {
692            Ok(None)
693        }
694    }
695
696    async fn delete_session(&self, session_id: &str) -> Result<()> {
697        let mut conn = self.get_connection().await?;
698        let session_key = self.session_key(session_id);
699
700        // Legacy name first: a migration that runs in between then finds no
701        // legacy row to move, so a deleted session cannot be recreated.
702        self.del_legacy(&self.legacy_session_key(session_id))
703            .await?;
704        let _: () = redis::cmd("DEL")
705            .arg(&session_key)
706            .query_async(&mut conn)
707            .await
708            .map_err(|e| {
709                StorageError::operation_failed(format!("Failed to delete session: {e}"))
710            })?;
711
712        Ok(())
713    }
714
715    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> {
716        let mut conn = self.get_connection().await?;
717        let keys = self.session_keys(&mut conn).await?;
718
719        let mut user_sessions = Vec::new();
720        let mut seen = std::collections::HashSet::new();
721
722        let legacy_prefix = self.legacy_session_key("");
723        // Check each session to see if it belongs to the user
724        for key in keys {
725            // A row still under the pre-fix name is moved to its digest name as
726            // it is listed, so it stops exposing the raw session id in key names.
727            let session_json = match key.strip_prefix(&legacy_prefix) {
728                Some(session_id) => self
729                    .get_migrating(&self.session_key(session_id), &key)
730                    .await
731                    .ok()
732                    .flatten(),
733                None => redis::cmd("GET")
734                    .arg(&key)
735                    .query_async::<Option<String>>(&mut conn)
736                    .await
737                    .ok()
738                    .flatten(),
739            };
740            if let Some(session_json) = session_json
741                && let Ok(session) = serde_json::from_str::<SessionData>(&session_json)
742                && session.user_id == user_id
743                && !session.is_expired()
744                && seen.insert(session.session_id.clone())
745            {
746                user_sessions.push(session);
747            }
748        }
749
750        Ok(user_sessions)
751    }
752
753    async fn store_kv(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()> {
754        let mut conn = self.get_connection().await?;
755        let storage_key = self.key(&format!("kv:{key}"));
756
757        if let Some(ttl) = ttl {
758            let _: () = redis::cmd("SETEX")
759                .arg(&storage_key)
760                .arg(ttl.as_secs())
761                .arg(value)
762                .query_async(&mut conn)
763                .await
764                .map_err(|e| {
765                    StorageError::operation_failed(format!("Failed to store KV with TTL: {e}"))
766                })?;
767        } else {
768            let _: () = redis::cmd("SET")
769                .arg(&storage_key)
770                .arg(value)
771                .query_async(&mut conn)
772                .await
773                .map_err(|e| StorageError::operation_failed(format!("Failed to store KV: {e}")))?;
774        }
775
776        Ok(())
777    }
778
779    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
780        let mut conn = self.get_connection().await?;
781        let storage_key = self.key(&format!("kv:{key}"));
782
783        let value: Option<Vec<u8>> = redis::cmd("GET")
784            .arg(&storage_key)
785            .query_async(&mut conn)
786            .await
787            .map_err(|e| StorageError::operation_failed(format!("Failed to get KV: {e}")))?;
788
789        Ok(value)
790    }
791
792    async fn delete_kv(&self, key: &str) -> Result<()> {
793        let mut conn = self.get_connection().await?;
794        let storage_key = self.key(&format!("kv:{key}"));
795
796        let _: () = redis::cmd("DEL")
797            .arg(&storage_key)
798            .query_async(&mut conn)
799            .await
800            .map_err(|e| StorageError::operation_failed(format!("Failed to delete KV: {e}")))?;
801
802        Ok(())
803    }
804
805    async fn cleanup_expired(&self) -> Result<()> {
806        // Redis handles expiration automatically, so this is a no-op
807        Ok(())
808    }
809
810    async fn count_active_sessions(&self) -> Result<u64> {
811        let mut conn = self.get_connection().await?;
812
813        // Use KEYS to find all session keys (consider SCAN for production with many keys)
814        let keys = self.session_keys(&mut conn).await?;
815        // A session present under both names is one session.
816        let keys = crate::storage::key_names::without_shadowed_legacy(
817            keys,
818            &self.legacy_session_key(""),
819            &self.key("session_h:"),
820            "session",
821        );
822
823        // Count only non-expired sessions by checking TTL
824        let mut active_count = 0u64;
825        for key in keys {
826            let ttl: i64 = redis::cmd("TTL")
827                .arg(&key)
828                .query_async(&mut conn)
829                .await
830                .map_err(|e| StorageError::operation_failed(format!("Failed to check TTL: {e}")))?;
831
832            // TTL > 0 means key has expiration and is still active
833            // TTL = -1 means key has no expiration (active)
834            // TTL = -2 means key doesn't exist (expired)
835            if ttl > 0 || ttl == -1 {
836                active_count += 1;
837            }
838        }
839
840        Ok(active_count)
841    }
842}
843
844impl SessionData {
845    /// Create a new session.
846    pub fn new(
847        session_id: impl Into<String>,
848        user_id: impl Into<String>,
849        expires_in: Duration,
850    ) -> Self {
851        let now = chrono::Utc::now();
852
853        Self {
854            session_id: session_id.into(),
855            user_id: user_id.into(),
856            created_at: now,
857            expires_at: now + chrono::Duration::from_std(expires_in).unwrap(),
858            last_activity: now,
859            ip_address: None,
860            user_agent: None,
861            data: HashMap::new(),
862        }
863    }
864
865    /// Check if the session has expired.
866    pub fn is_expired(&self) -> bool {
867        chrono::Utc::now() > self.expires_at
868    }
869
870    /// Update the last activity timestamp.
871    pub fn update_activity(&mut self) {
872        self.last_activity = chrono::Utc::now();
873    }
874
875    /// Set session metadata.
876    pub fn with_metadata(mut self, ip_address: Option<String>, user_agent: Option<String>) -> Self {
877        self.ip_address = ip_address;
878        self.user_agent = user_agent;
879        self
880    }
881
882    /// Add custom data to the session.
883    pub fn set_data(&mut self, key: impl Into<String>, value: serde_json::Value) {
884        self.data.insert(key.into(), value);
885    }
886
887    /// Get custom data from the session.
888    pub fn get_data(&self, key: &str) -> Option<&serde_json::Value> {
889        self.data.get(key)
890    }
891}
892
893/// Implementation of AuditStorage for MemoryStorage
894#[async_trait]
895impl crate::audit::AuditStorage for MemoryStorage {
896    async fn store_event(&self, event: &crate::audit::AuditEvent) -> Result<()> {
897        // Store audit event as JSON in KV storage
898        let json_data = serde_json::to_vec(event).map_err(|e| {
899            crate::errors::AuthError::internal(format!("Failed to serialize audit event: {}", e))
900        })?;
901
902        let key = format!("audit_event_{}", event.id);
903        self.store_kv(&key, &json_data, None).await
904    }
905
906    async fn query_events(
907        &self,
908        query: &crate::audit::AuditQuery,
909    ) -> Result<Vec<crate::audit::AuditEvent>> {
910        // Simple implementation - in production, this would be more efficient
911        let all_keys = self.list_kv_keys("audit_event_").await?;
912        let mut events = Vec::new();
913
914        for key in all_keys {
915            if let Some(data) = self.get_kv(&key).await?
916                && let Ok(event) = serde_json::from_slice::<crate::audit::AuditEvent>(&data)
917            {
918                // Apply filters
919                let mut include = true;
920
921                if let Some(ref time_range) = query.time_range
922                    && (event.timestamp < time_range.start || event.timestamp > time_range.end)
923                {
924                    include = false;
925                }
926
927                if let Some(ref event_types) = query.event_types
928                    && !event_types.contains(&event.event_type)
929                {
930                    include = false;
931                }
932
933                if let Some(ref user_id) = query.user_id
934                    && event.user_id.as_ref() != Some(user_id)
935                {
936                    include = false;
937                }
938
939                if include {
940                    events.push(event);
941                }
942            }
943        }
944
945        // Sort and limit
946        events.sort_by(|a, b| match query.sort_order {
947            crate::audit::SortOrder::TimestampAsc => a.timestamp.cmp(&b.timestamp),
948            crate::audit::SortOrder::TimestampDesc => b.timestamp.cmp(&a.timestamp),
949            crate::audit::SortOrder::RiskLevelDesc => b.risk_level.cmp(&a.risk_level),
950        });
951
952        if let Some(limit) = query.limit {
953            events.truncate(limit as usize);
954        }
955        Ok(events)
956    }
957
958    async fn get_event(&self, event_id: &str) -> Result<Option<crate::audit::AuditEvent>> {
959        let key = format!("audit_event_{}", event_id);
960        if let Some(data) = self.get_kv(&key).await? {
961            let event = serde_json::from_slice(&data).map_err(|e| {
962                crate::errors::AuthError::internal(format!(
963                    "Failed to deserialize audit event: {}",
964                    e
965                ))
966            })?;
967            Ok(Some(event))
968        } else {
969            Ok(None)
970        }
971    }
972
973    async fn count_events(&self, query: &crate::audit::AuditQuery) -> Result<u64> {
974        let events = self.query_events(query).await?;
975        Ok(events.len() as u64)
976    }
977
978    async fn delete_old_events(&self, before: std::time::SystemTime) -> Result<u64> {
979        let all_keys = self.list_kv_keys("audit_event_").await?;
980        let mut deleted_count = 0;
981
982        for key in all_keys {
983            if let Some(data) = self.get_kv(&key).await?
984                && let Ok(event) = serde_json::from_slice::<crate::audit::AuditEvent>(&data)
985                && event.timestamp < before
986            {
987                self.delete_kv(&key).await?;
988                deleted_count += 1;
989            }
990        }
991
992        Ok(deleted_count)
993    }
994
995    async fn get_statistics(
996        &self,
997        _query: &crate::audit::StatsQuery,
998    ) -> Result<crate::audit::AuditStatistics> {
999        // For now, return basic statistics
1000        // PRODUCTION: Full audit statistics available with integrated audit storage
1001
1002        let total_events = 0; // Placeholder
1003        let event_type_counts = std::collections::HashMap::new();
1004        let risk_level_counts = std::collections::HashMap::new();
1005        let outcome_counts = std::collections::HashMap::new();
1006        let time_series = Vec::new();
1007        let top_users = Vec::new();
1008        let top_ips = Vec::new();
1009
1010        Ok(crate::audit::AuditStatistics {
1011            total_events,
1012            event_type_counts,
1013            risk_level_counts,
1014            outcome_counts,
1015            time_series,
1016            top_users,
1017            top_ips,
1018        })
1019    }
1020}
1021
1022impl MemoryStorage {
1023    /// Helper method to list KV keys with a prefix
1024    async fn list_kv_keys(&self, prefix: &str) -> Result<Vec<String>> {
1025        Ok(self.inner.list_kv_keys_by_prefix(prefix))
1026    }
1027}
1028
1029/// Implementation of AuditStorage for Arc<MemoryStorage>
1030#[async_trait]
1031impl crate::audit::AuditStorage for Arc<MemoryStorage> {
1032    async fn store_event(&self, event: &crate::audit::AuditEvent) -> Result<()> {
1033        self.as_ref().store_event(event).await
1034    }
1035
1036    async fn query_events(
1037        &self,
1038        query: &crate::audit::AuditQuery,
1039    ) -> Result<Vec<crate::audit::AuditEvent>> {
1040        self.as_ref().query_events(query).await
1041    }
1042
1043    async fn get_event(&self, event_id: &str) -> Result<Option<crate::audit::AuditEvent>> {
1044        self.as_ref().get_event(event_id).await
1045    }
1046
1047    async fn count_events(&self, query: &crate::audit::AuditQuery) -> Result<u64> {
1048        self.as_ref().count_events(query).await
1049    }
1050
1051    async fn delete_old_events(&self, before: std::time::SystemTime) -> Result<u64> {
1052        self.as_ref().delete_old_events(before).await
1053    }
1054
1055    async fn get_statistics(
1056        &self,
1057        query: &crate::audit::StatsQuery,
1058    ) -> Result<crate::audit::AuditStatistics> {
1059        self.as_ref().get_statistics(query).await
1060    }
1061}
1062
1063#[cfg(test)]
1064mod tests {
1065    use super::*;
1066    use crate::tokens::AuthToken;
1067
1068    #[tokio::test]
1069    async fn test_memory_storage() {
1070        let storage = MemoryStorage::new();
1071
1072        // Create a test token
1073        let token = AuthToken::new("user123", "token123", Duration::from_secs(3600), "test");
1074
1075        // Store token
1076        storage.store_token(&token).await.unwrap();
1077
1078        // Retrieve token
1079        let retrieved = storage.get_token(&token.token_id).await.unwrap().unwrap();
1080        assert_eq!(retrieved.user_id, "user123");
1081
1082        // Retrieve by access token
1083        let retrieved = storage
1084            .get_token_by_access_token(&token.access_token)
1085            .await
1086            .unwrap()
1087            .unwrap();
1088        assert_eq!(retrieved.token_id, token.token_id);
1089
1090        // List user tokens
1091        let user_tokens = storage.list_user_tokens("user123").await.unwrap();
1092        assert_eq!(user_tokens.len(), 1);
1093
1094        // Delete token
1095        storage.delete_token(&token.token_id).await.unwrap();
1096        let retrieved = storage.get_token(&token.token_id).await.unwrap();
1097        assert!(retrieved.is_none());
1098    }
1099
1100    #[tokio::test]
1101    async fn test_session_storage() {
1102        let storage = MemoryStorage::new();
1103
1104        let session = SessionData::new("session123", "user123", Duration::from_secs(3600))
1105            .with_metadata(
1106                Some("192.168.1.1".to_string()),
1107                Some("Test Agent".to_string()),
1108            );
1109
1110        // Store session
1111        storage
1112            .store_session(&session.session_id, &session)
1113            .await
1114            .unwrap();
1115
1116        // Retrieve session
1117        let retrieved = storage
1118            .get_session(&session.session_id)
1119            .await
1120            .unwrap()
1121            .unwrap();
1122        assert_eq!(retrieved.user_id, "user123");
1123        assert_eq!(retrieved.ip_address, Some("192.168.1.1".to_string()));
1124
1125        // Delete session
1126        storage.delete_session(&session.session_id).await.unwrap();
1127        let retrieved = storage.get_session(&session.session_id).await.unwrap();
1128        assert!(retrieved.is_none());
1129    }
1130
1131    #[tokio::test]
1132    async fn test_kv_storage() {
1133        let storage = MemoryStorage::new();
1134
1135        let key = "test_key";
1136        let value = b"test_value";
1137
1138        // Store KV
1139        storage
1140            .store_kv(key, value, Some(Duration::from_secs(3600)))
1141            .await
1142            .unwrap();
1143
1144        // Retrieve KV
1145        let retrieved = storage.get_kv(key).await.unwrap().unwrap();
1146        assert_eq!(retrieved, value);
1147
1148        // Delete KV
1149        storage.delete_kv(key).await.unwrap();
1150        let retrieved = storage.get_kv(key).await.unwrap();
1151        assert!(retrieved.is_none());
1152    }
1153}