1use super::secure_utils::{SecureComparison, SecureRandomGen};
3use crate::errors::{AuthError, Result};
4use crate::session::manager::SessionState;
5use dashmap::DashMap;
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use std::sync::Arc;
9use std::time::{Duration, SystemTime};
10use zeroize::ZeroizeOnDrop;
11
12#[derive(Clone, Serialize, Deserialize)]
14pub struct SecureSession {
15 pub id: String,
17
18 pub user_id: String,
20
21 pub created_at: SystemTime,
23
24 pub last_accessed: SystemTime,
26
27 pub expires_at: SystemTime,
29
30 pub state: SessionState,
32
33 pub device_fingerprint: DeviceFingerprint,
35
36 pub creation_ip: String,
38
39 pub current_ip: String,
41
42 pub user_agent: String,
44
45 pub mfa_verified: bool,
47
48 pub security_flags: SecurityFlags,
50
51 pub metadata: HashMap<String, String>,
53
54 pub concurrent_sessions: u32,
56
57 pub risk_score: u8,
59
60 pub rotation_count: u32,
62}
63
64impl std::fmt::Debug for SecureSession {
65 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 let mut d = f.debug_struct("SecureSession");
67 d.field("id", &crate::utils::redact::redacted(&self.id));
68 d.field("user_id", &self.user_id);
69 d.field("created_at", &self.created_at);
70 d.field("last_accessed", &self.last_accessed);
71 d.field("expires_at", &self.expires_at);
72 d.field("state", &self.state);
73 d.field("device_fingerprint", &self.device_fingerprint);
74 d.field("creation_ip", &self.creation_ip);
75 d.field("current_ip", &self.current_ip);
76 d.field("user_agent", &self.user_agent);
77 d.field("mfa_verified", &self.mfa_verified);
78 d.field("security_flags", &self.security_flags);
79 d.field("metadata", &self.metadata);
80 d.field("concurrent_sessions", &self.concurrent_sessions);
81 d.field("risk_score", &self.risk_score);
82 d.field("rotation_count", &self.rotation_count);
83 d.finish()
84 }
85}
86
87#[derive(Debug, Clone, Serialize, Deserialize, ZeroizeOnDrop)]
89pub struct DeviceFingerprint {
90 pub browser_hash: String,
92
93 pub screen_resolution: Option<String>,
95
96 pub timezone_offset: Option<i32>,
98
99 pub platform: Option<String>,
101
102 pub languages: Vec<String>,
104
105 pub canvas_hash: Option<String>,
107
108 pub webgl_hash: Option<String>,
110}
111
112#[derive(Debug, Clone, Serialize, Deserialize, Default)]
114pub struct SecurityFlags {
115 pub secure_transport: bool,
117
118 pub suspicious_location: bool,
120
121 pub multiple_failures: bool,
123
124 pub new_device: bool,
126
127 pub unusual_hours: bool,
129
130 pub high_privilege_ops: bool,
132
133 pub cross_device_access: bool,
135}
136
137#[derive(Debug, Clone)]
139pub struct SecureSessionConfig {
140 pub max_lifetime: Duration,
142
143 pub idle_timeout: Duration,
145
146 pub max_concurrent_sessions: u32,
148
149 pub rotation_interval: Duration,
151
152 pub require_secure_transport: bool,
154
155 pub enable_device_fingerprinting: bool,
157
158 pub max_risk_score: u8,
160
161 pub validate_ip_address: bool,
163
164 pub max_ip_changes: u32,
166
167 pub enable_geolocation: bool,
169}
170
171impl Default for SecureSessionConfig {
172 fn default() -> Self {
187 Self {
188 max_lifetime: Duration::from_secs(8 * 3600), idle_timeout: Duration::from_secs(30 * 60), max_concurrent_sessions: 3,
191 rotation_interval: Duration::from_secs(3600), require_secure_transport: true,
193 enable_device_fingerprinting: true,
194 max_risk_score: 70,
195 validate_ip_address: true,
196 max_ip_changes: 3,
197 enable_geolocation: false, }
199 }
200}
201
202impl SecureSessionConfig {
203 pub fn for_high_security() -> Self {
212 Self {
213 max_lifetime: Duration::from_secs(2 * 3600), idle_timeout: Duration::from_secs(10 * 60), max_concurrent_sessions: 1,
216 rotation_interval: Duration::from_secs(15 * 60), require_secure_transport: true,
218 enable_device_fingerprinting: true,
219 max_risk_score: 40,
220 validate_ip_address: true,
221 max_ip_changes: 1,
222 enable_geolocation: true,
223 }
224 }
225
226 pub fn for_mobile() -> Self {
236 Self {
237 max_lifetime: Duration::from_secs(30 * 24 * 3600), idle_timeout: Duration::from_secs(7 * 24 * 3600), max_concurrent_sessions: 5,
240 rotation_interval: Duration::from_secs(24 * 3600), require_secure_transport: true,
242 enable_device_fingerprinting: true,
243 max_risk_score: 80,
244 validate_ip_address: false,
245 max_ip_changes: 50,
246 enable_geolocation: false,
247 }
248 }
249}
250
251pub struct SecureSessionManager {
253 config: SecureSessionConfig,
254 active_sessions: Arc<DashMap<String, SecureSession>>,
255 user_sessions: Arc<DashMap<String, Vec<String>>>, ip_changes: Arc<DashMap<String, u32>>, }
258
259impl SecureSessionManager {
260 pub fn new(config: SecureSessionConfig) -> Self {
262 Self {
263 config,
264 active_sessions: Arc::new(DashMap::new()),
265 user_sessions: Arc::new(DashMap::new()),
266 ip_changes: Arc::new(DashMap::new()),
267 }
268 }
269
270 pub fn create_session(
272 &self,
273 user_id: &str,
274 ip_address: &str,
275 user_agent: &str,
276 device_fingerprint: Option<DeviceFingerprint>,
277 secure_transport: bool,
278 ) -> Result<SecureSession> {
279 if self.config.require_secure_transport && !secure_transport {
281 return Err(AuthError::validation(
282 "Session must be created over secure transport (HTTPS)".to_string(),
283 ));
284 }
285
286 self.enforce_concurrent_session_limit(user_id)?;
288
289 let session_id = SecureRandomGen::generate_session_id()?;
291
292 let now = SystemTime::now();
293 let expires_at = now + self.config.max_lifetime;
294
295 let risk_score = self.calculate_risk_score(
297 ip_address,
298 user_agent,
299 &device_fingerprint,
300 secure_transport,
301 );
302
303 let concurrent_sessions = self.get_user_session_count(user_id);
305
306 let session = SecureSession {
307 id: session_id.clone(),
308 user_id: user_id.to_string(),
309 created_at: now,
310 last_accessed: now,
311 expires_at,
312 state: if risk_score > self.config.max_risk_score {
313 SessionState::HighRisk
314 } else {
315 SessionState::Active
316 },
317 device_fingerprint: device_fingerprint.unwrap_or_else(|| DeviceFingerprint {
318 browser_hash: "unknown".to_string(),
319 screen_resolution: None,
320 timezone_offset: None,
321 platform: None,
322 languages: vec![],
323 canvas_hash: None,
324 webgl_hash: None,
325 }),
326 creation_ip: ip_address.to_string(),
327 current_ip: ip_address.to_string(),
328 user_agent: user_agent.to_string(),
329 mfa_verified: false,
330 security_flags: SecurityFlags {
331 secure_transport,
332 ..SecurityFlags::default()
333 },
334 metadata: HashMap::new(),
335 concurrent_sessions,
336 risk_score,
337 rotation_count: 0,
338 };
339
340 self.store_session(session.clone())?;
342
343 tracing::info!(
344 "Created secure session {} for user {} (risk score: {})",
345 crate::utils::redact::fingerprint(&session_id),
346 user_id,
347 risk_score
348 );
349
350 Ok(session)
351 }
352
353 pub fn get_session(&self, session_id: &str) -> Result<Option<SecureSession>> {
355 if let Some(session_ref) = self.active_sessions.get(session_id) {
356 let session = session_ref.value().clone();
357
358 if session.expires_at < SystemTime::now() {
360 drop(session_ref);
361 self.revoke_session(session_id)?;
362 return Ok(None);
363 }
364
365 match session.state {
367 SessionState::Active => Ok(Some(session)),
368 SessionState::RequiresMfa => Ok(Some(session)),
369 SessionState::RequiresRotation => Ok(Some(session)),
370 _ => Ok(None), }
372 } else {
373 Ok(None)
374 }
375 }
376
377 pub fn update_session_activity(
383 &self,
384 session_id: &str,
385 ip_address: &str,
386 user_agent: &str,
387 ) -> Result<()> {
388 if let Some(mut session_entry) = self.active_sessions.get_mut(session_id) {
389 let session = session_entry.value_mut();
390 let now = SystemTime::now();
391
392 match session.state {
394 SessionState::Active | SessionState::RequiresRotation => {}
395 SessionState::RequiresMfa => {
396 return Err(AuthError::validation(
397 "Session requires MFA verification before activity is allowed".to_string(),
398 ));
399 }
400 _ => {
401 return Err(AuthError::validation(
402 "Session is no longer active".to_string(),
403 ));
404 }
405 }
406
407 if now
409 .duration_since(session.last_accessed)
410 .unwrap_or_default()
411 > self.config.idle_timeout
412 {
413 session.state = SessionState::Expired;
414 return Err(AuthError::validation(
415 "Session expired due to inactivity".to_string(),
416 ));
417 }
418
419 if self.config.validate_ip_address && session.current_ip != ip_address {
421 self.handle_ip_change(session, ip_address)?;
422 }
423
424 if !SecureComparison::constant_time_eq(&session.user_agent, user_agent) {
426 session.security_flags.cross_device_access = true;
427 tracing::warn!(
428 "User agent change detected for session {}: {} -> {}",
429 crate::utils::redact::fingerprint(session_id),
430 session.user_agent,
431 user_agent
432 );
433 }
434
435 session.last_accessed = now;
437 session.current_ip = ip_address.to_string();
438
439 if now.duration_since(session.created_at).unwrap_or_default()
441 > self.config.rotation_interval
442 {
443 session.state = SessionState::RequiresRotation;
444 }
445
446 let new_risk_score = self.calculate_risk_score_update(session);
448 session.risk_score = new_risk_score;
449
450 if new_risk_score > self.config.max_risk_score {
451 session.state = SessionState::HighRisk;
452 tracing::warn!(
453 "Session {} marked as high risk (score: {})",
454 crate::utils::redact::fingerprint(session_id),
455 new_risk_score
456 );
457 }
458
459 Ok(())
460 } else {
461 Err(AuthError::validation("Session not found".to_string()))
462 }
463 }
464
465 pub fn rotate_session(&self, session_id: &str) -> Result<String> {
467 if let Some((_, mut session)) = self.active_sessions.remove(session_id) {
468 let new_session_id = SecureRandomGen::generate_session_id()?;
470
471 session.id = new_session_id.clone();
473 session.rotation_count += 1;
474 session.state = SessionState::Active;
475 session.last_accessed = SystemTime::now();
476
477 self.active_sessions
479 .insert(new_session_id.clone(), session.clone());
480
481 if let Some(mut user_session_list) = self.user_sessions.get_mut(&session.user_id)
483 && let Some(pos) = user_session_list.iter().position(|id| id == session_id)
484 {
485 user_session_list[pos] = new_session_id.clone();
486 }
487
488 tracing::info!(
489 "Session rotated: {} -> {} (rotation count: {})",
490 crate::utils::redact::fingerprint(session_id),
491 crate::utils::redact::fingerprint(&new_session_id),
492 session.rotation_count
493 );
494
495 Ok(new_session_id)
496 } else {
497 Err(AuthError::validation(
498 "Session not found for rotation".to_string(),
499 ))
500 }
501 }
502
503 pub fn revoke_session(&self, session_id: &str) -> Result<()> {
505 if let Some((_, session)) = self.active_sessions.remove(session_id) {
506 if let Some(mut user_session_list) = self.user_sessions.get_mut(&session.user_id) {
508 user_session_list.retain(|id| id != session_id);
509 if user_session_list.is_empty() {
510 drop(user_session_list);
511 self.user_sessions.remove(&session.user_id);
512 }
513 }
514
515 self.ip_changes.remove(session_id);
517
518 tracing::info!(
519 "Session {} revoked for user {}",
520 crate::utils::redact::fingerprint(session_id),
521 session.user_id
522 );
523
524 Ok(())
525 } else {
526 Err(AuthError::validation(
527 "Session not found for revocation".to_string(),
528 ))
529 }
530 }
531
532 pub fn revoke_user_sessions(&self, user_id: &str) -> Result<u32> {
534 if let Some((_, session_ids)) = self.user_sessions.remove(user_id) {
535 let count = session_ids.len() as u32;
536
537 for session_id in &session_ids {
538 self.active_sessions.remove(session_id);
539 }
540
541 for session_id in &session_ids {
543 self.ip_changes.remove(session_id);
544 }
545
546 tracing::info!("Revoked {} sessions for user {}", count, user_id);
547
548 Ok(count)
549 } else {
550 Ok(0)
551 }
552 }
553
554 pub fn cleanup_expired_sessions(&self) -> Result<u32> {
556 let now = SystemTime::now();
557 let mut expired_sessions = Vec::new();
558
559 for session_ref in self.active_sessions.iter() {
561 if session_ref.value().expires_at < now {
562 expired_sessions.push(session_ref.key().clone());
563 }
564 }
565
566 let count = expired_sessions.len() as u32;
568 for session_id in expired_sessions {
569 let _ = self.revoke_session(&session_id);
570 }
571
572 if count > 0 {
573 tracing::info!("Cleaned up {} expired sessions", count);
574 }
575
576 Ok(count)
577 }
578
579 fn store_session(&self, session: SecureSession) -> Result<()> {
581 self.active_sessions
582 .insert(session.id.clone(), session.clone());
583
584 self.user_sessions
585 .entry(session.user_id.clone())
586 .or_default()
587 .push(session.id.clone());
588
589 Ok(())
590 }
591
592 fn enforce_concurrent_session_limit(&self, user_id: &str) -> Result<()> {
594 let current_count = self.get_user_session_count(user_id);
595
596 if current_count >= self.config.max_concurrent_sessions {
597 self.revoke_oldest_user_session(user_id)?;
599 }
600
601 Ok(())
602 }
603
604 fn get_user_session_count(&self, user_id: &str) -> u32 {
606 self.user_sessions
607 .get(user_id)
608 .map(|sessions| sessions.len() as u32)
609 .unwrap_or(0)
610 }
611
612 fn revoke_oldest_user_session(&self, user_id: &str) -> Result<()> {
614 let oldest_session_id = if let Some(session_ids_ref) = self.user_sessions.get(user_id) {
615 let session_ids = session_ids_ref.value();
616 session_ids
617 .iter()
618 .filter_map(|id| self.active_sessions.get(id))
619 .min_by_key(|session_ref| session_ref.value().created_at)
620 .map(|session_ref| session_ref.key().clone())
621 } else {
622 None
623 };
624
625 if let Some(session_id) = oldest_session_id {
626 self.revoke_session(&session_id)?;
627 tracing::info!(
628 "Revoked oldest session {} for user {} due to concurrent limit",
629 crate::utils::redact::fingerprint(&session_id),
630 user_id
631 );
632 }
633
634 Ok(())
635 }
636
637 fn handle_ip_change(&self, session: &mut SecureSession, new_ip: &str) -> Result<()> {
639 let mut change_count = self.ip_changes.entry(session.id.clone()).or_insert(0);
640 *change_count += 1;
641
642 if *change_count > self.config.max_ip_changes {
643 session.state = SessionState::HighRisk;
644 session.security_flags.suspicious_location = true;
645 return Err(AuthError::validation(
646 "Too many IP address changes - session marked as high risk".to_string(),
647 ));
648 }
649
650 session.security_flags.suspicious_location = true;
651 tracing::warn!(
652 "IP address change #{} for session {}: {} -> {}",
653 *change_count,
654 session.id,
655 session.current_ip,
656 new_ip
657 );
658
659 Ok(())
660 }
661
662 fn calculate_risk_score(
664 &self,
665 ip_address: &str,
666 user_agent: &str,
667 device_fingerprint: &Option<DeviceFingerprint>,
668 secure_transport: bool,
669 ) -> u8 {
670 let mut score = 0u8;
671
672 if !secure_transport {
674 score += 30;
675 }
676
677 if user_agent.is_empty() || user_agent.len() < 10 {
679 score += 20;
680 }
681
682 if device_fingerprint.is_none() {
684 score += 15;
685 }
686
687 if self.is_private_ip(ip_address) {
689 score += 10;
690 }
691
692 score.min(100)
693 }
694
695 fn calculate_risk_score_update(&self, session: &SecureSession) -> u8 {
697 let mut score: u8 = 0;
700
701 if session.security_flags.suspicious_location {
703 score = score.saturating_add(20);
704 }
705 if session.security_flags.multiple_failures {
706 score = score.saturating_add(25);
707 }
708 if session.security_flags.new_device {
709 let age_secs = session
712 .last_accessed
713 .duration_since(session.created_at)
714 .unwrap_or_default()
715 .as_secs();
716 let penalty = if age_secs > 1800 { 7 } else { 15 };
717 score = score.saturating_add(penalty);
718 }
719 if session.security_flags.unusual_hours {
720 score = score.saturating_add(10);
721 }
722 if session.security_flags.cross_device_access {
723 score = score.saturating_add(20);
724 }
725
726 if session.concurrent_sessions > 5 {
728 score = score.saturating_add(15);
729 }
730
731 if session.rotation_count > 3 {
733 score = score.saturating_add(10);
734 }
735
736 if session.rotation_count > 1 {
740 let age_secs = session
741 .last_accessed
742 .duration_since(session.created_at)
743 .unwrap_or_default()
744 .as_secs()
745 .max(1); let rotations_per_minute =
747 (session.rotation_count as u64).saturating_mul(60) / age_secs;
748 if rotations_per_minute > 5 {
749 score = score.saturating_add(20);
750 } else if rotations_per_minute > 2 {
751 score = score.saturating_add(10);
752 }
753 }
754
755 score.min(100)
756 }
757
758 fn is_private_ip(&self, ip: &str) -> bool {
760 if ip == "127.0.0.1" || ip == "::1" {
761 return true;
762 }
763 if ip.starts_with("192.168.") || ip.starts_with("10.") {
764 return true;
765 }
766 if let Some(rest) = ip.strip_prefix("172.")
768 && let Some(second_octet_str) = rest.split('.').next()
769 && let Ok(second_octet) = second_octet_str.parse::<u8>()
770 {
771 return (16..=31).contains(&second_octet);
772 }
773 false
774 }
775}
776
777#[cfg(test)]
778mod tests {
779 use super::*;
780
781 #[test]
782 fn test_secure_session_creation() {
783 let config = SecureSessionConfig::default();
784 let manager = SecureSessionManager::new(config);
785
786 let session = manager
787 .create_session(
788 "user123",
789 "192.168.1.100",
790 "Mozilla/5.0 Test Browser",
791 None,
792 true,
793 )
794 .unwrap();
795
796 assert_eq!(session.user_id, "user123");
797 assert_eq!(session.creation_ip, "192.168.1.100");
798 assert!(session.security_flags.secure_transport);
799 assert_eq!(session.state, SessionState::Active);
800 }
801
802 #[test]
803 fn test_session_rotation() {
804 let config = SecureSessionConfig::default();
805 let manager = SecureSessionManager::new(config);
806
807 let session = manager
808 .create_session(
809 "user123",
810 "192.168.1.100",
811 "Mozilla/5.0 Test Browser",
812 None,
813 true,
814 )
815 .unwrap();
816
817 let old_id = session.id.clone();
818 let new_id = manager.rotate_session(&old_id).unwrap();
819
820 assert_ne!(old_id, new_id);
821 assert!(manager.get_session(&old_id).unwrap().is_none());
822 assert!(manager.get_session(&new_id).unwrap().is_some());
823 }
824
825 #[test]
826 fn test_concurrent_session_limit() {
827 let config = SecureSessionConfig {
828 max_concurrent_sessions: 2,
829 ..Default::default()
830 };
831 let manager = SecureSessionManager::new(config);
832
833 let session1 = manager
835 .create_session(
836 "user123",
837 "192.168.1.100",
838 "Mozilla/5.0 Test Browser",
839 None,
840 true,
841 )
842 .unwrap();
843
844 let session2 = manager
846 .create_session(
847 "user123",
848 "192.168.1.101",
849 "Mozilla/5.0 Test Browser",
850 None,
851 true,
852 )
853 .unwrap();
854
855 let session3 = manager
857 .create_session(
858 "user123",
859 "192.168.1.102",
860 "Mozilla/5.0 Test Browser",
861 None,
862 true,
863 )
864 .unwrap();
865
866 assert!(manager.get_session(&session1.id).unwrap().is_none());
868 assert!(manager.get_session(&session2.id).unwrap().is_some());
869 assert!(manager.get_session(&session3.id).unwrap().is_some());
870 }
871
872 #[test]
873 fn test_risk_score_calculation() {
874 let config = SecureSessionConfig::default();
875 let manager = SecureSessionManager::new(config);
876
877 let risk_score = manager.calculate_risk_score("192.168.1.1", "", &None, false);
879
880 assert!(risk_score > 50, "Risk score should be high: {}", risk_score);
881 }
882
883 #[test]
884 fn test_session_cleanup() {
885 let config = SecureSessionConfig {
886 max_lifetime: Duration::from_millis(1), ..Default::default()
888 };
889 let manager = SecureSessionManager::new(config);
890
891 let session = manager
892 .create_session(
893 "user123",
894 "192.168.1.100",
895 "Mozilla/5.0 Test Browser",
896 None,
897 true,
898 )
899 .unwrap();
900
901 std::thread::sleep(Duration::from_millis(10));
903
904 let cleaned = manager.cleanup_expired_sessions().unwrap();
905 assert_eq!(cleaned, 1);
906 assert!(manager.get_session(&session.id).unwrap().is_none());
907 }
908
909 #[test]
910 fn test_for_high_security_preset() {
911 let config = SecureSessionConfig::for_high_security();
912 assert_eq!(config.max_lifetime, Duration::from_secs(2 * 3600));
913 assert_eq!(config.idle_timeout, Duration::from_secs(10 * 60));
914 assert_eq!(config.max_concurrent_sessions, 1);
915 assert_eq!(config.max_risk_score, 40);
916 assert!(config.enable_geolocation);
917 let manager = SecureSessionManager::new(config);
919 let session = manager
920 .create_session("u1", "10.0.0.1", "UA", None, true)
921 .unwrap();
922 assert_eq!(session.user_id, "u1");
923 }
924
925 #[test]
926 fn test_for_mobile_preset() {
927 let config = SecureSessionConfig::for_mobile();
928 assert_eq!(config.max_lifetime, Duration::from_secs(30 * 24 * 3600));
929 assert_eq!(config.max_concurrent_sessions, 5);
930 assert!(!config.validate_ip_address);
931 let manager = SecureSessionManager::new(config);
932 let session = manager
933 .create_session("u2", "10.0.0.2", "iOS", None, true)
934 .unwrap();
935 assert_eq!(session.user_id, "u2");
936 }
937}