Skip to main content

auth_framework/auth_modular/
session_manager.rs

1//! Session management module
2
3use crate::distributed::{DistributedSessionStore, LocalOnlySessionStore};
4use crate::errors::{AuthError, Result};
5use crate::storage::{AuthStorage, SessionData};
6use std::collections::HashMap;
7use std::sync::Arc;
8use std::time::Duration;
9use tracing::{debug, info, warn};
10
11/// Statistics from a distributed session coordination pass.
12///
13/// # Example
14/// ```rust,ignore
15/// let stats = session_mgr.coordinate_distributed_sessions().await?;
16/// println!("local={}, remote={}", stats.local_active_sessions, stats.remote_active_sessions);
17/// ```
18#[derive(Debug)]
19pub struct SessionCoordinationStats {
20    pub local_active_sessions: u64,
21    pub remote_active_sessions: u64,
22    pub synchronized_sessions: u64,
23    pub coordination_conflicts: u64,
24    pub last_coordination_time: chrono::DateTime<chrono::Utc>,
25}
26
27/// Session manager for handling user sessions.
28///
29/// # Example
30/// ```rust,ignore
31/// use auth_framework::auth_modular::SessionManager;
32/// use std::sync::Arc;
33///
34/// let mgr = SessionManager::new(storage.clone());
35/// let sid = mgr.create_session("user-1", Duration::from_secs(3600), None, None).await?;
36/// ```
37pub struct SessionManager {
38    storage: Arc<dyn AuthStorage>,
39    distributed_store: Arc<dyn DistributedSessionStore>,
40}
41
42impl SessionManager {
43    /// Create a new session manager.
44    ///
45    /// # Example
46    /// ```rust,ignore
47    /// use auth_framework::auth_modular::SessionManager;
48    /// let mgr = SessionManager::new(storage.clone());
49    /// ```
50    pub fn new(storage: Arc<dyn AuthStorage>) -> Self {
51        Self {
52            storage,
53            distributed_store: Arc::new(LocalOnlySessionStore),
54        }
55    }
56
57    /// Replace the distributed session store (multi-node deployments).
58    ///
59    /// # Example
60    /// ```rust,ignore
61    /// mgr.set_distributed_store(Arc::new(RedisSessionStore::new("redis://...").await?));
62    /// ```
63    pub fn set_distributed_store(&mut self, store: Arc<dyn DistributedSessionStore>) {
64        self.distributed_store = store;
65    }
66
67    /// Create a new session.
68    ///
69    /// # Example
70    /// ```rust,ignore
71    /// let sid = mgr.create_session(
72    ///     "user-1",
73    ///     Duration::from_secs(3600),
74    ///     Some("127.0.0.1".into()),
75    ///     Some("Mozilla/5.0".into()),
76    /// ).await?;
77    /// ```
78    pub async fn create_session(
79        &self,
80        user_id: &str,
81        expires_in: Duration,
82        ip_address: Option<String>,
83        user_agent: Option<String>,
84    ) -> Result<String> {
85        debug!("Creating session for user '{}'", user_id);
86
87        // Validate session duration
88        if expires_in.is_zero() {
89            return Err(AuthError::invalid_credential(
90                "session_duration",
91                "Session duration must be greater than zero",
92            ));
93        }
94
95        if expires_in > Duration::from_secs(365 * 24 * 60 * 60) {
96            // 1 year max
97            return Err(AuthError::invalid_credential(
98                "session_duration",
99                "Session duration exceeds maximum allowed (1 year)",
100            ));
101        }
102
103        let session_id = crate::utils::string::generate_id(Some("sess"));
104        let session = SessionData::new(session_id.clone(), user_id, expires_in)
105            .with_metadata(ip_address, user_agent);
106
107        self.storage.store_session(&session_id, &session).await?;
108
109        info!(
110            "Session '{}' created for user '{}'",
111            crate::utils::redact::fingerprint(&session_id),
112            user_id
113        );
114        Ok(session_id)
115    }
116
117    /// Get session information.
118    ///
119    /// Returns `None` if the session does not exist or has expired.
120    ///
121    /// # Example
122    /// ```rust,ignore
123    /// if let Some(session) = mgr.get_session("sess_abc").await? {
124    ///     println!("user: {}", session.user_id);
125    /// }
126    /// ```
127    pub async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
128        debug!(
129            "Getting session '{}'",
130            crate::utils::redact::fingerprint(session_id)
131        );
132
133        let session = self.storage.get_session(session_id).await?;
134
135        // Check if session is expired
136        if let Some(ref session_data) = session
137            && session_data.is_expired()
138        {
139            // Remove expired session
140            let _ = self.delete_session(session_id).await;
141            return Ok(None);
142        }
143
144        Ok(session)
145    }
146
147    /// Delete a session.
148    ///
149    /// # Example
150    /// ```rust,ignore
151    /// mgr.delete_session("sess_abc").await?;
152    /// ```
153    pub async fn delete_session(&self, session_id: &str) -> Result<()> {
154        debug!(
155            "Deleting session '{}'",
156            crate::utils::redact::fingerprint(session_id)
157        );
158
159        self.storage.delete_session(session_id).await?;
160        info!(
161            "Session '{}' deleted",
162            crate::utils::redact::fingerprint(session_id)
163        );
164        Ok(())
165    }
166
167    /// Update session last activity timestamp.
168    ///
169    /// # Example
170    /// ```rust,ignore
171    /// mgr.update_session_activity("sess_abc").await?;
172    /// ```
173    pub async fn update_session_activity(&self, session_id: &str) -> Result<()> {
174        if let Some(mut session) = self.storage.get_session(session_id).await? {
175            session.last_activity = chrono::Utc::now();
176            self.storage.store_session(session_id, &session).await?;
177        }
178        Ok(())
179    }
180
181    /// Get all active (non-expired) sessions for a user.
182    ///
183    /// # Example
184    /// ```rust,ignore
185    /// let sessions = mgr.get_user_sessions("user-1").await?;
186    /// for (id, data) in &sessions {
187    ///     println!("session {}: ip={:?}", id, data.ip_address);
188    /// }
189    /// ```
190    pub async fn get_user_sessions(&self, user_id: &str) -> Result<Vec<(String, SessionData)>> {
191        debug!("Getting all sessions for user '{}'", user_id);
192        let sessions = self.storage.list_user_sessions(user_id).await?;
193        Ok(sessions
194            .into_iter()
195            .filter(|s| !s.is_expired())
196            .map(|s| (s.session_id.clone(), s))
197            .collect())
198    }
199
200    /// Delete all sessions for a user.
201    ///
202    /// # Example
203    /// ```rust,ignore
204    /// mgr.delete_user_sessions("user-1").await?;
205    /// ```
206    pub async fn delete_user_sessions(&self, user_id: &str) -> Result<()> {
207        debug!("Deleting all sessions for user '{}'", user_id);
208
209        // Get user sessions and delete them
210        let sessions = self.get_user_sessions(user_id).await?;
211        for (session_id, _) in sessions {
212            let _ = self.delete_session(&session_id).await;
213        }
214
215        info!("All sessions deleted for user '{}'", user_id);
216        Ok(())
217    }
218
219    /// Clean up expired sessions from storage.
220    ///
221    /// # Example
222    /// ```rust,ignore
223    /// mgr.cleanup_expired_sessions().await?;
224    /// ```
225    pub async fn cleanup_expired_sessions(&self) -> Result<()> {
226        debug!("Cleaning up expired sessions");
227        self.storage.cleanup_expired().await?;
228        info!("Expired sessions cleaned up");
229        Ok(())
230    }
231
232    /// Validate a session and return the owning user ID.
233    ///
234    /// Returns `None` if the session is missing or expired.
235    ///
236    /// # Example
237    /// ```rust,ignore
238    /// if let Some(user_id) = mgr.validate_session("sess_abc").await? {
239    ///     println!("session belongs to {}", user_id);
240    /// }
241    /// ```
242    pub async fn validate_session(&self, session_id: &str) -> Result<Option<String>> {
243        if let Some(session) = self.get_session(session_id).await?
244            && !session.is_expired()
245        {
246            // Update last activity
247            let _ = self.update_session_activity(session_id).await;
248            return Ok(Some(session.user_id));
249        }
250        Ok(None)
251    }
252
253    /// Extend session expiration by `additional_time`.
254    ///
255    /// # Example
256    /// ```rust,ignore
257    /// mgr.extend_session("sess_abc", Duration::from_secs(1800)).await?;
258    /// ```
259    pub async fn extend_session(&self, session_id: &str, additional_time: Duration) -> Result<()> {
260        debug!(
261            "Extending session '{}' by {:?}",
262            crate::utils::redact::fingerprint(session_id),
263            additional_time
264        );
265
266        if let Some(mut session) = self.storage.get_session(session_id).await? {
267            session.expires_at += chrono::Duration::from_std(additional_time)
268                .map_err(|e| AuthError::internal(format!("Failed to convert duration: {}", e)))?;
269            self.storage.store_session(session_id, &session).await?;
270            info!(
271                "Session '{}' extended",
272                crate::utils::redact::fingerprint(session_id)
273            );
274        }
275
276        Ok(())
277    }
278
279    /// Create a new session with resource-limit guards.
280    ///
281    /// Enforces a global cap of 100 000 total sessions and a per-user cap
282    /// of 50 sessions to prevent DoS / resource exhaustion.
283    ///
284    /// Returns `(session_id, new_total_count)` so the caller can update monitoring.
285    ///
286    /// # Example
287    /// ```rust,ignore
288    /// let (sid, total) = mgr.create_session_limited(
289    ///     "user-1", Duration::from_secs(3600), None, None,
290    /// ).await?;
291    /// println!("created session {} (total active: {})", sid, total);
292    /// ```
293    pub async fn create_session_limited(
294        &self,
295        user_id: &str,
296        expires_in: Duration,
297        ip_address: Option<String>,
298        user_agent: Option<String>,
299    ) -> Result<(String, u64)> {
300        const MAX_TOTAL_SESSIONS: u64 = 100_000;
301        let total_sessions = self.count_active_sessions().await?;
302        if total_sessions >= MAX_TOTAL_SESSIONS {
303            warn!(
304                "Maximum total sessions ({}) exceeded, rejecting new session",
305                MAX_TOTAL_SESSIONS
306            );
307            return Err(AuthError::rate_limit(
308                "Maximum concurrent sessions exceeded. Please try again later.",
309            ));
310        }
311
312        const MAX_USER_SESSIONS: usize = 50;
313        let user_sessions = self.storage.list_user_sessions(user_id).await?;
314        if user_sessions.len() >= MAX_USER_SESSIONS {
315            warn!(
316                "User '{}' has reached maximum sessions ({})",
317                user_id, MAX_USER_SESSIONS
318            );
319            return Err(AuthError::TooManyConcurrentSessions);
320        }
321
322        let session_id = self
323            .create_session(user_id, expires_in, ip_address, user_agent)
324            .await?;
325        Ok((session_id, total_sessions + 1))
326    }
327
328    /// Count the number of currently active sessions.
329    ///
330    /// Used for security audit statistics.
331    ///
332    /// # Example
333    /// ```rust,ignore
334    /// let n = mgr.count_active_sessions().await?;
335    /// println!("{} active sessions", n);
336    /// ```
337    pub async fn count_active_sessions(&self) -> Result<u64> {
338        debug!("Counting active sessions");
339
340        // Use the storage layer's count_active_sessions method
341        let active_count = self.storage.count_active_sessions().await?;
342
343        debug!("Found {} active sessions", active_count);
344        Ok(active_count)
345    }
346
347    /// Get security metrics for sessions.
348    ///
349    /// # Example
350    /// ```rust,ignore
351    /// let metrics = mgr.get_session_security_metrics().await?;
352    /// println!("active: {:?}", metrics.get("active_sessions"));
353    /// ```
354    pub async fn get_session_security_metrics(&self) -> Result<HashMap<String, serde_json::Value>> {
355        debug!("Collecting session security metrics");
356
357        let mut metrics = HashMap::new();
358        let active_count = self.count_active_sessions().await?;
359
360        metrics.insert(
361            "active_sessions".to_string(),
362            serde_json::Value::Number(serde_json::Number::from(active_count)),
363        );
364        metrics.insert(
365            "last_check".to_string(),
366            serde_json::Value::String(chrono::Utc::now().to_rfc3339()),
367        );
368
369        Ok(metrics)
370    }
371
372    /// Coordinate session state across distributed instances.
373    ///
374    /// # Example
375    /// ```rust,ignore
376    /// let stats = mgr.coordinate_distributed_sessions().await?;
377    /// println!("synced: {}", stats.synchronized_sessions);
378    /// ```
379    pub async fn coordinate_distributed_sessions(&self) -> Result<SessionCoordinationStats> {
380        tracing::debug!("Coordinating distributed sessions across instances");
381
382        let local_sessions = self.count_active_sessions().await?;
383
384        let coordination_stats = SessionCoordinationStats {
385            local_active_sessions: local_sessions as u64,
386            remote_active_sessions: self.estimate_remote_sessions().await?,
387            synchronized_sessions: self.count_synchronized_sessions().await?,
388            coordination_conflicts: 0,
389            last_coordination_time: chrono::Utc::now(),
390        };
391
392        self.broadcast_session_state().await?;
393        self.resolve_session_conflicts().await?;
394
395        tracing::info!(
396            "Session coordination complete - Local: {}, Remote: {}, Synchronized: {}",
397            coordination_stats.local_active_sessions,
398            coordination_stats.remote_active_sessions,
399            coordination_stats.synchronized_sessions
400        );
401
402        Ok(coordination_stats)
403    }
404
405    /// Estimate active sessions on remote instances by querying the distributed store.
406    async fn estimate_remote_sessions(&self) -> Result<u64> {
407        let total = self.distributed_store.total_session_count().await?;
408        if total == 0 {
409            tracing::debug!("No distributed session store configured; remote session count = 0");
410            return Ok(0);
411        }
412        let local = self.count_active_sessions().await.unwrap_or(0);
413        let remote = total.saturating_sub(local);
414        tracing::debug!(
415            "Distributed session count: total={}, local={}, remote={}",
416            total,
417            local,
418            remote
419        );
420        Ok(remote)
421    }
422
423    /// Count sessions synchronized across instances.
424    async fn count_synchronized_sessions(&self) -> Result<u64> {
425        let metrics = self.get_session_security_metrics().await?;
426        let synchronized = metrics
427            .get("synchronized_sessions")
428            .and_then(|v| v.as_u64())
429            .unwrap_or(0);
430        tracing::debug!("Synchronized sessions count: {}", synchronized);
431        Ok(synchronized)
432    }
433
434    /// Broadcast local session state to other instances (no-op for single-node).
435    async fn broadcast_session_state(&self) -> Result<()> {
436        let count = self.count_active_sessions().await.unwrap_or(0);
437        tracing::debug!("Session state broadcast completed for {} sessions", count);
438        Ok(())
439    }
440
441    /// Resolve session conflicts between instances (no-op for single-node).
442    async fn resolve_session_conflicts(&self) -> Result<()> {
443        tracing::debug!("Session conflict resolution completed (no-op for single-instance)");
444        Ok(())
445    }
446
447    /// Synchronize a specific session with remote instances.
448    ///
449    /// # Example
450    /// ```rust,ignore
451    /// mgr.synchronize_session("sess_abc").await?;
452    /// ```
453    pub async fn synchronize_session(&self, session_id: &str) -> Result<()> {
454        if self.get_session(session_id).await?.is_none() {
455            return Err(AuthError::validation(format!(
456                "Session {} not found",
457                crate::utils::redact::fingerprint(session_id)
458            )));
459        }
460        tracing::info!(
461            "Session {} synchronized (single-instance)",
462            crate::utils::redact::fingerprint(session_id)
463        );
464        Ok(())
465    }
466}
467
468#[cfg(test)]
469mod tests {
470    use super::*;
471    use crate::storage::MemoryStorage;
472
473    fn make_manager() -> SessionManager {
474        SessionManager::new(Arc::new(MemoryStorage::new()))
475    }
476
477    // ── create_session ──────────────────────────────────────────────────
478
479    #[tokio::test]
480    async fn test_create_session_success() {
481        let mgr = make_manager();
482        let sid = mgr
483            .create_session("u1", Duration::from_secs(600), None, None)
484            .await
485            .unwrap();
486        assert!(sid.starts_with("sess"));
487    }
488
489    #[tokio::test]
490    async fn test_create_session_with_metadata() {
491        let mgr = make_manager();
492        let sid = mgr
493            .create_session(
494                "u2",
495                Duration::from_secs(600),
496                Some("127.0.0.1".into()),
497                Some("TestUA".into()),
498            )
499            .await
500            .unwrap();
501        let session = mgr.get_session(&sid).await.unwrap().unwrap();
502        assert_eq!(session.ip_address.as_deref(), Some("127.0.0.1"));
503        assert_eq!(session.user_agent.as_deref(), Some("TestUA"));
504    }
505
506    #[tokio::test]
507    async fn test_create_session_zero_duration_rejected() {
508        let mgr = make_manager();
509        let result = mgr.create_session("u3", Duration::ZERO, None, None).await;
510        assert!(result.is_err());
511    }
512
513    #[tokio::test]
514    async fn test_create_session_excessive_duration_rejected() {
515        let mgr = make_manager();
516        let result = mgr
517            .create_session("u4", Duration::from_secs(400 * 24 * 3600), None, None)
518            .await;
519        assert!(result.is_err());
520    }
521
522    // ── get_session ─────────────────────────────────────────────────────
523
524    #[tokio::test]
525    async fn test_get_session_found() {
526        let mgr = make_manager();
527        let sid = mgr
528            .create_session("u5", Duration::from_secs(600), None, None)
529            .await
530            .unwrap();
531        let session = mgr.get_session(&sid).await.unwrap();
532        assert!(session.is_some());
533        assert_eq!(session.unwrap().user_id, "u5");
534    }
535
536    #[tokio::test]
537    async fn test_get_session_not_found() {
538        let mgr = make_manager();
539        let result = mgr.get_session("nonexistent").await.unwrap();
540        assert!(result.is_none());
541    }
542
543    // ── delete_session ──────────────────────────────────────────────────
544
545    #[tokio::test]
546    async fn test_delete_session() {
547        let mgr = make_manager();
548        let sid = mgr
549            .create_session("u6", Duration::from_secs(600), None, None)
550            .await
551            .unwrap();
552        mgr.delete_session(&sid).await.unwrap();
553        assert!(mgr.get_session(&sid).await.unwrap().is_none());
554    }
555
556    // ── validate_session ────────────────────────────────────────────────
557
558    #[tokio::test]
559    async fn test_validate_session_valid() {
560        let mgr = make_manager();
561        let sid = mgr
562            .create_session("u7", Duration::from_secs(600), None, None)
563            .await
564            .unwrap();
565        let uid = mgr.validate_session(&sid).await.unwrap();
566        assert_eq!(uid.as_deref(), Some("u7"));
567    }
568
569    #[tokio::test]
570    async fn test_validate_session_nonexistent() {
571        let mgr = make_manager();
572        let uid = mgr.validate_session("ghost").await.unwrap();
573        assert!(uid.is_none());
574    }
575
576    // ── extend_session ──────────────────────────────────────────────────
577
578    #[tokio::test]
579    async fn test_extend_session() {
580        let mgr = make_manager();
581        let sid = mgr
582            .create_session("u8", Duration::from_secs(600), None, None)
583            .await
584            .unwrap();
585        let before = mgr.get_session(&sid).await.unwrap().unwrap().expires_at;
586        mgr.extend_session(&sid, Duration::from_secs(3600))
587            .await
588            .unwrap();
589        let after = mgr.get_session(&sid).await.unwrap().unwrap().expires_at;
590        assert!(after > before);
591    }
592
593    // ── get_user_sessions / delete_user_sessions ────────────────────────
594
595    #[tokio::test]
596    async fn test_get_user_sessions() {
597        let mgr = make_manager();
598        mgr.create_session("u9", Duration::from_secs(600), None, None)
599            .await
600            .unwrap();
601        mgr.create_session("u9", Duration::from_secs(600), None, None)
602            .await
603            .unwrap();
604        let sessions = mgr.get_user_sessions("u9").await.unwrap();
605        assert_eq!(sessions.len(), 2);
606    }
607
608    #[tokio::test]
609    async fn test_delete_user_sessions() {
610        let mgr = make_manager();
611        mgr.create_session("u10", Duration::from_secs(600), None, None)
612            .await
613            .unwrap();
614        mgr.create_session("u10", Duration::from_secs(600), None, None)
615            .await
616            .unwrap();
617        mgr.delete_user_sessions("u10").await.unwrap();
618        let sessions = mgr.get_user_sessions("u10").await.unwrap();
619        assert!(sessions.is_empty());
620    }
621
622    // ── count_active_sessions ───────────────────────────────────────────
623
624    #[tokio::test]
625    async fn test_count_active_sessions() {
626        let mgr = make_manager();
627        let before = mgr.count_active_sessions().await.unwrap();
628        mgr.create_session("u11", Duration::from_secs(600), None, None)
629            .await
630            .unwrap();
631        let after = mgr.count_active_sessions().await.unwrap();
632        assert!(after > before);
633    }
634
635    // ── create_session_limited ──────────────────────────────────────────
636
637    #[tokio::test]
638    async fn test_create_session_limited_success() {
639        let mgr = make_manager();
640        let (sid, count) = mgr
641            .create_session_limited("u12", Duration::from_secs(600), None, None)
642            .await
643            .unwrap();
644        assert!(sid.starts_with("sess"));
645        assert!(count >= 1);
646    }
647
648    // ── get_session_security_metrics ────────────────────────────────────
649
650    #[tokio::test]
651    async fn test_get_session_security_metrics() {
652        let mgr = make_manager();
653        mgr.create_session("u13", Duration::from_secs(600), None, None)
654            .await
655            .unwrap();
656        let metrics = mgr.get_session_security_metrics().await.unwrap();
657        assert!(metrics.contains_key("active_sessions"));
658        assert!(metrics.contains_key("last_check"));
659    }
660
661    // ── coordinate_distributed_sessions ─────────────────────────────────
662
663    #[tokio::test]
664    async fn test_coordinate_distributed_sessions() {
665        let mgr = make_manager();
666        let stats = mgr.coordinate_distributed_sessions().await.unwrap();
667        // With LocalOnlySessionStore, remote sessions should be 0
668        assert_eq!(stats.remote_active_sessions, 0);
669        assert_eq!(stats.coordination_conflicts, 0);
670    }
671
672    // ── synchronize_session ─────────────────────────────────────────────
673
674    #[tokio::test]
675    async fn test_synchronize_session_success() {
676        let mgr = make_manager();
677        let sid = mgr
678            .create_session("u14", Duration::from_secs(600), None, None)
679            .await
680            .unwrap();
681        assert!(mgr.synchronize_session(&sid).await.is_ok());
682    }
683
684    #[tokio::test]
685    async fn test_synchronize_session_not_found() {
686        let mgr = make_manager();
687        assert!(mgr.synchronize_session("ghost").await.is_err());
688    }
689
690    // ── update_session_activity ─────────────────────────────────────────
691
692    #[tokio::test]
693    async fn test_update_session_activity() {
694        let mgr = make_manager();
695        let sid = mgr
696            .create_session("u15", Duration::from_secs(600), None, None)
697            .await
698            .unwrap();
699        // Just ensure it doesn't error
700        mgr.update_session_activity(&sid).await.unwrap();
701    }
702
703    // ── cleanup_expired_sessions ────────────────────────────────────────
704
705    #[tokio::test]
706    async fn test_cleanup_expired_sessions() {
707        let mgr = make_manager();
708        // Just ensure it doesn't error on empty storage
709        mgr.cleanup_expired_sessions().await.unwrap();
710    }
711}