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            && crate::account_state::ensure_account_active(&*self.storage, &session.user_id)
246                .await
247                .is_ok()
248            && crate::account_state::ensure_issued_after_revocation(
249                &*self.storage,
250                &session.user_id,
251                session.created_at.timestamp_millis(),
252            )
253            .await
254            .is_ok()
255        {
256            // Update last activity
257            let _ = self.update_session_activity(session_id).await;
258            return Ok(Some(session.user_id));
259        }
260        Ok(None)
261    }
262
263    /// Extend session expiration by `additional_time`.
264    ///
265    /// # Example
266    /// ```rust,ignore
267    /// mgr.extend_session("sess_abc", Duration::from_secs(1800)).await?;
268    /// ```
269    pub async fn extend_session(&self, session_id: &str, additional_time: Duration) -> Result<()> {
270        debug!(
271            "Extending session '{}' by {:?}",
272            crate::utils::redact::fingerprint(session_id),
273            additional_time
274        );
275
276        if let Some(mut session) = self.storage.get_session(session_id).await? {
277            session.expires_at += chrono::Duration::from_std(additional_time)
278                .map_err(|e| AuthError::internal(format!("Failed to convert duration: {}", e)))?;
279            self.storage.store_session(session_id, &session).await?;
280            info!(
281                "Session '{}' extended",
282                crate::utils::redact::fingerprint(session_id)
283            );
284        }
285
286        Ok(())
287    }
288
289    /// Create a new session with resource-limit guards.
290    ///
291    /// Enforces a global cap of 100 000 total sessions and a per-user cap
292    /// of 50 sessions to prevent DoS / resource exhaustion.
293    ///
294    /// Returns `(session_id, new_total_count)` so the caller can update monitoring.
295    ///
296    /// # Example
297    /// ```rust,ignore
298    /// let (sid, total) = mgr.create_session_limited(
299    ///     "user-1", Duration::from_secs(3600), None, None,
300    /// ).await?;
301    /// println!("created session {} (total active: {})", sid, total);
302    /// ```
303    pub async fn create_session_limited(
304        &self,
305        user_id: &str,
306        expires_in: Duration,
307        ip_address: Option<String>,
308        user_agent: Option<String>,
309    ) -> Result<(String, u64)> {
310        const MAX_TOTAL_SESSIONS: u64 = 100_000;
311        let total_sessions = self.count_active_sessions().await?;
312        if total_sessions >= MAX_TOTAL_SESSIONS {
313            warn!(
314                "Maximum total sessions ({}) exceeded, rejecting new session",
315                MAX_TOTAL_SESSIONS
316            );
317            return Err(AuthError::rate_limit(
318                "Maximum concurrent sessions exceeded. Please try again later.",
319            ));
320        }
321
322        const MAX_USER_SESSIONS: usize = 50;
323        let user_sessions = self.storage.list_user_sessions(user_id).await?;
324        if user_sessions.len() >= MAX_USER_SESSIONS {
325            warn!(
326                "User '{}' has reached maximum sessions ({})",
327                user_id, MAX_USER_SESSIONS
328            );
329            return Err(AuthError::TooManyConcurrentSessions);
330        }
331
332        let session_id = self
333            .create_session(user_id, expires_in, ip_address, user_agent)
334            .await?;
335        Ok((session_id, total_sessions + 1))
336    }
337
338    /// Count the number of currently active sessions.
339    ///
340    /// Used for security audit statistics.
341    ///
342    /// # Example
343    /// ```rust,ignore
344    /// let n = mgr.count_active_sessions().await?;
345    /// println!("{} active sessions", n);
346    /// ```
347    pub async fn count_active_sessions(&self) -> Result<u64> {
348        debug!("Counting active sessions");
349
350        // Use the storage layer's count_active_sessions method
351        let active_count = self.storage.count_active_sessions().await?;
352
353        debug!("Found {} active sessions", active_count);
354        Ok(active_count)
355    }
356
357    /// Get security metrics for sessions.
358    ///
359    /// # Example
360    /// ```rust,ignore
361    /// let metrics = mgr.get_session_security_metrics().await?;
362    /// println!("active: {:?}", metrics.get("active_sessions"));
363    /// ```
364    pub async fn get_session_security_metrics(&self) -> Result<HashMap<String, serde_json::Value>> {
365        debug!("Collecting session security metrics");
366
367        let mut metrics = HashMap::new();
368        let active_count = self.count_active_sessions().await?;
369
370        metrics.insert(
371            "active_sessions".to_string(),
372            serde_json::Value::Number(serde_json::Number::from(active_count)),
373        );
374        metrics.insert(
375            "last_check".to_string(),
376            serde_json::Value::String(chrono::Utc::now().to_rfc3339()),
377        );
378
379        Ok(metrics)
380    }
381
382    /// Coordinate session state across distributed instances.
383    ///
384    /// # Example
385    /// ```rust,ignore
386    /// let stats = mgr.coordinate_distributed_sessions().await?;
387    /// println!("synced: {}", stats.synchronized_sessions);
388    /// ```
389    pub async fn coordinate_distributed_sessions(&self) -> Result<SessionCoordinationStats> {
390        tracing::debug!("Coordinating distributed sessions across instances");
391
392        let local_sessions = self.count_active_sessions().await?;
393
394        let coordination_stats = SessionCoordinationStats {
395            local_active_sessions: local_sessions as u64,
396            remote_active_sessions: self.estimate_remote_sessions().await?,
397            synchronized_sessions: self.count_synchronized_sessions().await?,
398            coordination_conflicts: 0,
399            last_coordination_time: chrono::Utc::now(),
400        };
401
402        self.broadcast_session_state().await?;
403        self.resolve_session_conflicts().await?;
404
405        tracing::info!(
406            "Session coordination complete - Local: {}, Remote: {}, Synchronized: {}",
407            coordination_stats.local_active_sessions,
408            coordination_stats.remote_active_sessions,
409            coordination_stats.synchronized_sessions
410        );
411
412        Ok(coordination_stats)
413    }
414
415    /// Estimate active sessions on remote instances by querying the distributed store.
416    async fn estimate_remote_sessions(&self) -> Result<u64> {
417        let total = self.distributed_store.total_session_count().await?;
418        if total == 0 {
419            tracing::debug!("No distributed session store configured; remote session count = 0");
420            return Ok(0);
421        }
422        let local = self.count_active_sessions().await.unwrap_or(0);
423        let remote = total.saturating_sub(local);
424        tracing::debug!(
425            "Distributed session count: total={}, local={}, remote={}",
426            total,
427            local,
428            remote
429        );
430        Ok(remote)
431    }
432
433    /// Count sessions synchronized across instances.
434    async fn count_synchronized_sessions(&self) -> Result<u64> {
435        let metrics = self.get_session_security_metrics().await?;
436        let synchronized = metrics
437            .get("synchronized_sessions")
438            .and_then(|v| v.as_u64())
439            .unwrap_or(0);
440        tracing::debug!("Synchronized sessions count: {}", synchronized);
441        Ok(synchronized)
442    }
443
444    /// Broadcast local session state to other instances (no-op for single-node).
445    async fn broadcast_session_state(&self) -> Result<()> {
446        let count = self.count_active_sessions().await.unwrap_or(0);
447        tracing::debug!("Session state broadcast completed for {} sessions", count);
448        Ok(())
449    }
450
451    /// Resolve session conflicts between instances (no-op for single-node).
452    async fn resolve_session_conflicts(&self) -> Result<()> {
453        tracing::debug!("Session conflict resolution completed (no-op for single-instance)");
454        Ok(())
455    }
456
457    /// Synchronize a specific session with remote instances.
458    ///
459    /// # Example
460    /// ```rust,ignore
461    /// mgr.synchronize_session("sess_abc").await?;
462    /// ```
463    pub async fn synchronize_session(&self, session_id: &str) -> Result<()> {
464        if self.get_session(session_id).await?.is_none() {
465            return Err(AuthError::validation(format!(
466                "Session {} not found",
467                crate::utils::redact::fingerprint(session_id)
468            )));
469        }
470        tracing::info!(
471            "Session {} synchronized (single-instance)",
472            crate::utils::redact::fingerprint(session_id)
473        );
474        Ok(())
475    }
476}
477
478#[cfg(test)]
479mod tests {
480    use super::*;
481    use crate::storage::MemoryStorage;
482
483    fn make_manager() -> SessionManager {
484        SessionManager::new(Arc::new(MemoryStorage::new()))
485    }
486
487    // ── create_session ──────────────────────────────────────────────────
488
489    #[tokio::test]
490    async fn test_create_session_success() {
491        let mgr = make_manager();
492        let sid = mgr
493            .create_session("u1", Duration::from_secs(600), None, None)
494            .await
495            .unwrap();
496        assert!(sid.starts_with("sess"));
497    }
498
499    #[tokio::test]
500    async fn test_create_session_with_metadata() {
501        let mgr = make_manager();
502        let sid = mgr
503            .create_session(
504                "u2",
505                Duration::from_secs(600),
506                Some("127.0.0.1".into()),
507                Some("TestUA".into()),
508            )
509            .await
510            .unwrap();
511        let session = mgr.get_session(&sid).await.unwrap().unwrap();
512        assert_eq!(session.ip_address.as_deref(), Some("127.0.0.1"));
513        assert_eq!(session.user_agent.as_deref(), Some("TestUA"));
514    }
515
516    #[tokio::test]
517    async fn test_create_session_zero_duration_rejected() {
518        let mgr = make_manager();
519        let result = mgr.create_session("u3", Duration::ZERO, None, None).await;
520        assert!(result.is_err());
521    }
522
523    #[tokio::test]
524    async fn test_create_session_excessive_duration_rejected() {
525        let mgr = make_manager();
526        let result = mgr
527            .create_session("u4", Duration::from_secs(400 * 24 * 3600), None, None)
528            .await;
529        assert!(result.is_err());
530    }
531
532    // ── get_session ─────────────────────────────────────────────────────
533
534    #[tokio::test]
535    async fn test_get_session_found() {
536        let mgr = make_manager();
537        let sid = mgr
538            .create_session("u5", Duration::from_secs(600), None, None)
539            .await
540            .unwrap();
541        let session = mgr.get_session(&sid).await.unwrap();
542        assert!(session.is_some());
543        assert_eq!(session.unwrap().user_id, "u5");
544    }
545
546    #[tokio::test]
547    async fn test_get_session_not_found() {
548        let mgr = make_manager();
549        let result = mgr.get_session("nonexistent").await.unwrap();
550        assert!(result.is_none());
551    }
552
553    // ── delete_session ──────────────────────────────────────────────────
554
555    #[tokio::test]
556    async fn test_delete_session() {
557        let mgr = make_manager();
558        let sid = mgr
559            .create_session("u6", Duration::from_secs(600), None, None)
560            .await
561            .unwrap();
562        mgr.delete_session(&sid).await.unwrap();
563        assert!(mgr.get_session(&sid).await.unwrap().is_none());
564    }
565
566    // ── validate_session ────────────────────────────────────────────────
567
568    #[tokio::test]
569    async fn test_validate_session_valid() {
570        let mgr = make_manager();
571        let sid = mgr
572            .create_session("u7", Duration::from_secs(600), None, None)
573            .await
574            .unwrap();
575        let uid = mgr.validate_session(&sid).await.unwrap();
576        assert_eq!(uid.as_deref(), Some("u7"));
577    }
578
579    #[tokio::test]
580    async fn test_validate_session_nonexistent() {
581        let mgr = make_manager();
582        let uid = mgr.validate_session("ghost").await.unwrap();
583        assert!(uid.is_none());
584    }
585
586    // ── extend_session ──────────────────────────────────────────────────
587
588    #[tokio::test]
589    async fn test_extend_session() {
590        let mgr = make_manager();
591        let sid = mgr
592            .create_session("u8", Duration::from_secs(600), None, None)
593            .await
594            .unwrap();
595        let before = mgr.get_session(&sid).await.unwrap().unwrap().expires_at;
596        mgr.extend_session(&sid, Duration::from_secs(3600))
597            .await
598            .unwrap();
599        let after = mgr.get_session(&sid).await.unwrap().unwrap().expires_at;
600        assert!(after > before);
601    }
602
603    // ── get_user_sessions / delete_user_sessions ────────────────────────
604
605    #[tokio::test]
606    async fn test_get_user_sessions() {
607        let mgr = make_manager();
608        mgr.create_session("u9", Duration::from_secs(600), None, None)
609            .await
610            .unwrap();
611        mgr.create_session("u9", Duration::from_secs(600), None, None)
612            .await
613            .unwrap();
614        let sessions = mgr.get_user_sessions("u9").await.unwrap();
615        assert_eq!(sessions.len(), 2);
616    }
617
618    #[tokio::test]
619    async fn test_delete_user_sessions() {
620        let mgr = make_manager();
621        mgr.create_session("u10", Duration::from_secs(600), None, None)
622            .await
623            .unwrap();
624        mgr.create_session("u10", Duration::from_secs(600), None, None)
625            .await
626            .unwrap();
627        mgr.delete_user_sessions("u10").await.unwrap();
628        let sessions = mgr.get_user_sessions("u10").await.unwrap();
629        assert!(sessions.is_empty());
630    }
631
632    // ── count_active_sessions ───────────────────────────────────────────
633
634    #[tokio::test]
635    async fn test_count_active_sessions() {
636        let mgr = make_manager();
637        let before = mgr.count_active_sessions().await.unwrap();
638        mgr.create_session("u11", Duration::from_secs(600), None, None)
639            .await
640            .unwrap();
641        let after = mgr.count_active_sessions().await.unwrap();
642        assert!(after > before);
643    }
644
645    // ── create_session_limited ──────────────────────────────────────────
646
647    #[tokio::test]
648    async fn test_create_session_limited_success() {
649        let mgr = make_manager();
650        let (sid, count) = mgr
651            .create_session_limited("u12", Duration::from_secs(600), None, None)
652            .await
653            .unwrap();
654        assert!(sid.starts_with("sess"));
655        assert!(count >= 1);
656    }
657
658    // ── get_session_security_metrics ────────────────────────────────────
659
660    #[tokio::test]
661    async fn test_get_session_security_metrics() {
662        let mgr = make_manager();
663        mgr.create_session("u13", Duration::from_secs(600), None, None)
664            .await
665            .unwrap();
666        let metrics = mgr.get_session_security_metrics().await.unwrap();
667        assert!(metrics.contains_key("active_sessions"));
668        assert!(metrics.contains_key("last_check"));
669    }
670
671    // ── coordinate_distributed_sessions ─────────────────────────────────
672
673    #[tokio::test]
674    async fn test_coordinate_distributed_sessions() {
675        let mgr = make_manager();
676        let stats = mgr.coordinate_distributed_sessions().await.unwrap();
677        // With LocalOnlySessionStore, remote sessions should be 0
678        assert_eq!(stats.remote_active_sessions, 0);
679        assert_eq!(stats.coordination_conflicts, 0);
680    }
681
682    // ── synchronize_session ─────────────────────────────────────────────
683
684    #[tokio::test]
685    async fn test_synchronize_session_success() {
686        let mgr = make_manager();
687        let sid = mgr
688            .create_session("u14", Duration::from_secs(600), None, None)
689            .await
690            .unwrap();
691        assert!(mgr.synchronize_session(&sid).await.is_ok());
692    }
693
694    #[tokio::test]
695    async fn test_synchronize_session_not_found() {
696        let mgr = make_manager();
697        assert!(mgr.synchronize_session("ghost").await.is_err());
698    }
699
700    // ── update_session_activity ─────────────────────────────────────────
701
702    #[tokio::test]
703    async fn test_update_session_activity() {
704        let mgr = make_manager();
705        let sid = mgr
706            .create_session("u15", Duration::from_secs(600), None, None)
707            .await
708            .unwrap();
709        // Just ensure it doesn't error
710        mgr.update_session_activity(&sid).await.unwrap();
711    }
712
713    // ── cleanup_expired_sessions ────────────────────────────────────────
714
715    #[tokio::test]
716    async fn test_cleanup_expired_sessions() {
717        let mgr = make_manager();
718        // Just ensure it doesn't error on empty storage
719        mgr.cleanup_expired_sessions().await.unwrap();
720    }
721}