Skip to main content

auth_framework/storage/
dashmap_memory.rs

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