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