Skip to main content

auth_framework/storage/
dashmap_memory.rs

1use crate::audit::{
2    ActorInfo, AuditEvent, AuditEventType, EventOutcome, RequestMetadata, ResourceInfo, RiskLevel,
3};
4/// DashMap-based storage implementation with deadlock-safe patterns
5///
6/// This implementation replaces RwLock<HashMap> with DashMap to provide:
7/// - Lock-free concurrent access
8/// - Deadlock-free operations
9/// - Better performance under high concurrency
10///
11/// Key safety principles:
12/// 1. Never hold multiple DashMap references simultaneously
13/// 2. Always extract values immediately rather than holding references
14/// 3. Use atomic operations for cross-map updates
15/// 4. Scope all operations to prevent reference leaks
16use crate::errors::Result;
17use crate::storage::core::{AuthStorage, SessionData};
18use crate::tokens::AuthToken;
19use async_trait::async_trait;
20use dashmap::DashMap;
21use std::time::Duration;
22
23/// Wrapper for tokens with expiration tracking
24#[derive(Debug, Clone)]
25struct TimestampedToken {
26    token: AuthToken,
27    created_at: chrono::DateTime<chrono::Utc>,
28    expires_at: Option<chrono::DateTime<chrono::Utc>>,
29}
30
31/// Wrapper for sessions with expiration tracking
32#[derive(Debug, Clone)]
33struct TimestampedSession {
34    session: SessionData,
35    created_at: chrono::DateTime<chrono::Utc>,
36}
37
38/// Wrapper for KV values with expiration
39#[derive(Debug, Clone)]
40struct TimestampedValue {
41    data: Vec<u8>,
42    created_at: chrono::DateTime<chrono::Utc>,
43    expires_at: Option<chrono::DateTime<chrono::Utc>>,
44}
45
46impl TimestampedToken {
47    fn new(token: AuthToken, ttl: Option<Duration>) -> Self {
48        let now = chrono::Utc::now();
49        let expires_at =
50            ttl.map(|d| now + chrono::Duration::from_std(d).unwrap_or(chrono::Duration::hours(1)));
51
52        Self {
53            token,
54            created_at: now,
55            expires_at,
56        }
57    }
58
59    fn is_expired(&self) -> bool {
60        self.expires_at
61            .map(|exp| chrono::Utc::now() > exp)
62            .unwrap_or(false)
63    }
64}
65
66impl TimestampedSession {
67    fn new(session: SessionData) -> Self {
68        Self {
69            session,
70            created_at: chrono::Utc::now(),
71        }
72    }
73
74    fn is_expired(&self) -> bool {
75        self.session.is_expired()
76    }
77}
78
79impl TimestampedValue {
80    fn new(data: Vec<u8>, ttl: Option<Duration>) -> Self {
81        let now = chrono::Utc::now();
82        let expires_at =
83            ttl.map(|d| now + chrono::Duration::from_std(d).unwrap_or(chrono::Duration::hours(1)));
84
85        Self {
86            data,
87            created_at: now,
88            expires_at,
89        }
90    }
91
92    fn is_expired(&self) -> bool {
93        self.expires_at
94            .map(|exp| chrono::Utc::now() > exp)
95            .unwrap_or(false)
96    }
97}
98
99/// DashMap-based storage with deadlock-safe patterns
100#[derive(Debug, Clone)]
101pub struct DashMapMemoryStorage {
102    // Core storage maps
103    tokens: DashMap<String, TimestampedToken>,
104    sessions: DashMap<String, TimestampedSession>,
105    kv_store: DashMap<String, TimestampedValue>,
106
107    // Index maps for efficient lookups
108    access_token_to_id: DashMap<String, String>,
109    user_to_tokens: DashMap<String, Vec<String>>,
110    user_to_sessions: DashMap<String, Vec<String>>,
111
112    // Configuration
113    default_ttl: Option<Duration>,
114}
115
116impl Default for DashMapMemoryStorage {
117    fn default() -> Self {
118        Self::new()
119    }
120}
121
122impl DashMapMemoryStorage {
123    /// Create a new DashMap-based storage
124    pub fn new() -> Self {
125        Self {
126            tokens: DashMap::new(),
127            sessions: DashMap::new(),
128            kv_store: DashMap::new(),
129            access_token_to_id: DashMap::new(),
130            user_to_tokens: DashMap::new(),
131            user_to_sessions: DashMap::new(),
132            default_ttl: None,
133        }
134    }
135
136    /// Create storage with default TTL for all stored items
137    pub fn with_ttl(ttl: Duration) -> Self {
138        Self {
139            tokens: DashMap::new(),
140            sessions: DashMap::new(),
141            kv_store: DashMap::new(),
142            access_token_to_id: DashMap::new(),
143            user_to_tokens: DashMap::new(),
144            user_to_sessions: DashMap::new(),
145            default_ttl: Some(ttl),
146        }
147    }
148
149    /// Generate audit event for storage operations
150    fn create_audit_event(
151        &self,
152        event_type: AuditEventType,
153        user_id: &str,
154        resource_id: &str,
155        resource_type: &str,
156        outcome: EventOutcome,
157        details_str: Option<&str>,
158    ) -> AuditEvent {
159        let mut details = std::collections::HashMap::new();
160        if let Some(detail) = details_str {
161            details.insert("operation_details".to_string(), detail.to_string());
162        }
163        details.insert("resource_type".to_string(), resource_type.to_string());
164        details.insert("resource_id".to_string(), resource_id.to_string());
165
166        let risk_level = match &event_type {
167            AuditEventType::TokenRevoked | AuditEventType::TokenExpired => RiskLevel::Medium,
168            AuditEventType::SuspiciousActivity => RiskLevel::High,
169            _ => RiskLevel::Low,
170        };
171
172        AuditEvent::builder(
173            event_type.clone(),
174            format!(
175                "{:?} operation on {} {}",
176                event_type, resource_type, resource_id
177            ),
178        )
179        .user_id(user_id)
180        .outcome(outcome)
181        .risk_level(risk_level)
182        .details(details)
183        .request_metadata(RequestMetadata::new().with_endpoint("storage"))
184        .resource(ResourceInfo {
185            resource_type: resource_type.to_string(),
186            resource_id: resource_id.to_string(),
187            resource_name: None,
188            attributes: std::collections::HashMap::new(),
189        })
190        .actor(ActorInfo {
191            actor_type: "storage_system".to_string(),
192            actor_id: user_id.to_string(),
193            actor_name: Some(user_id.to_string()),
194            roles: vec!["storage_user".to_string()],
195        })
196        .build()
197    }
198
199    /// Log storage operation with lifecycle information
200    async fn log_storage_operation(
201        &self,
202        event_type: AuditEventType,
203        user_id: &str,
204        resource_id: &str,
205        resource_type: &str,
206        created_at: Option<chrono::DateTime<chrono::Utc>>,
207        outcome: EventOutcome,
208    ) {
209        let details = if let Some(created) = created_at {
210            let age = chrono::Utc::now().signed_duration_since(created);
211            format!(
212                "{:?} operation on {} {} (age: {} seconds)",
213                event_type,
214                resource_type,
215                resource_id,
216                age.num_seconds()
217            )
218        } else {
219            format!(
220                "{:?} operation on {} {}",
221                event_type, resource_type, resource_id
222            )
223        };
224
225        let audit_event = self.create_audit_event(
226            event_type,
227            user_id,
228            resource_id,
229            resource_type,
230            outcome,
231            Some(&details),
232        );
233
234        // Log the audit event - in production this would go to the audit logger
235        tracing::info!(
236            "STORAGE AUDIT: {}",
237            serde_json::to_string(&audit_event).unwrap_or_default()
238        );
239    }
240
241    /// Get storage statistics for audit reporting
242    pub fn get_storage_statistics(&self) -> std::collections::HashMap<String, serde_json::Value> {
243        let mut stats = std::collections::HashMap::new();
244        stats.insert(
245            "total_tokens".to_string(),
246            serde_json::Value::from(self.tokens.len()),
247        );
248        stats.insert(
249            "total_sessions".to_string(),
250            serde_json::Value::from(self.sessions.len()),
251        );
252        stats.insert(
253            "total_kv_pairs".to_string(),
254            serde_json::Value::from(self.kv_store.len()),
255        );
256        stats.insert(
257            "total_users_with_tokens".to_string(),
258            serde_json::Value::from(self.user_to_tokens.len()),
259        );
260        stats.insert(
261            "total_users_with_sessions".to_string(),
262            serde_json::Value::from(self.user_to_sessions.len()),
263        );
264        stats.insert(
265            "timestamp".to_string(),
266            serde_json::Value::from(chrono::Utc::now().to_rfc3339()),
267        );
268        stats
269    }
270
271    /// Audit tokens by age - find old tokens for security review
272    pub fn audit_token_ages(&self) -> Vec<(String, String, i64)> {
273        let mut aged_tokens = Vec::new();
274        let now = chrono::Utc::now();
275
276        for entry in self.tokens.iter() {
277            let age_seconds = now.signed_duration_since(entry.created_at).num_seconds();
278            aged_tokens.push((
279                entry.key().clone(),
280                entry.token.user_id.clone(),
281                age_seconds,
282            ));
283        }
284
285        aged_tokens.sort_by(|a, b| b.2.cmp(&a.2)); // Sort by age descending
286        aged_tokens
287    }
288
289    /// Audit sessions by age - find old sessions for security review
290    pub fn audit_session_ages(&self) -> Vec<(String, String, i64)> {
291        let mut aged_sessions = Vec::new();
292        let now = chrono::Utc::now();
293
294        for entry in self.sessions.iter() {
295            let age_seconds = now.signed_duration_since(entry.created_at).num_seconds();
296            aged_sessions.push((
297                entry.key().clone(),
298                entry.session.user_id.clone(),
299                age_seconds,
300            ));
301        }
302
303        aged_sessions.sort_by(|a, b| b.2.cmp(&a.2)); // Sort by age descending
304        aged_sessions
305    }
306
307    /// Generate comprehensive audit report
308    pub fn generate_audit_report(&self) -> std::collections::HashMap<String, serde_json::Value> {
309        let mut report = self.get_storage_statistics();
310
311        let token_ages = self.audit_token_ages();
312        let session_ages = self.audit_session_ages();
313
314        // Add age analysis
315        if !token_ages.is_empty() {
316            report.insert(
317                "oldest_token_age_seconds".to_string(),
318                serde_json::Value::from(token_ages[0].2),
319            );
320            report.insert(
321                "tokens_older_than_24h".to_string(),
322                serde_json::Value::from(
323                    token_ages.iter().filter(|(_, _, age)| *age > 86400).count(),
324                ),
325            );
326        }
327
328        if !session_ages.is_empty() {
329            report.insert(
330                "oldest_session_age_seconds".to_string(),
331                serde_json::Value::from(session_ages[0].2),
332            );
333            report.insert(
334                "sessions_older_than_24h".to_string(),
335                serde_json::Value::from(
336                    session_ages
337                        .iter()
338                        .filter(|(_, _, age)| *age > 86400)
339                        .count(),
340                ),
341            );
342        }
343
344        report
345    }
346
347    /// DEADLOCK-SAFE: Add token to user index
348    /// Uses atomic operations to prevent cross-map deadlocks
349    fn add_token_to_user_index(&self, user_id: &str, token_id: &str) {
350        // SAFE: Scoped operation that doesn't hold references across map operations
351        self.user_to_tokens
352            .entry(user_id.to_string())
353            .and_modify(|tokens| tokens.push(token_id.to_string()))
354            .or_insert_with(|| vec![token_id.to_string()]);
355    }
356
357    /// DEADLOCK-SAFE: Remove token from user index
358    fn remove_token_from_user_index(&self, user_id: &str, token_id: &str) {
359        // SAFE: Scoped operation with immediate value extraction
360        if let Some(mut entry) = self.user_to_tokens.get_mut(user_id) {
361            entry.retain(|id| id != token_id);
362            if entry.is_empty() {
363                drop(entry); // Release the entry before removal
364                self.user_to_tokens.remove(user_id);
365            }
366        }
367    }
368
369    /// DEADLOCK-SAFE: Add session to user index
370    fn add_session_to_user_index(&self, user_id: &str, session_id: &str) {
371        self.user_to_sessions
372            .entry(user_id.to_string())
373            .and_modify(|sessions| sessions.push(session_id.to_string()))
374            .or_insert_with(|| vec![session_id.to_string()]);
375    }
376
377    /// DEADLOCK-SAFE: Remove session from user index
378    fn remove_session_from_user_index(&self, user_id: &str, session_id: &str) {
379        if let Some(mut entry) = self.user_to_sessions.get_mut(user_id) {
380            entry.retain(|id| id != session_id);
381            if entry.is_empty() {
382                drop(entry);
383                self.user_to_sessions.remove(user_id);
384            }
385        }
386    }
387
388    /// Return all KV keys that start with `prefix`.
389    pub fn list_kv_keys_by_prefix(&self, prefix: &str) -> Vec<String> {
390        self.kv_store
391            .iter()
392            .filter_map(|entry| {
393                if entry.key().starts_with(prefix) {
394                    Some(entry.key().clone())
395                } else {
396                    None
397                }
398            })
399            .collect()
400    }
401}
402
403#[async_trait]
404impl AuthStorage for DashMapMemoryStorage {
405    async fn store_token(&self, token: &AuthToken) -> Result<()> {
406        let timestamped = TimestampedToken::new(token.clone(), self.default_ttl);
407        let created_at = timestamped.created_at;
408
409        // SAFE: Store in primary map first
410        self.tokens.insert(token.token_id.clone(), timestamped);
411
412        // SAFE: Update access token index (no cross-map references)
413        self.access_token_to_id
414            .insert(token.access_token.clone(), token.token_id.clone());
415
416        // SAFE: Update user index (atomic operation)
417        self.add_token_to_user_index(&token.user_id, &token.token_id);
418
419        // Log storage operation with creation timestamp
420        self.log_storage_operation(
421            AuditEventType::LoginSuccess, // Token storage represents successful authentication
422            &token.user_id,
423            &token.token_id,
424            "token",
425            Some(created_at),
426            EventOutcome::Success,
427        )
428        .await;
429
430        Ok(())
431    }
432
433    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>> {
434        // SAFE: Immediate value extraction, no reference holding
435        if let Some(timestamped) = self.tokens.get(token_id) {
436            let created_at = timestamped.created_at;
437            let user_id = timestamped.token.user_id.clone();
438
439            if timestamped.is_expired() {
440                drop(timestamped); // Release reference
441                self.tokens.remove(token_id); // Cleanup expired
442
443                // Log expired token access attempt
444                self.log_storage_operation(
445                    AuditEventType::TokenExpired,
446                    &user_id,
447                    token_id,
448                    "token",
449                    Some(created_at),
450                    EventOutcome::Failure,
451                )
452                .await;
453
454                return Ok(None);
455            }
456
457            let token = timestamped.token.clone();
458            drop(timestamped); // Release reference
459
460            // Log successful token access
461            self.log_storage_operation(
462                AuditEventType::LoginSuccess, // Token access represents authentication validation
463                &user_id,
464                token_id,
465                "token",
466                Some(created_at),
467                EventOutcome::Success,
468            )
469            .await;
470
471            Ok(Some(token))
472        } else {
473            Ok(None)
474        }
475    }
476
477    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>> {
478        // SAFE: Two-step lookup with immediate value extraction
479        if let Some(token_id_entry) = self.access_token_to_id.get(access_token) {
480            let token_id = token_id_entry.clone(); // Extract value immediately
481            drop(token_id_entry); // Release first map reference
482            self.get_token(&token_id).await // Use extracted value
483        } else {
484            Ok(None)
485        }
486    }
487
488    async fn update_token(&self, token: &AuthToken) -> Result<()> {
489        // SAFE: Update is same as store for this implementation
490        self.store_token(token).await
491    }
492
493    async fn delete_token(&self, token_id: &str) -> Result<()> {
494        // SAFE: Extract token info before removal to avoid reference issues
495        let token_info = if let Some(timestamped) = self.tokens.get(token_id) {
496            Some((
497                timestamped.token.user_id.clone(),
498                timestamped.token.access_token.clone(),
499                timestamped.created_at,
500            ))
501        } else {
502            None
503        };
504
505        if let Some((user_id, access_token, created_at)) = token_info {
506            // SAFE: All operations use extracted values, no cross-map references
507            self.tokens.remove(token_id);
508            self.access_token_to_id.remove(&access_token);
509            self.remove_token_from_user_index(&user_id, token_id);
510
511            // Log token deletion with creation timestamp for audit trail
512            self.log_storage_operation(
513                AuditEventType::TokenRevoked,
514                &user_id,
515                token_id,
516                "token",
517                Some(created_at),
518                EventOutcome::Success,
519            )
520            .await;
521        }
522
523        Ok(())
524    }
525
526    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
527        // SAFE: Extract token IDs first, then lookup individually
528        let token_ids = if let Some(ids) = self.user_to_tokens.get(user_id) {
529            ids.clone() // Immediate extraction
530        } else {
531            return Ok(Vec::new());
532        };
533
534        let mut tokens = Vec::new();
535        let mut expired_tokens = Vec::new();
536
537        // SAFE: Iterate over extracted IDs, no cross-map reference holding
538        for token_id in token_ids {
539            if let Some(timestamped) = self.tokens.get(&token_id) {
540                if timestamped.is_expired() {
541                    expired_tokens.push(token_id);
542                } else {
543                    tokens.push(timestamped.token.clone());
544                }
545            } else {
546                expired_tokens.push(token_id); // Token was removed elsewhere
547            }
548        }
549
550        // SAFE: Cleanup expired tokens (uses extracted IDs)
551        for token_id in expired_tokens {
552            self.delete_token(&token_id).await?;
553        }
554
555        Ok(tokens)
556    }
557
558    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()> {
559        let timestamped = TimestampedSession::new(data.clone());
560        let created_at = timestamped.created_at;
561
562        // SAFE: Store in primary map first
563        self.sessions.insert(session_id.to_string(), timestamped);
564
565        // SAFE: Update user index (atomic operation)
566        self.add_session_to_user_index(&data.user_id, session_id);
567
568        // Log session storage with creation timestamp
569        self.log_storage_operation(
570            AuditEventType::LoginSuccess, // Session creation represents successful login
571            &data.user_id,
572            session_id,
573            "session",
574            Some(created_at),
575            EventOutcome::Success,
576        )
577        .await;
578
579        Ok(())
580    }
581
582    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
583        // SAFE: Immediate value extraction
584        if let Some(timestamped) = self.sessions.get(session_id) {
585            let created_at = timestamped.created_at;
586            let user_id = timestamped.session.user_id.clone();
587
588            if timestamped.is_expired() {
589                drop(timestamped);
590                self.sessions.remove(session_id);
591
592                // Log expired session access
593                self.log_storage_operation(
594                    AuditEventType::TokenExpired, // Session expiration
595                    &user_id,
596                    session_id,
597                    "session",
598                    Some(created_at),
599                    EventOutcome::Failure,
600                )
601                .await;
602
603                return Ok(None);
604            }
605
606            let session = timestamped.session.clone();
607            drop(timestamped);
608
609            // Log successful session access
610            self.log_storage_operation(
611                AuditEventType::LoginSuccess, // Session access represents continued authentication
612                &user_id,
613                session_id,
614                "session",
615                Some(created_at),
616                EventOutcome::Success,
617            )
618            .await;
619
620            Ok(Some(session))
621        } else {
622            Ok(None)
623        }
624    }
625
626    async fn delete_session(&self, session_id: &str) -> Result<()> {
627        // SAFE: Extract session info before removal
628        let session_info = if let Some(timestamped) = self.sessions.get(session_id) {
629            Some((timestamped.session.user_id.clone(), timestamped.created_at))
630        } else {
631            None
632        };
633
634        if let Some((user_id, created_at)) = session_info {
635            self.sessions.remove(session_id);
636            self.remove_session_from_user_index(&user_id, session_id);
637
638            // Log session deletion with creation timestamp
639            self.log_storage_operation(
640                AuditEventType::Logout,
641                &user_id,
642                session_id,
643                "session",
644                Some(created_at),
645                EventOutcome::Success,
646            )
647            .await;
648        }
649
650        Ok(())
651    }
652
653    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> {
654        // SAFE: Extract session IDs first
655        let session_ids = if let Some(ids) = self.user_to_sessions.get(user_id) {
656            ids.clone()
657        } else {
658            return Ok(Vec::new());
659        };
660
661        let mut sessions = Vec::new();
662        let mut expired_sessions = Vec::new();
663
664        // SAFE: Iterate over extracted IDs
665        for session_id in session_ids {
666            if let Some(timestamped) = self.sessions.get(&session_id) {
667                if timestamped.is_expired() {
668                    expired_sessions.push(session_id);
669                } else {
670                    sessions.push(timestamped.session.clone());
671                }
672            } else {
673                expired_sessions.push(session_id);
674            }
675        }
676
677        // SAFE: Cleanup expired sessions
678        for session_id in expired_sessions {
679            self.delete_session(&session_id).await?;
680        }
681
682        Ok(sessions)
683    }
684
685    async fn store_kv(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()> {
686        let timestamped = TimestampedValue::new(value.to_vec(), ttl.or(self.default_ttl));
687        let created_at = timestamped.created_at;
688
689        self.kv_store.insert(key.to_string(), timestamped);
690
691        // Log KV storage operation with creation timestamp
692        self.log_storage_operation(
693            AuditEventType::ConfigurationChanged, // KV operations represent configuration/data changes
694            "system",                             // KV operations are typically system-level
695            key,
696            "kv_pair",
697            Some(created_at),
698            EventOutcome::Success,
699        )
700        .await;
701
702        Ok(())
703    }
704
705    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
706        // SAFE: Immediate value extraction
707        if let Some(timestamped) = self.kv_store.get(key) {
708            let created_at = timestamped.created_at;
709
710            if timestamped.is_expired() {
711                drop(timestamped);
712                self.kv_store.remove(key);
713
714                // Log expired KV access
715                self.log_storage_operation(
716                    AuditEventType::TokenExpired, // Data expiration
717                    "system",
718                    key,
719                    "kv_pair",
720                    Some(created_at),
721                    EventOutcome::Failure,
722                )
723                .await;
724
725                return Ok(None);
726            }
727
728            let data = timestamped.data.clone();
729            drop(timestamped);
730
731            // Log successful KV access
732            self.log_storage_operation(
733                AuditEventType::ConfigurationChanged, // KV access
734                "system",
735                key,
736                "kv_pair",
737                Some(created_at),
738                EventOutcome::Success,
739            )
740            .await;
741
742            Ok(Some(data))
743        } else {
744            Ok(None)
745        }
746    }
747
748    async fn delete_kv(&self, key: &str) -> Result<()> {
749        // SAFE: Extract creation timestamp before removal
750        let created_at = if let Some(timestamped) = self.kv_store.get(key) {
751            Some(timestamped.created_at)
752        } else {
753            None
754        };
755
756        self.kv_store.remove(key);
757
758        if let Some(created_at) = created_at {
759            // Log KV deletion with creation timestamp
760            self.log_storage_operation(
761                AuditEventType::ConfigurationChanged, // KV deletion
762                "system",
763                key,
764                "kv_pair",
765                Some(created_at),
766                EventOutcome::Success,
767            )
768            .await;
769        }
770
771        Ok(())
772    }
773
774    async fn cleanup_expired(&self) -> Result<()> {
775        // SAFE: Collect expired keys first, then remove them
776        let mut expired_tokens = Vec::new();
777        let mut expired_sessions = Vec::new();
778        let mut expired_kvs = Vec::new();
779
780        // SAFE: Scan for expired items (no cross-map operations)
781        for entry in self.tokens.iter() {
782            if entry.is_expired() {
783                expired_tokens.push(entry.key().clone());
784            }
785        }
786
787        for entry in self.sessions.iter() {
788            if entry.is_expired() {
789                expired_sessions.push(entry.key().clone());
790            }
791        }
792
793        for entry in self.kv_store.iter() {
794            if entry.is_expired() {
795                expired_kvs.push(entry.key().clone());
796            }
797        }
798
799        // SAFE: Remove expired items using extracted keys
800        for token_id in expired_tokens {
801            self.delete_token(&token_id).await?;
802        }
803
804        for session_id in expired_sessions {
805            self.delete_session(&session_id).await?;
806        }
807
808        for key in expired_kvs {
809            self.delete_kv(&key).await?;
810        }
811
812        Ok(())
813    }
814
815    async fn count_active_sessions(&self) -> Result<u64> {
816        let mut count = 0;
817
818        // Count all non-expired sessions
819        for entry in self.sessions.iter() {
820            if !entry.is_expired() {
821                count += 1;
822            }
823        }
824
825        Ok(count)
826    }
827}
828
829#[cfg(test)]
830mod tests {
831    use super::*;
832    use crate::{
833        testing::test_infrastructure::TestEnvironmentGuard,
834        tokens::TokenMetadata,
835        types::{Permissions, Roles, Scopes},
836    };
837    use std::collections::HashMap;
838    use tokio::task::JoinSet;
839
840    #[tokio::test]
841    async fn test_basic_token_operations() {
842        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-test");
843        let storage = DashMapMemoryStorage::new();
844
845        let token = AuthToken {
846            token_id: "test-token".to_string(),
847            user_id: "test-user".to_string(),
848            access_token: "access-123".to_string(),
849            token_type: Some("bearer".to_string()),
850            subject: Some("test-user".to_string()),
851            issuer: Some("test-issuer".to_string()),
852            refresh_token: None,
853            issued_at: chrono::Utc::now(),
854            expires_at: chrono::Utc::now() + chrono::Duration::hours(1),
855            scopes: Scopes::new(vec!["read".to_string()]),
856            auth_method: "password".to_string(),
857            client_id: Some("test-client".to_string()),
858            user_profile: None,
859            permissions: Permissions::new(vec!["read:data".to_string()]),
860            roles: Roles::new(vec!["user".to_string()]),
861            metadata: TokenMetadata::default(),
862        };
863
864        // Store token
865        storage.store_token(&token).await.unwrap();
866
867        // Get token by ID
868        let retrieved = storage.get_token("test-token").await.unwrap().unwrap();
869        assert_eq!(retrieved.user_id, "test-user");
870
871        // Get token by access token
872        let retrieved = storage
873            .get_token_by_access_token("access-123")
874            .await
875            .unwrap()
876            .unwrap();
877        assert_eq!(retrieved.token_id, "test-token");
878
879        // List user tokens
880        let user_tokens = storage.list_user_tokens("test-user").await.unwrap();
881        assert_eq!(user_tokens.len(), 1);
882
883        // Delete token
884        storage.delete_token("test-token").await.unwrap();
885        let retrieved = storage.get_token("test-token").await.unwrap();
886        assert!(retrieved.is_none());
887    }
888
889    #[tokio::test]
890    async fn test_session_operations() {
891        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-session-test");
892        let storage = DashMapMemoryStorage::new();
893
894        let session = SessionData {
895            session_id: "test-session".to_string(),
896            user_id: "test-user".to_string(),
897            created_at: chrono::Utc::now(),
898            last_activity: chrono::Utc::now(),
899            expires_at: chrono::Utc::now() + chrono::Duration::hours(1),
900            ip_address: Some("192.168.1.1".to_string()),
901            user_agent: Some("test-agent".to_string()),
902            data: HashMap::new(),
903        };
904
905        // Store session
906        storage
907            .store_session("test-session", &session)
908            .await
909            .unwrap();
910
911        // Get session
912        let retrieved = storage.get_session("test-session").await.unwrap().unwrap();
913        assert_eq!(retrieved.user_id, "test-user");
914
915        // List user sessions
916        let user_sessions = storage.list_user_sessions("test-user").await.unwrap();
917        assert_eq!(user_sessions.len(), 1);
918
919        // Delete session
920        storage.delete_session("test-session").await.unwrap();
921        let retrieved = storage.get_session("test-session").await.unwrap();
922        assert!(retrieved.is_none());
923    }
924
925    #[tokio::test]
926    async fn test_kv_operations() {
927        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-kv-test");
928        let storage = DashMapMemoryStorage::new();
929
930        let key = "test-key";
931        let value = b"test-value";
932
933        // Store KV
934        storage
935            .store_kv(key, value, Some(Duration::from_secs(3600)))
936            .await
937            .unwrap();
938
939        // Get KV
940        let retrieved = storage.get_kv(key).await.unwrap().unwrap();
941        assert_eq!(retrieved, value);
942
943        // Delete KV
944        storage.delete_kv(key).await.unwrap();
945        let retrieved = storage.get_kv(key).await.unwrap();
946        assert!(retrieved.is_none());
947    }
948
949    #[tokio::test]
950    async fn test_concurrent_operations_no_deadlock() {
951        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-concurrent-test");
952        let storage = std::sync::Arc::new(DashMapMemoryStorage::new());
953
954        let mut join_set = JoinSet::new();
955
956        // Spawn multiple tasks doing concurrent operations
957        for i in 0..10 {
958            let storage = storage.clone();
959            join_set.spawn(async move {
960                for j in 0..50 {
961                    let token = AuthToken {
962                        token_id: format!("token-{}-{}", i, j),
963                        user_id: format!("user-{}", i % 3), // Multiple users per task
964                        access_token: format!("access-{}-{}", i, j),
965                        token_type: Some("bearer".to_string()),
966                        subject: Some(format!("user-{}", i % 3)),
967                        issuer: Some("test-issuer".to_string()),
968                        refresh_token: None,
969                        issued_at: chrono::Utc::now(),
970                        expires_at: chrono::Utc::now() + chrono::Duration::hours(1),
971                        scopes: Scopes::new(vec!["read".to_string()]),
972                        auth_method: "password".to_string(),
973                        client_id: Some("test-client".to_string()),
974                        user_profile: None,
975                        permissions: Permissions::new(vec!["read:data".to_string()]),
976                        roles: Roles::new(vec!["user".to_string()]),
977                        metadata: TokenMetadata::default(),
978                    };
979
980                    // Store token
981                    storage.store_token(&token).await.unwrap();
982
983                    // Immediately list user tokens (tests cross-map operations)
984                    let _user_tokens = storage.list_user_tokens(&token.user_id).await.unwrap();
985
986                    // Get by access token
987                    let _retrieved = storage
988                        .get_token_by_access_token(&token.access_token)
989                        .await
990                        .unwrap();
991                }
992            });
993        }
994
995        // Wait for all tasks to complete (should not deadlock)
996        while join_set.join_next().await.is_some() {}
997
998        println!("✅ Concurrent operations test passed - no deadlocks detected!");
999    }
1000
1001    #[tokio::test]
1002    async fn test_ttl_expiration() {
1003        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-ttl-test");
1004        let storage = DashMapMemoryStorage::with_ttl(Duration::from_millis(100));
1005
1006        // Store a KV that should expire
1007        storage
1008            .store_kv("expiring-key", b"expiring-value", None)
1009            .await
1010            .unwrap();
1011
1012        // Should be available immediately
1013        let retrieved = storage.get_kv("expiring-key").await.unwrap();
1014        assert!(retrieved.is_some());
1015
1016        // Wait for expiration
1017        tokio::time::sleep(Duration::from_millis(150)).await;
1018
1019        // Should be expired and cleaned up
1020        let retrieved = storage.get_kv("expiring-key").await.unwrap();
1021        assert!(retrieved.is_none());
1022    }
1023
1024    #[tokio::test]
1025    async fn test_cleanup_expired() {
1026        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-cleanup-test");
1027        let storage = DashMapMemoryStorage::with_ttl(Duration::from_millis(50));
1028
1029        // Store multiple items that will expire
1030        for i in 0..10 {
1031            storage
1032                .store_kv(&format!("key-{}", i), b"value", None)
1033                .await
1034                .unwrap();
1035        }
1036
1037        // Wait for expiration
1038        tokio::time::sleep(Duration::from_millis(100)).await;
1039
1040        // Run cleanup
1041        storage.cleanup_expired().await.unwrap();
1042
1043        // Verify all items are cleaned up
1044        for i in 0..10 {
1045            let retrieved = storage.get_kv(&format!("key-{}", i)).await.unwrap();
1046            assert!(retrieved.is_none());
1047        }
1048    }
1049}