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