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 && 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 let _ = self.update_session_activity(session_id).await;
258 return Ok(Some(session.user_id));
259 }
260 Ok(None)
261 }
262
263 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 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 pub async fn count_active_sessions(&self) -> Result<u64> {
348 debug!("Counting active sessions");
349
350 let active_count = self.storage.count_active_sessions().await?;
352
353 debug!("Found {} active sessions", active_count);
354 Ok(active_count)
355 }
356
357 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 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 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 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 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 async fn resolve_session_conflicts(&self) -> Result<()> {
453 tracing::debug!("Session conflict resolution completed (no-op for single-instance)");
454 Ok(())
455 }
456
457 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[tokio::test]
674 async fn test_coordinate_distributed_sessions() {
675 let mgr = make_manager();
676 let stats = mgr.coordinate_distributed_sessions().await.unwrap();
677 assert_eq!(stats.remote_active_sessions, 0);
679 assert_eq!(stats.coordination_conflicts, 0);
680 }
681
682 #[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 #[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 mgr.update_session_activity(&sid).await.unwrap();
711 }
712
713 #[tokio::test]
716 async fn test_cleanup_expired_sessions() {
717 let mgr = make_manager();
718 mgr.cleanup_expired_sessions().await.unwrap();
720 }
721}