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