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