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 get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
742        // SAFE: Immediate value extraction
743        if let Some(timestamped) = self.kv_store.get(key) {
744            let created_at = timestamped.created_at;
745
746            if timestamped.is_expired() {
747                drop(timestamped);
748                self.kv_store.remove(key);
749
750                // Log expired KV access
751                self.log_storage_operation(
752                    AuditEventType::TokenExpired, // Data expiration
753                    "system",
754                    key,
755                    "kv_pair",
756                    Some(created_at),
757                    EventOutcome::Failure,
758                )
759                .await;
760
761                return Ok(None);
762            }
763
764            let data = timestamped.data.clone();
765            drop(timestamped);
766
767            // Log successful KV access
768            self.log_storage_operation(
769                AuditEventType::ConfigurationChanged, // KV access
770                "system",
771                key,
772                "kv_pair",
773                Some(created_at),
774                EventOutcome::Success,
775            )
776            .await;
777
778            Ok(Some(data))
779        } else {
780            Ok(None)
781        }
782    }
783
784    async fn delete_kv(&self, key: &str) -> Result<()> {
785        // SAFE: Extract creation timestamp before removal
786        let created_at = if let Some(timestamped) = self.kv_store.get(key) {
787            Some(timestamped.created_at)
788        } else {
789            None
790        };
791
792        self.kv_store.remove(key);
793
794        if let Some(created_at) = created_at {
795            // Log KV deletion with creation timestamp
796            self.log_storage_operation(
797                AuditEventType::ConfigurationChanged, // KV deletion
798                "system",
799                key,
800                "kv_pair",
801                Some(created_at),
802                EventOutcome::Success,
803            )
804            .await;
805        }
806
807        Ok(())
808    }
809
810    async fn cleanup_expired(&self) -> Result<()> {
811        // SAFE: Collect expired keys first, then remove them
812        let mut expired_tokens = Vec::new();
813        let mut expired_sessions = Vec::new();
814        let mut expired_kvs = Vec::new();
815
816        // SAFE: Scan for expired items (no cross-map operations)
817        for entry in self.tokens.iter() {
818            if entry.is_expired() {
819                expired_tokens.push(entry.key().clone());
820            }
821        }
822
823        for entry in self.sessions.iter() {
824            if entry.is_expired() {
825                expired_sessions.push(entry.key().clone());
826            }
827        }
828
829        for entry in self.kv_store.iter() {
830            if entry.is_expired() {
831                expired_kvs.push(entry.key().clone());
832            }
833        }
834
835        // SAFE: Remove expired items using extracted keys
836        for token_id in expired_tokens {
837            self.delete_token(&token_id).await?;
838        }
839
840        for session_id in expired_sessions {
841            self.delete_session(&session_id).await?;
842        }
843
844        for key in expired_kvs {
845            self.delete_kv(&key).await?;
846        }
847
848        Ok(())
849    }
850
851    async fn count_active_sessions(&self) -> Result<u64> {
852        let mut count = 0;
853
854        // Count all non-expired sessions
855        for entry in self.sessions.iter() {
856            if !entry.is_expired() {
857                count += 1;
858            }
859        }
860
861        Ok(count)
862    }
863}
864
865#[cfg(test)]
866mod tests {
867    use super::*;
868    use crate::{
869        testing::test_infrastructure::TestEnvironmentGuard,
870        tokens::TokenMetadata,
871        types::{Permissions, Roles, Scopes},
872    };
873    use std::collections::HashMap;
874    use tokio::task::JoinSet;
875
876    #[tokio::test]
877    async fn test_basic_token_operations() {
878        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-test");
879        let storage = DashMapMemoryStorage::new();
880
881        let token = AuthToken {
882            token_id: "test-token".to_string(),
883            user_id: "test-user".to_string(),
884            access_token: "access-123".to_string(),
885            token_type: Some("bearer".to_string()),
886            subject: Some("test-user".to_string()),
887            issuer: Some("test-issuer".to_string()),
888            refresh_token: None,
889            issued_at: chrono::Utc::now(),
890            expires_at: chrono::Utc::now() + chrono::Duration::hours(1),
891            scopes: Scopes::new(vec!["read".to_string()]),
892            auth_method: "password".to_string(),
893            client_id: Some("test-client".to_string()),
894            user_profile: None,
895            permissions: Permissions::new(vec!["read:data".to_string()]),
896            roles: Roles::new(vec!["user".to_string()]),
897            metadata: TokenMetadata::default(),
898        };
899
900        // Store token
901        storage.store_token(&token).await.unwrap();
902
903        // Get token by ID
904        let retrieved = storage.get_token("test-token").await.unwrap().unwrap();
905        assert_eq!(retrieved.user_id, "test-user");
906
907        // Get token by access token
908        let retrieved = storage
909            .get_token_by_access_token("access-123")
910            .await
911            .unwrap()
912            .unwrap();
913        assert_eq!(retrieved.token_id, "test-token");
914
915        // List user tokens
916        let user_tokens = storage.list_user_tokens("test-user").await.unwrap();
917        assert_eq!(user_tokens.len(), 1);
918
919        // Delete token
920        storage.delete_token("test-token").await.unwrap();
921        let retrieved = storage.get_token("test-token").await.unwrap();
922        assert!(retrieved.is_none());
923    }
924
925    #[tokio::test]
926    async fn test_session_operations() {
927        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-session-test");
928        let storage = DashMapMemoryStorage::new();
929
930        let session = SessionData {
931            session_id: "test-session".to_string(),
932            user_id: "test-user".to_string(),
933            created_at: chrono::Utc::now(),
934            last_activity: chrono::Utc::now(),
935            expires_at: chrono::Utc::now() + chrono::Duration::hours(1),
936            ip_address: Some("192.168.1.1".to_string()),
937            user_agent: Some("test-agent".to_string()),
938            data: HashMap::new(),
939        };
940
941        // Store session
942        storage
943            .store_session("test-session", &session)
944            .await
945            .unwrap();
946
947        // Get session
948        let retrieved = storage.get_session("test-session").await.unwrap().unwrap();
949        assert_eq!(retrieved.user_id, "test-user");
950
951        // List user sessions
952        let user_sessions = storage.list_user_sessions("test-user").await.unwrap();
953        assert_eq!(user_sessions.len(), 1);
954
955        // Delete session
956        storage.delete_session("test-session").await.unwrap();
957        let retrieved = storage.get_session("test-session").await.unwrap();
958        assert!(retrieved.is_none());
959    }
960
961    #[tokio::test]
962    async fn test_kv_operations() {
963        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-kv-test");
964        let storage = DashMapMemoryStorage::new();
965
966        let key = "test-key";
967        let value = b"test-value";
968
969        // Store KV
970        storage
971            .store_kv(key, value, Some(Duration::from_secs(3600)))
972            .await
973            .unwrap();
974
975        // Get KV
976        let retrieved = storage.get_kv(key).await.unwrap().unwrap();
977        assert_eq!(retrieved, value);
978
979        // Delete KV
980        storage.delete_kv(key).await.unwrap();
981        let retrieved = storage.get_kv(key).await.unwrap();
982        assert!(retrieved.is_none());
983    }
984
985    #[tokio::test]
986    async fn test_concurrent_operations_no_deadlock() {
987        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-concurrent-test");
988        let storage = std::sync::Arc::new(DashMapMemoryStorage::new());
989
990        let mut join_set = JoinSet::new();
991
992        // Spawn multiple tasks doing concurrent operations
993        for i in 0..10 {
994            let storage = storage.clone();
995            join_set.spawn(async move {
996                for j in 0..50 {
997                    let token = AuthToken {
998                        token_id: format!("token-{}-{}", i, j),
999                        user_id: format!("user-{}", i % 3), // Multiple users per task
1000                        access_token: format!("access-{}-{}", i, j),
1001                        token_type: Some("bearer".to_string()),
1002                        subject: Some(format!("user-{}", i % 3)),
1003                        issuer: Some("test-issuer".to_string()),
1004                        refresh_token: None,
1005                        issued_at: chrono::Utc::now(),
1006                        expires_at: chrono::Utc::now() + chrono::Duration::hours(1),
1007                        scopes: Scopes::new(vec!["read".to_string()]),
1008                        auth_method: "password".to_string(),
1009                        client_id: Some("test-client".to_string()),
1010                        user_profile: None,
1011                        permissions: Permissions::new(vec!["read:data".to_string()]),
1012                        roles: Roles::new(vec!["user".to_string()]),
1013                        metadata: TokenMetadata::default(),
1014                    };
1015
1016                    // Store token
1017                    storage.store_token(&token).await.unwrap();
1018
1019                    // Immediately list user tokens (tests cross-map operations)
1020                    let _user_tokens = storage.list_user_tokens(&token.user_id).await.unwrap();
1021
1022                    // Get by access token
1023                    let _retrieved = storage
1024                        .get_token_by_access_token(&token.access_token)
1025                        .await
1026                        .unwrap();
1027                }
1028            });
1029        }
1030
1031        // Wait for all tasks to complete (should not deadlock)
1032        while join_set.join_next().await.is_some() {}
1033
1034        println!("✅ Concurrent operations test passed - no deadlocks detected!");
1035    }
1036
1037    #[tokio::test]
1038    async fn test_ttl_expiration() {
1039        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-ttl-test");
1040        let storage = DashMapMemoryStorage::with_ttl(Duration::from_millis(100));
1041
1042        // Store a KV that should expire
1043        storage
1044            .store_kv("expiring-key", b"expiring-value", None)
1045            .await
1046            .unwrap();
1047
1048        // Should be available immediately
1049        let retrieved = storage.get_kv("expiring-key").await.unwrap();
1050        assert!(retrieved.is_some());
1051
1052        // Wait for expiration
1053        tokio::time::sleep(Duration::from_millis(150)).await;
1054
1055        // Should be expired and cleaned up
1056        let retrieved = storage.get_kv("expiring-key").await.unwrap();
1057        assert!(retrieved.is_none());
1058    }
1059
1060    #[tokio::test]
1061    async fn test_cleanup_expired() {
1062        let _env = TestEnvironmentGuard::new().with_jwt_secret("dashmap-cleanup-test");
1063        let storage = DashMapMemoryStorage::with_ttl(Duration::from_millis(50));
1064
1065        // Store multiple items that will expire
1066        for i in 0..10 {
1067            storage
1068                .store_kv(&format!("key-{}", i), b"value", None)
1069                .await
1070                .unwrap();
1071        }
1072
1073        // Wait for expiration
1074        tokio::time::sleep(Duration::from_millis(100)).await;
1075
1076        // Run cleanup
1077        storage.cleanup_expired().await.unwrap();
1078
1079        // Verify all items are cleaned up
1080        for i in 0..10 {
1081            let retrieved = storage.get_kv(&format!("key-{}", i)).await.unwrap();
1082            assert!(retrieved.is_none());
1083        }
1084    }
1085}