1use crate::audit::{AuditLogger, AuditStorage, GeolocationInfo, RequestMetadata};
8use crate::errors::{AuthError, Result};
9use crate::threat_intelligence::{ThreatFeedManager, ThreatIntelConfig};
10use async_trait::async_trait;
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13use std::time::{Duration, SystemTime};
14
15#[derive(Clone, Serialize, Deserialize)]
19pub struct Session {
20 pub id: String,
22 pub user_id: String,
24 pub created_at: SystemTime,
26 pub last_accessed: SystemTime,
28 pub expires_at: SystemTime,
30 pub state: SessionState,
32 pub device_info: DeviceInfo,
34 pub security_metadata: SecurityMetadata,
36 pub data: HashMap<String, String>,
38 pub mfa_verified: bool,
40 pub cached_permissions: Option<Vec<String>>,
42 pub last_activity: ActivityInfo,
44}
45
46impl std::fmt::Debug for Session {
47 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 let mut d = f.debug_struct("Session");
49 d.field("id", &crate::utils::redact::redacted(&self.id));
50 d.field("user_id", &self.user_id);
51 d.field("created_at", &self.created_at);
52 d.field("last_accessed", &self.last_accessed);
53 d.field("expires_at", &self.expires_at);
54 d.field("state", &self.state);
55 d.field("device_info", &self.device_info);
56 d.field("security_metadata", &self.security_metadata);
57 d.field("data", &crate::utils::redact::redacted(&self.data));
58 d.field("mfa_verified", &self.mfa_verified);
59 d.field("cached_permissions", &self.cached_permissions);
60 d.field("last_activity", &self.last_activity);
61 d.finish()
62 }
63}
64
65impl Session {
66 pub fn new(user_id: impl Into<String>, lifetime: Duration) -> Self {
82 let now = SystemTime::now();
83 Self {
84 id: uuid::Uuid::new_v4().to_string(),
85 user_id: user_id.into(),
86 created_at: now,
87 last_accessed: now,
88 expires_at: now + lifetime,
89 state: SessionState::Active,
90 device_info: DeviceInfo::unknown(),
91 security_metadata: SecurityMetadata::default(),
92 data: HashMap::new(),
93 mfa_verified: false,
94 cached_permissions: None,
95 last_activity: ActivityInfo {
96 endpoint: None,
97 action: None,
98 request_metadata: None,
99 timestamp: now,
100 },
101 }
102 }
103}
104
105#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
107pub enum SessionState {
108 Active,
109 Expired,
110 Revoked,
111 Suspended,
112 RequiresMfa,
113 RequiresReauth,
114 RequiresRotation,
116 HighRisk,
118}
119
120#[derive(Debug, Clone, Serialize, Deserialize)]
122pub struct DeviceInfo {
123 pub fingerprint: String,
125 pub device_type: String,
127 pub operating_system: Option<String>,
129 pub browser: Option<String>,
131 pub screen_resolution: Option<String>,
133 pub timezone: Option<String>,
135 pub language: Option<String>,
137 pub is_trusted: bool,
139 pub device_name: Option<String>,
141 pub is_mobile: bool,
143 pub ip_address: Option<String>,
145}
146
147impl DeviceInfo {
148 pub fn unknown() -> Self {
150 Self {
151 fingerprint: String::new(),
152 device_type: "unknown".into(),
153 operating_system: None,
154 browser: None,
155 screen_resolution: None,
156 timezone: None,
157 language: None,
158 is_trusted: false,
159 device_name: None,
160 is_mobile: false,
161 ip_address: None,
162 }
163 }
164}
165
166#[derive(Debug, Clone, Serialize, Deserialize, Default)]
168pub struct SecurityMetadata {
169 pub creation_ip: String,
171 pub current_ip: String,
173 pub creation_location: Option<GeolocationInfo>,
175 pub current_location: Option<GeolocationInfo>,
177 pub security_flags: Vec<SecurityFlag>,
179 pub risk_score: u8,
181 pub location_changed: bool,
183 pub ip_changed: bool,
185 pub failed_auth_attempts: u32,
187}
188
189#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
191pub enum SecurityFlag {
192 SuspiciousActivity,
193 LocationAnomaly,
194 DeviceAnomaly,
195 TimeAnomaly,
196 ConcurrentSessionLimit,
197 BruteForceAttempt,
198 RequiresVerification,
199 ElevatedPrivileges,
200}
201
202#[derive(Debug, Clone, Serialize, Deserialize)]
204pub struct ActivityInfo {
205 pub endpoint: Option<String>,
207 pub action: Option<String>,
209 pub request_metadata: Option<RequestMetadata>,
211 pub timestamp: SystemTime,
213}
214
215#[derive(Debug, Clone)]
217pub struct SessionConfig {
218 pub default_duration: Duration,
220 pub max_duration: Duration,
222 pub idle_timeout: Duration,
224 pub rotate_on_privilege_escalation: bool,
228 pub rotate_periodically: bool,
230 pub rotation_interval: Duration,
232 pub max_concurrent_sessions: Option<u32>,
234 pub track_device_fingerprints: bool,
236 pub enforce_geographic_restrictions: bool,
238 pub allowed_countries: Vec<String>,
240 pub security_policy: SessionSecurityPolicy,
242}
243
244impl SessionConfig {
246 pub fn builder() -> SessionConfigBuilder {
248 SessionConfigBuilder::default()
249 }
250}
251
252#[derive(Default)]
254pub struct SessionConfigBuilder {
255 config: SessionConfig,
256}
257
258impl SessionConfigBuilder {
259 pub fn default_duration(mut self, duration: std::time::Duration) -> Self {
269 self.config.default_duration = duration;
270 self
271 }
272
273 pub fn max_duration(mut self, duration: std::time::Duration) -> Self {
282 self.config.max_duration = duration;
283 self
284 }
285
286 pub fn idle_timeout(mut self, timeout: std::time::Duration) -> Self {
295 self.config.idle_timeout = timeout;
296 self
297 }
298
299 #[deprecated(
302 since = "0.6.0",
303 note = "has no effect: sessions are not rotated on privilege escalation; use rotate_periodically"
304 )]
305 pub fn rotate_on_privilege_escalation(mut self, rotate: bool) -> Self {
306 self.config.rotate_on_privilege_escalation = rotate;
307 self
308 }
309
310 pub fn rotate_periodically(mut self, rotate: bool) -> Self {
320 self.config.rotate_periodically = rotate;
321 self
322 }
323
324 pub fn rotation_interval(mut self, interval: std::time::Duration) -> Self {
334 self.config.rotation_interval = interval;
335 self
336 }
337
338 pub fn max_concurrent_sessions(mut self, max: u32) -> Self {
347 self.config.max_concurrent_sessions = Some(max);
348 self
349 }
350
351 pub fn allowed_countries(mut self, countries: Vec<String>) -> Self {
356 self.config.allowed_countries = countries;
357 self
358 }
359
360 pub fn for_web_app() -> Self {
369 Self {
370 config: SessionConfig {
371 default_duration: Duration::from_secs(3600), max_duration: Duration::from_secs(86400), idle_timeout: Duration::from_secs(1800), rotate_on_privilege_escalation: true,
375 rotate_periodically: true,
376 rotation_interval: Duration::from_secs(1800), max_concurrent_sessions: Some(5),
378 track_device_fingerprints: true,
379 enforce_geographic_restrictions: false,
380 allowed_countries: vec![],
381 security_policy: SessionSecurityPolicy::default(),
382 },
383 }
384 }
385
386 pub fn for_api_service() -> Self {
397 Self {
398 config: SessionConfig {
399 default_duration: Duration::from_secs(900), max_duration: Duration::from_secs(3600), idle_timeout: Duration::from_secs(600), rotate_on_privilege_escalation: true,
403 rotate_periodically: false,
404 rotation_interval: Duration::from_secs(3600),
405 max_concurrent_sessions: None, track_device_fingerprints: false,
407 enforce_geographic_restrictions: false,
408 allowed_countries: vec![],
409 security_policy: SessionSecurityPolicy {
410 require_mfa_for_new_devices: false,
411 require_reauth_for_sensitive_ops: false,
412 reauth_timeout: Duration::from_secs(300),
413 max_risk_score: 90,
414 auto_suspend_suspicious: false,
415 verify_location_changes: false,
416 limit_concurrent_sessions: false,
417 },
418 },
419 }
420 }
421
422 pub fn for_high_security() -> Self {
432 Self {
433 config: SessionConfig {
434 default_duration: Duration::from_secs(1800), max_duration: Duration::from_secs(7200), idle_timeout: Duration::from_secs(300), rotate_on_privilege_escalation: true,
438 rotate_periodically: true,
439 rotation_interval: Duration::from_secs(900), max_concurrent_sessions: Some(1),
441 track_device_fingerprints: true,
442 enforce_geographic_restrictions: true,
443 allowed_countries: vec![], security_policy: SessionSecurityPolicy {
445 require_mfa_for_new_devices: true,
446 require_reauth_for_sensitive_ops: true,
447 reauth_timeout: Duration::from_secs(120), max_risk_score: 40,
449 auto_suspend_suspicious: true,
450 verify_location_changes: true,
451 limit_concurrent_sessions: true,
452 },
453 },
454 }
455 }
456
457 pub fn build(self) -> SessionConfig {
467 self.config
468 }
469}
470
471#[derive(Debug, Clone)]
472pub struct SessionSecurityPolicy {
473 pub require_mfa_for_new_devices: bool,
475 pub require_reauth_for_sensitive_ops: bool,
477 pub reauth_timeout: Duration,
479 pub max_risk_score: u8,
481 pub auto_suspend_suspicious: bool,
483 pub verify_location_changes: bool,
485 pub limit_concurrent_sessions: bool,
487}
488
489#[async_trait]
491pub trait SessionStorage: Send + Sync {
492 async fn create_session(&self, session: &Session) -> Result<()>;
494
495 async fn get_session(&self, session_id: &str) -> Result<Option<Session>>;
497
498 async fn update_session(&self, session: &Session) -> Result<()>;
500
501 async fn delete_session(&self, session_id: &str) -> Result<()>;
503
504 async fn get_user_sessions(&self, user_id: &str) -> Result<Vec<Session>>;
506
507 async fn count_active_sessions(&self, user_id: &str) -> Result<u32>;
509
510 async fn cleanup_expired_sessions(&self) -> Result<u32>;
512
513 async fn find_sessions_by_device(&self, device_fingerprint: &str) -> Result<Vec<Session>>;
515
516 async fn find_sessions_by_ip(&self, ip_address: &str) -> Result<Vec<Session>>;
518}
519
520pub struct SessionManager<S: SessionStorage, A: AuditStorage> {
522 storage: S,
523 config: SessionConfig,
524 audit_logger: AuditLogger<A>,
525 fingerprint_generator: DeviceFingerprintGenerator,
526 risk_calculator: RiskCalculator,
527 threat_intel_manager: Option<ThreatFeedManager>,
528}
529
530impl<S: SessionStorage, A: AuditStorage> SessionManager<S, A> {
531 pub fn new(storage: S, config: SessionConfig, audit_logger: AuditLogger<A>) -> Self {
536 let threat_intel_manager = if std::env::var("THREAT_INTEL_ENABLED")
538 .unwrap_or_else(|_| "false".to_string())
539 .to_lowercase()
540 == "true"
541 {
542 match ThreatIntelConfig::from_env_and_config() {
543 Ok(intel_config) => {
544 tracing::info!(
545 "🟢 Automated threat intelligence enabled - feeds will update automatically"
546 );
547 match ThreatFeedManager::new(intel_config) {
548 Ok(manager) => {
549 if let Err(e) = manager.start_automated_updates() {
551 tracing::error!(
552 "Failed to start automated threat feed updates: {}",
553 e
554 );
555 None
556 } else {
557 tracing::info!(
558 "✅ Threat intelligence automation started successfully"
559 );
560 Some(manager)
561 }
562 }
563 Err(e) => {
564 tracing::error!(
565 "Failed to initialize threat intelligence manager: {}",
566 e
567 );
568 None
569 }
570 }
571 }
572 Err(e) => {
573 tracing::error!("Failed to load threat intelligence configuration: {}", e);
574 None
575 }
576 }
577 } else {
578 tracing::info!(
579 "🔴 Automated threat intelligence disabled (THREAT_INTEL_ENABLED=false)"
580 );
581 None
582 };
583
584 Self {
585 storage,
586 config,
587 audit_logger,
588 fingerprint_generator: DeviceFingerprintGenerator::new(),
589 risk_calculator: RiskCalculator::new(),
590 threat_intel_manager,
591 }
592 }
593
594 pub async fn create_session(
596 &self,
597 user_id: &str,
598 mut device_info: DeviceInfo,
599 metadata: RequestMetadata,
600 ) -> Result<Session> {
601 if device_info.fingerprint.is_empty() {
603 device_info.fingerprint = self.fingerprint_generator.generate_fingerprint(&metadata);
604 }
605
606 if let Some(max_sessions) = self.config.max_concurrent_sessions {
608 let active_count = self.storage.count_active_sessions(user_id).await?;
609 if active_count >= max_sessions {
610 return Err(AuthError::TooManyConcurrentSessions);
611 }
612 }
613
614 let now = SystemTime::now();
615 let session_id = self.generate_session_id();
616
617 let risk_score = self.risk_calculator.calculate_risk(
619 &device_info,
620 &metadata,
621 &self.get_user_session_history(user_id).await?,
622 self.threat_intel_manager.as_ref(),
623 );
624
625 let mut security_flags = Vec::new();
626 if risk_score > 70 {
627 security_flags.push(SecurityFlag::SuspiciousActivity);
628 }
629
630 let existing_sessions = self
632 .storage
633 .find_sessions_by_device(&device_info.fingerprint)
634 .await?;
635 let is_new_device = existing_sessions.is_empty();
636
637 if is_new_device && self.config.security_policy.require_mfa_for_new_devices {
638 security_flags.push(SecurityFlag::RequiresVerification);
639 }
640
641 let session = Session {
642 id: session_id.clone(),
643 user_id: user_id.to_string(),
644 created_at: now,
645 last_accessed: now,
646 expires_at: now + self.config.default_duration,
647 state: if security_flags.contains(&SecurityFlag::RequiresVerification) {
648 SessionState::RequiresMfa
649 } else {
650 SessionState::Active
651 },
652 device_info: device_info.clone(),
653 security_metadata: SecurityMetadata {
654 creation_ip: metadata.ip_address.clone().unwrap_or_default(),
655 current_ip: metadata.ip_address.clone().unwrap_or_default(),
656 creation_location: metadata.geolocation.clone(),
657 current_location: metadata.geolocation.clone(),
658 security_flags,
659 risk_score,
660 location_changed: false,
661 ip_changed: false,
662 failed_auth_attempts: 0,
663 },
664 data: HashMap::new(),
665 mfa_verified: false,
666 cached_permissions: None,
667 last_activity: ActivityInfo {
668 endpoint: metadata.endpoint.clone(),
669 action: Some("session_created".to_string()),
670 request_metadata: Some(metadata.clone()),
671 timestamp: now,
672 },
673 };
674
675 self.storage.create_session(&session).await?;
676
677 self.audit_logger
679 .log_event({
680 let mut ev = crate::audit::AuditEvent::builder(
681 crate::audit::AuditEventType::LoginSuccess,
682 "Session created",
683 )
684 .user_id(user_id)
685 .outcome(crate::audit::EventOutcome::Success)
686 .risk_level(if risk_score > 70 {
687 crate::audit::RiskLevel::High
688 } else {
689 crate::audit::RiskLevel::Low
690 })
691 .request_metadata(metadata)
692 .with_actor("user", user_id)
693 .build();
694 ev.session_id = Some(session_id);
695 ev.timestamp = now;
696 ev
697 })
698 .await?;
699
700 Ok(session)
701 }
702
703 pub async fn validate_session(
705 &self,
706 session_id: &str,
707 metadata: RequestMetadata,
708 ) -> Result<Option<Session>> {
709 let mut session = match self.storage.get_session(session_id).await? {
710 Some(session) => session,
711 None => return Ok(None),
712 };
713
714 let now = SystemTime::now();
715
716 if let Ok(age) = now.duration_since(session.created_at)
718 && age > self.config.max_duration
719 {
720 session.state = SessionState::Expired;
721 self.storage.update_session(&session).await?;
722 return Ok(None);
723 }
724
725 if session.expires_at <= now {
727 session.state = SessionState::Expired;
728 self.storage.update_session(&session).await?;
729 return Ok(None);
730 }
731
732 let current_fingerprint = self.fingerprint_generator.generate_fingerprint(&metadata);
734 if current_fingerprint != session.device_info.fingerprint {
735 session.state = SessionState::RequiresMfa;
737 self.storage.update_session(&session).await?;
738
739 self.audit_logger
741 .log_suspicious_activity(
742 Some(&session.user_id),
743 "device_fingerprint_mismatch",
744 &format!(
745 "Session ID: {}, Expected: {}, Got: {}",
746 crate::utils::redact::fingerprint(session_id),
747 session.device_info.fingerprint,
748 current_fingerprint
749 ),
750 metadata.clone(),
751 )
752 .await?;
753 }
754
755 let idle_duration = now
757 .duration_since(session.last_accessed)
758 .unwrap_or_default();
759 if idle_duration > self.config.idle_timeout {
760 session.state = SessionState::Expired;
761 self.storage.update_session(&session).await?;
762 return Ok(None);
763 }
764
765 match session.state {
767 SessionState::Expired | SessionState::Revoked | SessionState::Suspended => {
768 return Ok(None);
769 }
770 SessionState::RequiresMfa | SessionState::RequiresReauth => {
771 return Ok(Some(session));
773 }
774 SessionState::Active | SessionState::RequiresRotation | SessionState::HighRisk => {}
775 }
776
777 let current_ip = metadata.ip_address.clone().unwrap_or_default();
779 let ip_changed = current_ip != session.security_metadata.current_ip;
780
781 if ip_changed {
782 session.security_metadata.ip_changed = true;
783 session.security_metadata.current_ip = current_ip;
784
785 if self.config.security_policy.verify_location_changes {
787 session
788 .security_metadata
789 .security_flags
790 .push(SecurityFlag::LocationAnomaly);
791 session.state = SessionState::RequiresReauth;
792 }
793 }
794
795 session.last_accessed = now;
797 session.last_activity = ActivityInfo {
798 endpoint: metadata.endpoint.clone(),
799 action: Some("session_validated".to_string()),
800 request_metadata: Some(metadata),
801 timestamp: now,
802 };
803
804 let should_rotate = self.should_rotate_session(&session);
806 if should_rotate {
807 let new_session_id = self.generate_session_id();
808 let old_session_id = session.id.clone();
809 session.id = new_session_id;
810
811 self.storage.delete_session(&old_session_id).await?;
813 self.storage.create_session(&session).await?;
814 } else {
815 self.storage.update_session(&session).await?;
816 }
817
818 Ok(Some(session))
819 }
820
821 pub async fn revoke_session(&self, session_id: &str) -> Result<()> {
823 if let Some(mut session) = self.storage.get_session(session_id).await? {
824 session.state = SessionState::Revoked;
825 self.storage.update_session(&session).await?;
826
827 self.audit_logger
829 .log_event(
830 crate::audit::AuditEvent::builder(
831 crate::audit::AuditEventType::Logout,
832 "Session revoked",
833 )
834 .user_id(session.user_id)
835 .session_id(session_id)
836 .outcome(crate::audit::EventOutcome::Success)
837 .with_actor("system", "session_manager")
838 .build(),
839 )
840 .await?;
841 }
842 Ok(())
843 }
844
845 pub async fn revoke_all_user_sessions(&self, user_id: &str) -> Result<u32> {
849 let sessions = self.storage.get_user_sessions(user_id).await?;
850 let mut revoked_count = 0;
851
852 for mut session in sessions {
853 if !matches!(session.state, SessionState::Expired | SessionState::Revoked) {
854 session.state = SessionState::Revoked;
855 self.storage.update_session(&session).await?;
856 revoked_count += 1;
857 }
858 }
859
860 Ok(revoked_count)
861 }
862
863 pub async fn get_user_sessions(
872 &self,
873 user_id: &str,
874 include_inactive: bool,
875 ) -> Result<Vec<Session>> {
876 let mut sessions = self.storage.get_user_sessions(user_id).await?;
877
878 if !include_inactive {
879 sessions.retain(|s| s.state == SessionState::Active);
880 }
881
882 Ok(sessions)
883 }
884
885 pub async fn list_user_sessions(
893 &self,
894 user_id: &str,
895 filter: crate::auth_operations::SessionFilter,
896 ) -> Result<Vec<Session>> {
897 self.get_user_sessions(user_id, filter.include_inactive())
898 .await
899 }
900
901 pub async fn cleanup_expired_sessions(&self) -> Result<u32> {
903 self.storage.cleanup_expired_sessions().await
904 }
905
906 pub fn generate_device_fingerprint(&self, metadata: &RequestMetadata) -> String {
908 self.fingerprint_generator.generate_fingerprint(metadata)
909 }
910
911 pub fn validate_device_fingerprint(
913 &self,
914 session: &Session,
915 metadata: &RequestMetadata,
916 ) -> bool {
917 let current_fingerprint = self.fingerprint_generator.generate_fingerprint(metadata);
918 current_fingerprint == session.device_info.fingerprint
919 }
920
921 pub async fn suspend_session(&self, session_id: &str, reason: &str) -> Result<()> {
923 if let Some(mut session) = self.storage.get_session(session_id).await? {
924 session.state = SessionState::Suspended;
925 session
926 .security_metadata
927 .security_flags
928 .push(SecurityFlag::SuspiciousActivity);
929
930 self.storage.update_session(&session).await?;
931
932 let mut details = HashMap::new();
934 details.insert("suspension_reason".to_string(), reason.to_string());
935
936 self.audit_logger
937 .log_event(
938 crate::audit::AuditEvent::builder(
939 crate::audit::AuditEventType::AccountLocked,
940 format!("Session suspended: {}", reason),
941 )
942 .user_id(session.user_id)
943 .session_id(session_id)
944 .outcome(crate::audit::EventOutcome::Success)
945 .risk_level(crate::audit::RiskLevel::High)
946 .details(details)
947 .with_actor("system", "security_monitor")
948 .build(),
949 )
950 .await?;
951 }
952 Ok(())
953 }
954
955 pub async fn update_session_data(
957 &self,
958 session_id: &str,
959 key: &str,
960 value: &str,
961 ) -> Result<()> {
962 if let Some(mut session) = self.storage.get_session(session_id).await? {
963 session.data.insert(key.to_string(), value.to_string());
964 session.last_accessed = SystemTime::now();
965 self.storage.update_session(&session).await?;
966 }
967 Ok(())
968 }
969
970 fn generate_session_id(&self) -> String {
972 format!("sess_{}", uuid::Uuid::new_v4())
973 }
974
975 fn should_rotate_session(&self, session: &Session) -> bool {
977 if !self.config.rotate_periodically {
978 return false;
979 }
980
981 let session_age = SystemTime::now()
982 .duration_since(session.created_at)
983 .unwrap_or_default();
984
985 session_age > self.config.rotation_interval
986 }
987
988 async fn get_user_session_history(&self, user_id: &str) -> Result<Vec<Session>> {
990 self.storage.get_user_sessions(user_id).await
993 }
994}
995
996pub struct DeviceFingerprintGenerator;
1001
1002impl Default for DeviceFingerprintGenerator {
1003 fn default() -> Self {
1004 Self::new()
1005 }
1006}
1007
1008impl DeviceFingerprintGenerator {
1009 pub fn new() -> Self {
1010 Self
1011 }
1012
1013 pub fn generate_fingerprint(&self, metadata: &RequestMetadata) -> String {
1015 let mut fingerprint_data = Vec::new();
1016
1017 if let Some(ua) = &metadata.user_agent {
1018 fingerprint_data.push(ua.clone());
1019 }
1020
1021 self.add_advanced_fingerprinting_data(&mut fingerprint_data, metadata);
1023
1024 let fingerprint_string = fingerprint_data.join("|");
1025 format!("fp_{:x}", crc32fast::hash(fingerprint_string.as_bytes()))
1026 }
1027
1028 fn add_advanced_fingerprinting_data(
1030 &self,
1031 fingerprint_data: &mut Vec<String>,
1032 metadata: &RequestMetadata,
1033 ) {
1034 if let Some(ref ip) = metadata.ip_address {
1036 fingerprint_data.push(format!("geo:{}", self.get_ip_geolocation(ip)));
1038 }
1039
1040 fingerprint_data.push(format!("lang:{}", self.get_system_language()));
1042 fingerprint_data.push(format!("tz:{}", self.get_timezone_offset()));
1043 fingerprint_data.push(format!("hw:{}", self.get_hardware_concurrency()));
1044
1045 fingerprint_data.push(format!("conn:{}", self.get_connection_info()));
1047
1048 fingerprint_data.push(format!("caps:{}", self.get_client_capabilities()));
1050 }
1051
1052 fn get_ip_geolocation(&self, ip: &str) -> String {
1054 use std::net::IpAddr;
1055 use std::str::FromStr;
1056
1057 if let Ok(ip_addr) = IpAddr::from_str(ip) {
1059 match ip_addr {
1060 IpAddr::V4(ipv4) => {
1061 let octets = ipv4.octets();
1062
1063 if (octets[0] == 10)
1065 || (octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31)
1066 || (octets[0] == 192 && octets[1] == 168)
1067 {
1068 return "private_rfc1918".to_string();
1069 }
1070
1071 if octets[0] == 127 {
1073 return "loopback".to_string();
1074 }
1075
1076 if octets[0] == 169 && octets[1] == 254 {
1078 return "link_local".to_string();
1079 }
1080
1081 if octets[0] >= 224 && octets[0] <= 239 {
1083 return "multicast".to_string();
1084 }
1085
1086 match (octets[0], octets[1], octets[2], octets[3]) {
1088 (8, 8, 8, 8) | (8, 8, 4, 4) => "google_dns".to_string(),
1089 (1, 1, 1, 1) | (1, 0, 0, 1) => "cloudflare_dns".to_string(),
1090 (208, 67, 222, 222) | (208, 67, 220, 220) => "opendns".to_string(),
1091 _ => {
1092 self.lookup_maxmind_geolocation(&ipv4).unwrap_or_else(|| {
1094 match octets[0] {
1096 1..=23 => "apnic_region".to_string(), 24..=49 => "arin_region".to_string(), 50..=99 => "ripe_region".to_string(), 100..=127 => "mixed_region".to_string(), 128..=191 => "arin_region".to_string(), 192..=223 => "ripe_apnic_region".to_string(), _ => format!("public_class_{}", octets[0] / 64),
1103 }
1104 })
1105 }
1106 }
1107 }
1108 IpAddr::V6(ipv6) => {
1109 let segments = ipv6.segments();
1110
1111 if ipv6.is_loopback() {
1113 return "ipv6_loopback".to_string();
1114 }
1115
1116 if segments[0] & 0xffc0 == 0xfe80 {
1118 return "ipv6_link_local".to_string();
1119 }
1120
1121 if segments[0] & 0xfe00 == 0xfc00 {
1123 return "ipv6_unique_local".to_string();
1124 }
1125
1126 if segments[0] & 0xff00 == 0xff00 {
1128 return "ipv6_multicast".to_string();
1129 }
1130
1131 format!("ipv6_global_{:x}", segments[0] / 0x1000)
1133 }
1134 }
1135 } else {
1136 "invalid_ip".to_string()
1137 }
1138 }
1139
1140 fn get_system_language(&self) -> String {
1142 "en-US".to_string()
1144 }
1145
1146 fn get_timezone_offset(&self) -> String {
1148 "-05:00".to_string() }
1151
1152 fn get_hardware_concurrency(&self) -> String {
1154 "4".to_string()
1156 }
1157
1158 fn get_connection_info(&self) -> String {
1160 "wifi".to_string()
1162 }
1163
1164 fn get_client_capabilities(&self) -> String {
1166 "webgl2_canvas_audio".to_string()
1168 }
1169
1170 fn lookup_maxmind_geolocation(&self, ip: &std::net::Ipv4Addr) -> Option<String> {
1172 let db_path =
1174 std::env::var("MAXMIND_DB_PATH").unwrap_or_else(|_| "GeoLite2-City.mmdb".to_string());
1175 self.lookup_maxmind_geolocation_at(&db_path, ip)
1176 }
1177
1178 fn lookup_maxmind_geolocation_at(
1180 &self,
1181 db_path: &str,
1182 ip: &std::net::Ipv4Addr,
1183 ) -> Option<String> {
1184 use std::path::Path;
1185
1186 if !Path::new(&db_path).exists() {
1187 tracing::warn!(
1188 "MaxMind database not found at {}, falling back to basic geolocation",
1189 db_path
1190 );
1191 return None;
1192 }
1193
1194 match maxminddb::Reader::open_readfile(db_path) {
1195 Ok(reader) => {
1196 match reader.lookup((*ip).into()) {
1197 Ok(result) => match result.decode::<maxminddb::geoip2::City>() {
1198 Ok(Some(city)) => {
1199 let mut location_parts = Vec::new();
1200
1201 let location = &city.location;
1203 if let (Some(lat), Some(lon)) = (location.latitude, location.longitude)
1204 {
1205 location_parts.push(format!("coords:{:.4},{:.4}", lat, lon));
1206 }
1207
1208 if location_parts.is_empty() {
1211 None
1212 } else {
1213 Some(location_parts.join("|"))
1214 }
1215 }
1216 Ok(None) => {
1217 tracing::debug!("MaxMind lookup returned no data for {}", ip);
1218 None
1219 }
1220 Err(e) => {
1221 tracing::debug!("MaxMind decode failed for {}: {}", ip, e);
1222 None
1223 }
1224 },
1225 Err(e) => {
1226 tracing::debug!("MaxMind lookup failed for {}: {}", ip, e);
1227 None
1228 }
1229 }
1230 }
1231 Err(e) => {
1232 tracing::warn!("Failed to open MaxMind database: {}", e);
1233 None
1234 }
1235 }
1236 }
1237}
1238
1239pub struct RiskCalculator;
1245
1246impl Default for RiskCalculator {
1247 fn default() -> Self {
1248 Self::new()
1249 }
1250}
1251
1252impl RiskCalculator {
1253 pub fn new() -> Self {
1254 Self
1255 }
1256
1257 pub fn calculate_risk(
1259 &self,
1260 device_info: &DeviceInfo,
1261 metadata: &RequestMetadata,
1262 _session_history: &[Session],
1263 threat_intel_manager: Option<&ThreatFeedManager>,
1264 ) -> u8 {
1265 let mut risk_score = 0u8;
1266
1267 if !device_info.is_trusted {
1269 risk_score += 20;
1270 }
1271
1272 if let Some(ip) = &metadata.ip_address
1274 && self.is_suspicious_ip(ip, threat_intel_manager)
1275 {
1276 risk_score += 30;
1277 }
1278
1279 if let Some(location) = &metadata.geolocation {
1281 let mut geo_risk = 0;
1282
1283 if let Some(country) = &location.country {
1285 let country_lower = country.to_lowercase();
1286
1287 let high_risk_countries =
1289 ["tor", "anonymous", "vpn", "proxy", "hosting", "datacenter"];
1290
1291 for indicator in &high_risk_countries {
1292 if country_lower.contains(indicator) {
1293 geo_risk += 30;
1294 break;
1295 }
1296 }
1297
1298 geo_risk += self.assess_country_threat_level(&country_lower) as u8;
1300
1301 let elevated_risk_patterns = ["cloud", "aws", "azure", "gcp"];
1303 for pattern in &elevated_risk_patterns {
1304 if country_lower.contains(pattern) {
1305 geo_risk += 20;
1306 break;
1307 }
1308 }
1309 }
1310
1311 if let (Some(lat), Some(lon)) = (location.latitude, location.longitude) {
1313 if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
1315 geo_risk += 25; }
1317
1318 if (lat * 100.0).fract().abs() < 0.01 && (lon * 100.0).fract().abs() < 0.01 {
1320 geo_risk += 15; }
1322 }
1323
1324 if let Some(region) = &location.region {
1326 let region_lower = region.to_lowercase();
1327 if region_lower.contains("hosting") || region_lower.contains("datacenter") {
1328 geo_risk += 20;
1329 }
1330 }
1331
1332 if let Some(city) = &location.city {
1334 let city_lower = city.to_lowercase();
1335 if city_lower.contains("server") || city_lower.contains("datacenter") {
1336 geo_risk += 15;
1337 }
1338 }
1339
1340 risk_score += geo_risk;
1341 }
1342
1343 risk_score.min(100)
1349 }
1350
1351 fn is_suspicious_ip(&self, ip: &str, threat_intel_manager: Option<&ThreatFeedManager>) -> bool {
1353 use std::net::IpAddr;
1354 use std::str::FromStr;
1355
1356 if let Ok(ip_addr) = IpAddr::from_str(ip) {
1358 match ip_addr {
1359 IpAddr::V4(ipv4) => {
1360 let octets = ipv4.octets();
1361
1362 if self.check_malicious_ip_feeds(&ipv4, threat_intel_manager) {
1364 return true;
1365 }
1366
1367 let suspicious_ranges = [
1369 (5, 0, 0, 0, 8), (31, 0, 0, 0, 8), (37, 0, 0, 0, 8), (46, 0, 0, 0, 8), (95, 0, 0, 0, 8), (185, 0, 0, 0, 8), ];
1377
1378 for (net, _, _, _, _) in &suspicious_ranges {
1379 if octets[0] == *net {
1380 return true;
1381 }
1382 }
1383
1384 if octets[0] == 0 || (octets[0] == 100 && octets[1] >= 64 && octets[1] <= 127) || (octets[0] == 169 && octets[1] == 254) || (octets[0] >= 224 && octets[0] <= 239) || (octets[0] >= 240)
1390 {
1391 return true;
1393 }
1394
1395 if octets[3] == 0 || octets[3] == 255 {
1397 return true;
1398 }
1399
1400 if self.check_proxy_vpn_databases(&ipv4) {
1402 return true;
1403 }
1404
1405 let proxy_ports_in_ip = [
1407 80, 443, 8080, 3128, 1080, 8000, 8888, 9050, ];
1409
1410 for &port in &proxy_ports_in_ip {
1411 if octets[2] == (port / 256) as u8 && octets[3] == (port % 256) as u8 {
1412 return true;
1413 }
1414 }
1415
1416 false
1417 }
1418 IpAddr::V6(ipv6) => {
1419 let segments = ipv6.segments();
1420
1421 if self.check_tor_exit_nodes(&ipv6) {
1423 return true;
1424 }
1425
1426 if segments[0] == 0x2001 && segments[1] == 0x67c {
1428 return true;
1430 }
1431
1432 let mut sequential_count = 0;
1434 for i in 1..segments.len() {
1435 if segments[i] == segments[i - 1] + 1 {
1436 sequential_count += 1;
1437 }
1438 }
1439 if sequential_count >= 4 {
1440 return true;
1442 }
1443
1444 if segments[0] == 0x2001 && segments[1] == 0x470 {
1446 return true;
1448 }
1449
1450 false
1451 }
1452 }
1453 } else {
1454 true }
1456 }
1457
1458 fn assess_country_threat_level(&self, country: &str) -> u32 {
1460 use std::path::Path;
1461
1462 let threat_db_path = std::env::var("COUNTRY_THREAT_DB_PATH")
1464 .unwrap_or_else(|_| "country-threats.csv".to_string());
1465
1466 if Path::new(&threat_db_path).exists() {
1467 if let Ok(contents) = std::fs::read_to_string(&threat_db_path) {
1469 let mut csv_reader = csv::Reader::from_reader(contents.as_bytes());
1470
1471 for result in csv_reader.records() {
1472 if let Ok(record) = result
1473 && record.len() >= 2
1474 {
1475 let threat_country = record[0].to_lowercase();
1476 if let Ok(risk_score) = record[1].parse::<u32>()
1477 && country.contains(&threat_country)
1478 {
1479 tracing::debug!(
1480 "Country threat match: {} -> risk {}",
1481 country,
1482 risk_score
1483 );
1484 return risk_score;
1485 }
1486 }
1487 }
1488 }
1489 }
1490
1491 0 }
1494
1495 fn check_malicious_ip_feeds(
1497 &self,
1498 ip: &std::net::Ipv4Addr,
1499 threat_intel_manager: Option<&ThreatFeedManager>,
1500 ) -> bool {
1501 if let Some(threat_manager) = threat_intel_manager {
1503 return threat_manager.is_malicious_ip(&std::net::IpAddr::V4(*ip));
1504 }
1505
1506 use std::path::Path;
1508
1509 let feed_paths = [
1511 std::env::var("MALICIOUS_IPS_DB_PATH")
1512 .unwrap_or_else(|_| "malicious-ips.txt".to_string()),
1513 std::env::var("BOTNET_IPS_DB_PATH").unwrap_or_else(|_| "botnet-ips.txt".to_string()),
1514 std::env::var("TOR_EXIT_NODES_DB_PATH").unwrap_or_else(|_| "tor-exits.txt".to_string()),
1515 ];
1516
1517 for feed_path in &feed_paths {
1518 if Path::new(feed_path).exists()
1519 && let Ok(contents) = std::fs::read_to_string(feed_path)
1520 {
1521 for line in contents.lines() {
1522 let line = line.trim();
1523 if line.is_empty() || line.starts_with('#') {
1524 continue;
1525 }
1526
1527 if line == ip.to_string() {
1529 tracing::warn!("Malicious IP detected: {} (source: {})", ip, feed_path);
1530 return true;
1531 }
1532
1533 if line.contains('/')
1535 && let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1536 && network.contains(*ip)
1537 {
1538 tracing::warn!(
1539 "Malicious network detected: {} in {} (source: {})",
1540 ip,
1541 network,
1542 feed_path
1543 );
1544 return true;
1545 }
1546 }
1547 }
1548 }
1549
1550 false
1551 }
1552
1553 fn check_proxy_vpn_databases(&self, ip: &std::net::Ipv4Addr) -> bool {
1555 use std::path::Path;
1556
1557 let db_sources = [
1559 ("VPN_DATABASE_PATH", "vpn-ranges.txt"),
1560 ("PROXY_DATABASE_PATH", "proxy-ips.txt"),
1561 ("DATACENTER_DATABASE_PATH", "datacenter-ranges.txt"),
1562 ("HOSTING_DATABASE_PATH", "hosting-providers.txt"),
1563 ];
1564
1565 for (env_var, default_file) in &db_sources {
1566 let db_path = std::env::var(env_var).unwrap_or_else(|_| default_file.to_string());
1567
1568 if Path::new(&db_path).exists()
1569 && let Ok(contents) = std::fs::read_to_string(&db_path)
1570 {
1571 for line in contents.lines() {
1572 let line = line.trim();
1573 if line.is_empty() || line.starts_with('#') {
1574 continue;
1575 }
1576
1577 if line.contains('/') {
1579 if let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1581 && network.contains(*ip)
1582 {
1583 tracing::info!(
1584 "Proxy/VPN detected: {} in {} (source: {})",
1585 ip,
1586 network,
1587 db_path
1588 );
1589 return true;
1590 }
1591 } else if line.contains('-') {
1592 let parts: Vec<&str> = line.split('-').collect();
1594 if parts.len() == 2
1595 && let (Ok(start_ip), Ok(end_ip)) = (
1596 parts[0].trim().parse::<std::net::Ipv4Addr>(),
1597 parts[1].trim().parse::<std::net::Ipv4Addr>(),
1598 )
1599 {
1600 let ip_u32 = u32::from(*ip);
1601 let start_u32 = u32::from(start_ip);
1602 let end_u32 = u32::from(end_ip);
1603
1604 if ip_u32 >= start_u32 && ip_u32 <= end_u32 {
1605 tracing::info!(
1606 "Proxy/VPN range detected: {} in {}-{} (source: {})",
1607 ip,
1608 start_ip,
1609 end_ip,
1610 db_path
1611 );
1612 return true;
1613 }
1614 }
1615 } else if line == ip.to_string() {
1616 tracing::info!("Proxy/VPN exact match: {} (source: {})", ip, db_path);
1618 return true;
1619 }
1620 }
1621 }
1622 }
1623
1624 false
1625 }
1626
1627 fn check_tor_exit_nodes(&self, ip: &std::net::Ipv6Addr) -> bool {
1629 use std::path::Path;
1630
1631 let tor_db_path = std::env::var("TOR_EXIT_NODES_IPV6_PATH")
1633 .unwrap_or_else(|_| "tor-exits-ipv6.txt".to_string());
1634
1635 if Path::new(&tor_db_path).exists()
1636 && let Ok(contents) = std::fs::read_to_string(&tor_db_path)
1637 {
1638 for line in contents.lines() {
1639 let line = line.trim();
1640 if line.is_empty() || line.starts_with('#') {
1641 continue;
1642 }
1643
1644 if let Ok(tor_ip) = line.parse::<std::net::Ipv6Addr>()
1646 && tor_ip == *ip
1647 {
1648 tracing::warn!("Tor exit node detected: {}", ip);
1649 return true;
1650 }
1651
1652 if line.contains('/')
1654 && let Ok(network) = line.parse::<ipnetwork::Ipv6Network>()
1655 && network.contains(*ip)
1656 {
1657 tracing::warn!("Tor exit network detected: {} in {}", ip, network);
1658 return true;
1659 }
1660 }
1661 }
1662
1663 if let Some(ipv4) = ip.to_ipv4() {
1665 let tor_v4_path = std::env::var("TOR_EXIT_NODES_IPV4_PATH")
1666 .unwrap_or_else(|_| "tor-exits-ipv4.txt".to_string());
1667
1668 if Path::new(&tor_v4_path).exists()
1669 && let Ok(contents) = std::fs::read_to_string(&tor_v4_path)
1670 {
1671 for line in contents.lines() {
1672 let line = line.trim();
1673 if line == ipv4.to_string() {
1674 tracing::warn!("Tor exit node detected (IPv4-mapped): {}", ip);
1675 return true;
1676 }
1677 }
1678 }
1679 }
1680
1681 false
1682 }
1683}
1684
1685impl Default for SessionConfig {
1686 fn default() -> Self {
1687 Self {
1688 default_duration: Duration::from_secs(3600), max_duration: Duration::from_secs(86400), idle_timeout: Duration::from_secs(1800), rotate_on_privilege_escalation: true,
1692 rotate_periodically: true,
1693 rotation_interval: Duration::from_secs(1800), max_concurrent_sessions: Some(5),
1695 track_device_fingerprints: true,
1696 enforce_geographic_restrictions: false,
1697 allowed_countries: vec![],
1698 security_policy: SessionSecurityPolicy::default(),
1699 }
1700 }
1701}
1702
1703impl Default for SessionSecurityPolicy {
1704 fn default() -> Self {
1705 Self {
1706 require_mfa_for_new_devices: true,
1707 require_reauth_for_sensitive_ops: true,
1708 reauth_timeout: Duration::from_secs(300), max_risk_score: 70,
1710 auto_suspend_suspicious: true,
1711 verify_location_changes: true,
1712 limit_concurrent_sessions: true,
1713 }
1714 }
1715}
1716
1717#[cfg(test)]
1718mod tests {
1719 use super::*;
1720
1721 #[test]
1722 fn test_device_fingerprint_generation() {
1723 let generator = DeviceFingerprintGenerator::new();
1724 let metadata = RequestMetadata {
1725 user_agent: Some("Mozilla/5.0".to_string()),
1726 ..Default::default()
1727 };
1728
1729 let fp1 = generator.generate_fingerprint(&metadata);
1730 let fp2 = generator.generate_fingerprint(&metadata);
1731
1732 assert_eq!(fp1, fp2);
1733 assert!(fp1.starts_with("fp_"));
1734 }
1735
1736 #[test]
1737 fn test_risk_calculation() {
1738 let calculator = RiskCalculator::new();
1739 let device_info = DeviceInfo {
1740 fingerprint: "test".to_string(),
1741 device_type: "desktop".to_string(),
1742 operating_system: None,
1743 browser: None,
1744 screen_resolution: None,
1745 timezone: None,
1746 language: None,
1747 is_trusted: false,
1748 device_name: None,
1749 is_mobile: false,
1750 ip_address: None,
1751 };
1752
1753 let metadata = RequestMetadata::default();
1754 let history = vec![];
1755
1756 let risk = calculator.calculate_risk(&device_info, &metadata, &history, None);
1757 assert!(risk >= 20); }
1759
1760 #[derive(Default)]
1762 struct TestSessionStorage {
1763 sessions: std::sync::Mutex<std::collections::HashMap<String, Session>>,
1764 }
1765
1766 #[async_trait::async_trait]
1767 impl SessionStorage for TestSessionStorage {
1768 async fn create_session(&self, session: &Session) -> Result<()> {
1769 self.sessions
1770 .lock()
1771 .unwrap()
1772 .insert(session.id.clone(), session.clone());
1773 Ok(())
1774 }
1775 async fn get_session(&self, id: &str) -> Result<Option<Session>> {
1776 Ok(self.sessions.lock().unwrap().get(id).cloned())
1777 }
1778 async fn update_session(&self, session: &Session) -> Result<()> {
1779 self.create_session(session).await
1780 }
1781 async fn delete_session(&self, id: &str) -> Result<()> {
1782 self.sessions.lock().unwrap().remove(id);
1783 Ok(())
1784 }
1785 async fn get_user_sessions(&self, user_id: &str) -> Result<Vec<Session>> {
1786 Ok(self
1787 .sessions
1788 .lock()
1789 .unwrap()
1790 .values()
1791 .filter(|s| s.user_id == user_id)
1792 .cloned()
1793 .collect())
1794 }
1795 async fn count_active_sessions(&self, _user_id: &str) -> Result<u32> {
1796 Ok(0)
1797 }
1798 async fn cleanup_expired_sessions(&self) -> Result<u32> {
1799 Ok(0)
1800 }
1801 async fn find_sessions_by_device(&self, _fp: &str) -> Result<Vec<Session>> {
1802 Ok(vec![])
1803 }
1804 async fn find_sessions_by_ip(&self, _ip: &str) -> Result<Vec<Session>> {
1805 Ok(vec![])
1806 }
1807 }
1808
1809 #[tokio::test]
1810 async fn revoke_all_user_sessions_ends_every_live_session_whatever_its_state() {
1811 use crate::audit::{AuditLogger, TracingAuditStorage};
1812 let manager = SessionManager::new(
1813 TestSessionStorage::default(),
1814 SessionConfigBuilder::for_web_app().build(),
1815 AuditLogger::new(TracingAuditStorage),
1816 );
1817 let live_states = [
1818 SessionState::Active,
1819 SessionState::Suspended,
1820 SessionState::RequiresMfa,
1821 SessionState::RequiresReauth,
1822 SessionState::RequiresRotation,
1823 SessionState::HighRisk,
1824 ];
1825 let mut ids = Vec::new();
1826 for state in live_states.iter().cloned() {
1827 let mut s = Session::new("victim", Duration::from_secs(3600));
1828 s.state = state;
1829 manager.storage.create_session(&s).await.unwrap();
1830 ids.push(s.id);
1831 }
1832 let mut expired = Session::new("victim", Duration::from_secs(3600));
1834 expired.state = SessionState::Expired;
1835 manager.storage.create_session(&expired).await.unwrap();
1836 let other = Session::new("someone-else", Duration::from_secs(3600));
1837 manager.storage.create_session(&other).await.unwrap();
1838
1839 let revoked = manager.revoke_all_user_sessions("victim").await.unwrap();
1840 assert_eq!(revoked as usize, live_states.len());
1841 for (id, state) in ids.iter().zip(live_states.iter()) {
1842 let after = manager.storage.get_session(id).await.unwrap().unwrap();
1843 assert_eq!(after.state, SessionState::Revoked, "was {state:?}");
1844 }
1845 let expired_after = manager
1846 .storage
1847 .get_session(&expired.id)
1848 .await
1849 .unwrap()
1850 .unwrap();
1851 assert_eq!(expired_after.state, SessionState::Expired);
1852 let other_after = manager
1853 .storage
1854 .get_session(&other.id)
1855 .await
1856 .unwrap()
1857 .unwrap();
1858 assert_eq!(other_after.state, SessionState::Active);
1859 }
1860
1861 #[test]
1862 fn test_session_config_builder_for_web_app() {
1863 let config = SessionConfigBuilder::for_web_app().build();
1864 assert_eq!(config.default_duration, Duration::from_secs(3600));
1865 assert_eq!(config.max_duration, Duration::from_secs(86400));
1866 assert_eq!(config.max_concurrent_sessions, Some(5));
1867 assert!(config.track_device_fingerprints);
1868 }
1869
1870 #[test]
1871 fn test_session_config_builder_for_api_service() {
1872 let config = SessionConfigBuilder::for_api_service().build();
1873 assert_eq!(config.default_duration, Duration::from_secs(900));
1874 assert!(config.max_concurrent_sessions.is_none());
1875 assert!(!config.track_device_fingerprints);
1876 assert!(!config.rotate_periodically);
1877 }
1878
1879 #[test]
1880 fn test_session_config_builder_for_high_security() {
1881 let config = SessionConfigBuilder::for_high_security()
1882 .allowed_countries(vec!["US".into()])
1883 .build();
1884 assert_eq!(config.default_duration, Duration::from_secs(1800));
1885 assert_eq!(config.max_concurrent_sessions, Some(1));
1886 assert!(config.enforce_geographic_restrictions);
1887 assert_eq!(config.allowed_countries, vec!["US".to_string()]);
1888 assert!(config.security_policy.require_mfa_for_new_devices);
1889 }
1890
1891 #[test]
1895 fn maxmind_geolocation_none_for_missing_or_garbage_database() {
1896 let generator = DeviceFingerprintGenerator::new();
1897 let ip = std::net::Ipv4Addr::new(8, 8, 8, 8);
1898 let dir = tempfile::tempdir().unwrap();
1899
1900 let missing = dir.path().join("missing.mmdb");
1901 assert_eq!(
1902 generator.lookup_maxmind_geolocation_at(missing.to_str().unwrap(), &ip),
1903 None
1904 );
1905
1906 let garbage_inputs: [(&str, &[u8]); 3] = [
1907 ("empty.mmdb", b""),
1908 ("garbage.mmdb", b"this is not a MaxMind database at all"),
1909 ("truncated.mmdb", b"\xAB\xCD\xEFMaxMind.com\x00"),
1910 ];
1911 for (name, bytes) in garbage_inputs {
1912 let path = dir.path().join(name);
1913 std::fs::write(&path, bytes).unwrap();
1914 assert!(
1916 maxminddb::Reader::open_readfile(&path).is_err(),
1917 "{name}: maxminddb accepted garbage bytes"
1918 );
1919 assert_eq!(
1920 generator.lookup_maxmind_geolocation_at(path.to_str().unwrap(), &ip),
1921 None,
1922 "{name}"
1923 );
1924 }
1925 }
1926}