auth_framework/auth_modular/
session_manager.rs1use 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#[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
27pub struct SessionManager {
38 storage: Arc<dyn AuthStorage>,
39 distributed_store: Arc<dyn DistributedSessionStore>,
40}
41
42impl SessionManager {
43 pub fn new(storage: Arc<dyn AuthStorage>) -> Self {
51 Self {
52 storage,
53 distributed_store: Arc::new(LocalOnlySessionStore),
54 }
55 }
56
57 pub fn set_distributed_store(&mut self, store: Arc<dyn DistributedSessionStore>) {
64 self.distributed_store = store;
65 }
66
67 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 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 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 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 if let Some(ref session_data) = session
137 && session_data.is_expired()
138 {
139 let _ = self.delete_session(session_id).await;
141 return Ok(None);
142 }
143
144 Ok(session)
145 }
146
147 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 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 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 pub async fn delete_user_sessions(&self, user_id: &str) -> Result<()> {
207 debug!("Deleting all sessions for user '{}'", user_id);
208
209 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 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 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 let _ = self.update_session_activity(session_id).await;
248 return Ok(Some(session.user_id));
249 }
250 Ok(None)
251 }
252
253 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 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 pub async fn count_active_sessions(&self) -> Result<u64> {
338 debug!("Counting active sessions");
339
340 let active_count = self.storage.count_active_sessions().await?;
342
343 debug!("Found {} active sessions", active_count);
344 Ok(active_count)
345 }
346
347 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 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 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 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 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 async fn resolve_session_conflicts(&self) -> Result<()> {
443 tracing::debug!("Session conflict resolution completed (no-op for single-instance)");
444 Ok(())
445 }
446
447 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[tokio::test]
664 async fn test_coordinate_distributed_sessions() {
665 let mgr = make_manager();
666 let stats = mgr.coordinate_distributed_sessions().await.unwrap();
667 assert_eq!(stats.remote_active_sessions, 0);
669 assert_eq!(stats.coordination_conflicts, 0);
670 }
671
672 #[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 #[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 mgr.update_session_activity(&sid).await.unwrap();
701 }
702
703 #[tokio::test]
706 async fn test_cleanup_expired_sessions() {
707 let mgr = make_manager();
708 mgr.cleanup_expired_sessions().await.unwrap();
710 }
711}