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            if timestamped.is_expired() {
474                drop(timestamped); // Release reference
475                self.tokens.remove(token_id); // Cleanup expired
476
477                // Log expired token access attempt
478                self.log_storage_operation(
479                    AuditEventType::TokenExpired,
480                    &user_id,
481                    token_id,
482                    "token",
483                    Some(created_at),
484                    EventOutcome::Failure,
485                )
486                .await;
487
488                return Ok(None);
489            }
490
491            let token = timestamped.token.clone();
492            drop(timestamped); // Release reference
493
494            // Log successful token access
495            self.log_storage_operation(
496                AuditEventType::LoginSuccess, // Token access represents authentication validation
497                &user_id,
498                token_id,
499                "token",
500                Some(created_at),
501                EventOutcome::Success,
502            )
503            .await;
504
505            Ok(Some(token))
506        } else {
507            Ok(None)
508        }
509    }
510
511    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>> {
512        // SAFE: Two-step lookup with immediate value extraction
513        if let Some(token_id_entry) = self.access_token_to_id.get(access_token) {
514            let token_id = token_id_entry.clone(); // Extract value immediately
515            drop(token_id_entry); // Release first map reference
516            self.get_token(&token_id).await // Use extracted value
517        } else {
518            Ok(None)
519        }
520    }
521
522    async fn update_token(&self, token: &AuthToken) -> Result<()> {
523        // SAFE: Update is same as store for this implementation
524        self.store_token(token).await
525    }
526
527    async fn delete_token(&self, token_id: &str) -> Result<()> {
528        // SAFE: Extract token info before removal to avoid reference issues
529        let token_info = if let Some(timestamped) = self.tokens.get(token_id) {
530            Some((
531                timestamped.token.user_id.clone(),
532                timestamped.token.access_token.clone(),
533                timestamped.created_at,
534            ))
535        } else {
536            None
537        };
538
539        if let Some((user_id, access_token, created_at)) = token_info {
540            // SAFE: All operations use extracted values, no cross-map references
541            self.tokens.remove(token_id);
542            self.access_token_to_id.remove(&access_token);
543            self.remove_token_from_user_index(&user_id, token_id);
544
545            // Log token deletion with creation timestamp for audit trail
546            self.log_storage_operation(
547                AuditEventType::TokenRevoked,
548                &user_id,
549                token_id,
550                "token",
551                Some(created_at),
552                EventOutcome::Success,
553            )
554            .await;
555        }
556
557        Ok(())
558    }
559
560    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
561        // SAFE: Extract token IDs first, then lookup individually
562        let token_ids = if let Some(ids) = self.user_to_tokens.get(user_id) {
563            ids.clone() // Immediate extraction
564        } else {
565            return Ok(Vec::new());
566        };
567
568        let mut tokens = Vec::new();
569        let mut expired_tokens = Vec::new();
570
571        // SAFE: Iterate over extracted IDs, no cross-map reference holding
572        for token_id in token_ids {
573            if let Some(timestamped) = self.tokens.get(&token_id) {
574                if timestamped.is_expired() {
575                    expired_tokens.push(token_id);
576                } else {
577                    tokens.push(timestamped.token.clone());
578                }
579            } else {
580                expired_tokens.push(token_id); // Token was removed elsewhere
581            }
582        }
583
584        // SAFE: Cleanup expired tokens (uses extracted IDs)
585        for token_id in expired_tokens {
586            self.delete_token(&token_id).await?;
587        }
588
589        Ok(tokens)
590    }
591
592    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()> {
593        let timestamped = TimestampedSession::new(data.clone());
594        let created_at = timestamped.created_at;
595
596        // SAFE: Store in primary map first
597        self.sessions.insert(session_id.to_string(), timestamped);
598
599        // SAFE: Update user index (atomic operation)
600        self.add_session_to_user_index(&data.user_id, session_id);
601
602        // Log session storage with creation timestamp
603        self.log_storage_operation(
604            AuditEventType::LoginSuccess, // Session creation represents successful login
605            &data.user_id,
606            session_id,
607            "session",
608            Some(created_at),
609            EventOutcome::Success,
610        )
611        .await;
612
613        Ok(())
614    }
615
616    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
617        // SAFE: Immediate value extraction
618        if let Some(timestamped) = self.sessions.get(session_id) {
619            let created_at = timestamped.created_at;
620            let user_id = timestamped.session.user_id.clone();
621
622            if timestamped.is_expired() {
623                drop(timestamped);
624                self.sessions.remove(session_id);
625
626                // Log expired session access
627                self.log_storage_operation(
628                    AuditEventType::TokenExpired, // Session expiration
629                    &user_id,
630                    session_id,
631                    "session",
632                    Some(created_at),
633                    EventOutcome::Failure,
634                )
635                .await;
636
637                return Ok(None);
638            }
639
640            let session = timestamped.session.clone();
641            drop(timestamped);
642
643            // Log successful session access
644            self.log_storage_operation(
645                AuditEventType::LoginSuccess, // Session access represents continued authentication
646                &user_id,
647                session_id,
648                "session",
649                Some(created_at),
650                EventOutcome::Success,
651            )
652            .await;
653
654            Ok(Some(session))
655        } else {
656            Ok(None)
657        }
658    }
659
660    async fn delete_session(&self, session_id: &str) -> Result<()> {
661        // SAFE: Extract session info before removal
662        let session_info = if let Some(timestamped) = self.sessions.get(session_id) {
663            Some((timestamped.session.user_id.clone(), timestamped.created_at))
664        } else {
665            None
666        };
667
668        if let Some((user_id, created_at)) = session_info {
669            self.sessions.remove(session_id);
670            self.remove_session_from_user_index(&user_id, session_id);
671
672            // Log session deletion with creation timestamp
673            self.log_storage_operation(
674                AuditEventType::Logout,
675                &user_id,
676                session_id,
677                "session",
678                Some(created_at),
679                EventOutcome::Success,
680            )
681            .await;
682        }
683
684        Ok(())
685    }
686
687    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> {
688        // SAFE: Extract session IDs first
689        let session_ids = if let Some(ids) = self.user_to_sessions.get(user_id) {
690            ids.clone()
691        } else {
692            return Ok(Vec::new());
693        };
694
695        let mut sessions = Vec::new();
696        let mut expired_sessions = Vec::new();
697
698        // SAFE: Iterate over extracted IDs
699        for session_id in session_ids {
700            if let Some(timestamped) = self.sessions.get(&session_id) {
701                if timestamped.is_expired() {
702                    expired_sessions.push(session_id);
703                } else {
704                    sessions.push(timestamped.session.clone());
705                }
706            } else {
707                expired_sessions.push(session_id);
708            }
709        }
710
711        // SAFE: Cleanup expired sessions
712        for session_id in expired_sessions {
713            self.delete_session(&session_id).await?;
714        }
715
716        Ok(sessions)
717    }
718
719    async fn store_kv(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()> {
720        let timestamped = TimestampedValue::new(value.to_vec(), ttl.or(self.default_ttl));
721        let created_at = timestamped.created_at;
722
723        self.kv_store.insert(key.to_string(), timestamped);
724
725        // Log KV storage operation with creation timestamp
726        self.log_storage_operation(
727            AuditEventType::ConfigurationChanged, // KV operations represent configuration/data changes
728            "system",                             // KV operations are typically system-level
729            key,
730            "kv_pair",
731            Some(created_at),
732            EventOutcome::Success,
733        )
734        .await;
735
736        Ok(())
737    }
738
739    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
740        // SAFE: Immediate value extraction
741        if let Some(timestamped) = self.kv_store.get(key) {
742            let created_at = timestamped.created_at;
743
744            if timestamped.is_expired() {
745                drop(timestamped);
746                self.kv_store.remove(key);
747
748                // Log expired KV access
749                self.log_storage_operation(
750                    AuditEventType::TokenExpired, // Data expiration
751                    "system",
752                    key,
753                    "kv_pair",
754                    Some(created_at),
755                    EventOutcome::Failure,
756                )
757                .await;
758
759                return Ok(None);
760            }
761
762            let data = timestamped.data.clone();
763            drop(timestamped);
764
765            // Log successful KV access
766            self.log_storage_operation(
767                AuditEventType::ConfigurationChanged, // KV access
768                "system",
769                key,
770                "kv_pair",
771                Some(created_at),
772                EventOutcome::Success,
773            )
774            .await;
775
776            Ok(Some(data))
777        } else {
778            Ok(None)
779        }
780    }
781
782    async fn delete_kv(&self, key: &str) -> Result<()> {
783        // SAFE: Extract creation timestamp before removal
784        let created_at = if let Some(timestamped) = self.kv_store.get(key) {
785            Some(timestamped.created_at)
786        } else {
787            None
788        };
789
790        self.kv_store.remove(key);
791
792        if let Some(created_at) = created_at {
793            // Log KV deletion with creation timestamp
794            self.log_storage_operation(
795                AuditEventType::ConfigurationChanged, // KV deletion
796                "system",
797                key,
798                "kv_pair",
799                Some(created_at),
800                EventOutcome::Success,
801            )
802            .await;
803        }
804
805        Ok(())
806    }
807
808    async fn cleanup_expired(&self) -> Result<()> {
809        // SAFE: Collect expired keys first, then remove them
810        let mut expired_tokens = Vec::new();
811        let mut expired_sessions = Vec::new();
812        let mut expired_kvs = Vec::new();
813
814        // SAFE: Scan for expired items (no cross-map operations)
815        for entry in self.tokens.iter() {
816            if entry.is_expired() {
817                expired_tokens.push(entry.key().clone());
818            }
819        }
820
821        for entry in self.sessions.iter() {
822            if entry.is_expired() {
823                expired_sessions.push(entry.key().clone());
824            }
825        }
826
827        for entry in self.kv_store.iter() {
828            if entry.is_expired() {
829                expired_kvs.push(entry.key().clone());
830            }
831        }
832
833        // SAFE: Remove expired items using extracted keys
834        for token_id in expired_tokens {
835            self.delete_token(&token_id).await?;
836        }
837
838        for session_id in expired_sessions {
839            self.delete_session(&session_id).await?;
840        }
841
842        for key in expired_kvs {
843            self.delete_kv(&key).await?;
844        }
845
846        Ok(())
847    }
848
849    async fn count_active_sessions(&self) -> Result<u64> {
850        let mut count = 0;
851
852        // Count all non-expired sessions
853        for entry in self.sessions.iter() {
854            if !entry.is_expired() {
855                count += 1;
856            }
857        }
858
859        Ok(count)
860    }
861}
862
863#[cfg(test)]
864mod tests {
865    use super::*;
866    use crate::{
867        testing::test_infrastructure::TestEnvironmentGuard,
868        tokens::TokenMetadata,
869        types::{Permissions, Roles, Scopes},
870    };
871    use std::collections::HashMap;
872    use tokio::task::JoinSet;
873
874    #[tokio::test]
875    async fn test_basic_token_operations() {
876        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-test");
877        let storage = DashMapMemoryStorage::new();
878
879        let token = AuthToken {
880            token_id: "test-token".to_string(),
881            user_id: "test-user".to_string(),
882            access_token: "access-123".to_string(),
883            token_type: Some("bearer".to_string()),
884            subject: Some("test-user".to_string()),
885            issuer: Some("test-issuer".to_string()),
886            refresh_token: None,
887            issued_at: chrono::Utc::now(),
888            expires_at: chrono::Utc::now() + chrono::Duration::hours(1),
889            scopes: Scopes::new(vec!["read".to_string()]),
890            auth_method: "password".to_string(),
891            client_id: Some("test-client".to_string()),
892            user_profile: None,
893            permissions: Permissions::new(vec!["read:data".to_string()]),
894            roles: Roles::new(vec!["user".to_string()]),
895            metadata: TokenMetadata::default(),
896        };
897
898        // Store token
899        storage.store_token(&token).await.unwrap();
900
901        // Get token by ID
902        let retrieved = storage.get_token("test-token").await.unwrap().unwrap();
903        assert_eq!(retrieved.user_id, "test-user");
904
905        // Get token by access token
906        let retrieved = storage
907            .get_token_by_access_token("access-123")
908            .await
909            .unwrap()
910            .unwrap();
911        assert_eq!(retrieved.token_id, "test-token");
912
913        // List user tokens
914        let user_tokens = storage.list_user_tokens("test-user").await.unwrap();
915        assert_eq!(user_tokens.len(), 1);
916
917        // Delete token
918        storage.delete_token("test-token").await.unwrap();
919        let retrieved = storage.get_token("test-token").await.unwrap();
920        assert!(retrieved.is_none());
921    }
922
923    #[tokio::test]
924    async fn test_session_operations() {
925        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-session-test");
926        let storage = DashMapMemoryStorage::new();
927
928        let session = SessionData {
929            session_id: "test-session".to_string(),
930            user_id: "test-user".to_string(),
931            created_at: chrono::Utc::now(),
932            last_activity: chrono::Utc::now(),
933            expires_at: chrono::Utc::now() + chrono::Duration::hours(1),
934            ip_address: Some("192.168.1.1".to_string()),
935            user_agent: Some("test-agent".to_string()),
936            data: HashMap::new(),
937        };
938
939        // Store session
940        storage
941            .store_session("test-session", &session)
942            .await
943            .unwrap();
944
945        // Get session
946        let retrieved = storage.get_session("test-session").await.unwrap().unwrap();
947        assert_eq!(retrieved.user_id, "test-user");
948
949        // List user sessions
950        let user_sessions = storage.list_user_sessions("test-user").await.unwrap();
951        assert_eq!(user_sessions.len(), 1);
952
953        // Delete session
954        storage.delete_session("test-session").await.unwrap();
955        let retrieved = storage.get_session("test-session").await.unwrap();
956        assert!(retrieved.is_none());
957    }
958
959    #[tokio::test]
960    async fn test_kv_operations() {
961        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-kv-test");
962        let storage = DashMapMemoryStorage::new();
963
964        let key = "test-key";
965        let value = b"test-value";
966
967        // Store KV
968        storage
969            .store_kv(key, value, Some(Duration::from_secs(3600)))
970            .await
971            .unwrap();
972
973        // Get KV
974        let retrieved = storage.get_kv(key).await.unwrap().unwrap();
975        assert_eq!(retrieved, value);
976
977        // Delete KV
978        storage.delete_kv(key).await.unwrap();
979        let retrieved = storage.get_kv(key).await.unwrap();
980        assert!(retrieved.is_none());
981    }
982
983    #[tokio::test]
984    async fn test_concurrent_operations_no_deadlock() {
985        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-concurrent-test");
986        let storage = std::sync::Arc::new(DashMapMemoryStorage::new());
987
988        let mut join_set = JoinSet::new();
989
990        // Spawn multiple tasks doing concurrent operations
991        for i in 0..10 {
992            let storage = storage.clone();
993            join_set.spawn(async move {
994                for j in 0..50 {
995                    let token = AuthToken {
996                        token_id: format!("token-{}-{}", i, j),
997                        user_id: format!("user-{}", i % 3), // Multiple users per task
998                        access_token: format!("access-{}-{}", i, j),
999                        token_type: Some("bearer".to_string()),
1000                        subject: Some(format!("user-{}", i % 3)),
1001                        issuer: Some("test-issuer".to_string()),
1002                        refresh_token: None,
1003                        issued_at: chrono::Utc::now(),
1004                        expires_at: chrono::Utc::now() + chrono::Duration::hours(1),
1005                        scopes: Scopes::new(vec!["read".to_string()]),
1006                        auth_method: "password".to_string(),
1007                        client_id: Some("test-client".to_string()),
1008                        user_profile: None,
1009                        permissions: Permissions::new(vec!["read:data".to_string()]),
1010                        roles: Roles::new(vec!["user".to_string()]),
1011                        metadata: TokenMetadata::default(),
1012                    };
1013
1014                    // Store token
1015                    storage.store_token(&token).await.unwrap();
1016
1017                    // Immediately list user tokens (tests cross-map operations)
1018                    let _user_tokens = storage.list_user_tokens(&token.user_id).await.unwrap();
1019
1020                    // Get by access token
1021                    let _retrieved = storage
1022                        .get_token_by_access_token(&token.access_token)
1023                        .await
1024                        .unwrap();
1025                }
1026            });
1027        }
1028
1029        // Wait for all tasks to complete (should not deadlock)
1030        while join_set.join_next().await.is_some() {}
1031
1032        println!("✅ Concurrent operations test passed - no deadlocks detected!");
1033    }
1034
1035    #[tokio::test]
1036    async fn test_ttl_expiration() {
1037        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-ttl-test");
1038        let storage = DashMapMemoryStorage::with_ttl(Duration::from_millis(100));
1039
1040        // Store a KV that should expire
1041        storage
1042            .store_kv("expiring-key", b"expiring-value", None)
1043            .await
1044            .unwrap();
1045
1046        // Should be available immediately
1047        let retrieved = storage.get_kv("expiring-key").await.unwrap();
1048        assert!(retrieved.is_some());
1049
1050        // Wait for expiration
1051        tokio::time::sleep(Duration::from_millis(150)).await;
1052
1053        // Should be expired and cleaned up
1054        let retrieved = storage.get_kv("expiring-key").await.unwrap();
1055        assert!(retrieved.is_none());
1056    }
1057
1058    #[tokio::test]
1059    async fn test_cleanup_expired() {
1060        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-cleanup-test");
1061        let storage = DashMapMemoryStorage::with_ttl(Duration::from_millis(50));
1062
1063        // Store multiple items that will expire
1064        for i in 0..10 {
1065            storage
1066                .store_kv(&format!("key-{}", i), b"value", None)
1067                .await
1068                .unwrap();
1069        }
1070
1071        // Wait for expiration
1072        tokio::time::sleep(Duration::from_millis(100)).await;
1073
1074        // Run cleanup
1075        storage.cleanup_expired().await.unwrap();
1076
1077        // Verify all items are cleaned up
1078        for i in 0..10 {
1079            let retrieved = storage.get_kv(&format!("key-{}", i)).await.unwrap();
1080            assert!(retrieved.is_none());
1081        }
1082    }
1083}