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,
226 pub rotate_periodically: bool,
228 pub rotation_interval: Duration,
230 pub max_concurrent_sessions: Option<u32>,
232 pub track_device_fingerprints: bool,
234 pub enforce_geographic_restrictions: bool,
236 pub allowed_countries: Vec<String>,
238 pub security_policy: SessionSecurityPolicy,
240}
241
242impl SessionConfig {
244 pub fn builder() -> SessionConfigBuilder {
246 SessionConfigBuilder::default()
247 }
248}
249
250#[derive(Default)]
252pub struct SessionConfigBuilder {
253 config: SessionConfig,
254}
255
256impl SessionConfigBuilder {
257 pub fn default_duration(mut self, duration: std::time::Duration) -> Self {
267 self.config.default_duration = duration;
268 self
269 }
270
271 pub fn max_duration(mut self, duration: std::time::Duration) -> Self {
280 self.config.max_duration = duration;
281 self
282 }
283
284 pub fn idle_timeout(mut self, timeout: std::time::Duration) -> Self {
293 self.config.idle_timeout = timeout;
294 self
295 }
296
297 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> {
847 let sessions = self.storage.get_user_sessions(user_id).await?;
848 let mut revoked_count = 0;
849
850 for mut session in sessions {
851 if session.state == SessionState::Active {
852 session.state = SessionState::Revoked;
853 self.storage.update_session(&session).await?;
854 revoked_count += 1;
855 }
856 }
857
858 Ok(revoked_count)
859 }
860
861 pub async fn get_user_sessions(
870 &self,
871 user_id: &str,
872 include_inactive: bool,
873 ) -> Result<Vec<Session>> {
874 let mut sessions = self.storage.get_user_sessions(user_id).await?;
875
876 if !include_inactive {
877 sessions.retain(|s| s.state == SessionState::Active);
878 }
879
880 Ok(sessions)
881 }
882
883 pub async fn list_user_sessions(
891 &self,
892 user_id: &str,
893 filter: crate::auth_operations::SessionFilter,
894 ) -> Result<Vec<Session>> {
895 self.get_user_sessions(user_id, filter.include_inactive())
896 .await
897 }
898
899 pub async fn cleanup_expired_sessions(&self) -> Result<u32> {
901 self.storage.cleanup_expired_sessions().await
902 }
903
904 pub fn generate_device_fingerprint(&self, metadata: &RequestMetadata) -> String {
906 self.fingerprint_generator.generate_fingerprint(metadata)
907 }
908
909 pub fn validate_device_fingerprint(
911 &self,
912 session: &Session,
913 metadata: &RequestMetadata,
914 ) -> bool {
915 let current_fingerprint = self.fingerprint_generator.generate_fingerprint(metadata);
916 current_fingerprint == session.device_info.fingerprint
917 }
918
919 pub async fn suspend_session(&self, session_id: &str, reason: &str) -> Result<()> {
921 if let Some(mut session) = self.storage.get_session(session_id).await? {
922 session.state = SessionState::Suspended;
923 session
924 .security_metadata
925 .security_flags
926 .push(SecurityFlag::SuspiciousActivity);
927
928 self.storage.update_session(&session).await?;
929
930 let mut details = HashMap::new();
932 details.insert("suspension_reason".to_string(), reason.to_string());
933
934 self.audit_logger
935 .log_event(
936 crate::audit::AuditEvent::builder(
937 crate::audit::AuditEventType::AccountLocked,
938 format!("Session suspended: {}", reason),
939 )
940 .user_id(session.user_id)
941 .session_id(session_id)
942 .outcome(crate::audit::EventOutcome::Success)
943 .risk_level(crate::audit::RiskLevel::High)
944 .details(details)
945 .with_actor("system", "security_monitor")
946 .build(),
947 )
948 .await?;
949 }
950 Ok(())
951 }
952
953 pub async fn update_session_data(
955 &self,
956 session_id: &str,
957 key: &str,
958 value: &str,
959 ) -> Result<()> {
960 if let Some(mut session) = self.storage.get_session(session_id).await? {
961 session.data.insert(key.to_string(), value.to_string());
962 session.last_accessed = SystemTime::now();
963 self.storage.update_session(&session).await?;
964 }
965 Ok(())
966 }
967
968 fn generate_session_id(&self) -> String {
970 format!("sess_{}", uuid::Uuid::new_v4())
971 }
972
973 fn should_rotate_session(&self, session: &Session) -> bool {
975 if !self.config.rotate_periodically {
976 return false;
977 }
978
979 let session_age = SystemTime::now()
980 .duration_since(session.created_at)
981 .unwrap_or_default();
982
983 session_age > self.config.rotation_interval
984 }
985
986 async fn get_user_session_history(&self, user_id: &str) -> Result<Vec<Session>> {
988 self.storage.get_user_sessions(user_id).await
991 }
992}
993
994pub struct DeviceFingerprintGenerator;
999
1000impl Default for DeviceFingerprintGenerator {
1001 fn default() -> Self {
1002 Self::new()
1003 }
1004}
1005
1006impl DeviceFingerprintGenerator {
1007 pub fn new() -> Self {
1008 Self
1009 }
1010
1011 pub fn generate_fingerprint(&self, metadata: &RequestMetadata) -> String {
1013 let mut fingerprint_data = Vec::new();
1014
1015 if let Some(ua) = &metadata.user_agent {
1016 fingerprint_data.push(ua.clone());
1017 }
1018
1019 self.add_advanced_fingerprinting_data(&mut fingerprint_data, metadata);
1021
1022 let fingerprint_string = fingerprint_data.join("|");
1023 format!("fp_{:x}", crc32fast::hash(fingerprint_string.as_bytes()))
1024 }
1025
1026 fn add_advanced_fingerprinting_data(
1028 &self,
1029 fingerprint_data: &mut Vec<String>,
1030 metadata: &RequestMetadata,
1031 ) {
1032 if let Some(ref ip) = metadata.ip_address {
1034 fingerprint_data.push(format!("geo:{}", self.get_ip_geolocation(ip)));
1036 }
1037
1038 fingerprint_data.push(format!("lang:{}", self.get_system_language()));
1040 fingerprint_data.push(format!("tz:{}", self.get_timezone_offset()));
1041 fingerprint_data.push(format!("hw:{}", self.get_hardware_concurrency()));
1042
1043 fingerprint_data.push(format!("conn:{}", self.get_connection_info()));
1045
1046 fingerprint_data.push(format!("caps:{}", self.get_client_capabilities()));
1048 }
1049
1050 fn get_ip_geolocation(&self, ip: &str) -> String {
1052 use std::net::IpAddr;
1053 use std::str::FromStr;
1054
1055 if let Ok(ip_addr) = IpAddr::from_str(ip) {
1057 match ip_addr {
1058 IpAddr::V4(ipv4) => {
1059 let octets = ipv4.octets();
1060
1061 if (octets[0] == 10)
1063 || (octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31)
1064 || (octets[0] == 192 && octets[1] == 168)
1065 {
1066 return "private_rfc1918".to_string();
1067 }
1068
1069 if octets[0] == 127 {
1071 return "loopback".to_string();
1072 }
1073
1074 if octets[0] == 169 && octets[1] == 254 {
1076 return "link_local".to_string();
1077 }
1078
1079 if octets[0] >= 224 && octets[0] <= 239 {
1081 return "multicast".to_string();
1082 }
1083
1084 match (octets[0], octets[1], octets[2], octets[3]) {
1086 (8, 8, 8, 8) | (8, 8, 4, 4) => "google_dns".to_string(),
1087 (1, 1, 1, 1) | (1, 0, 0, 1) => "cloudflare_dns".to_string(),
1088 (208, 67, 222, 222) | (208, 67, 220, 220) => "opendns".to_string(),
1089 _ => {
1090 self.lookup_maxmind_geolocation(&ipv4).unwrap_or_else(|| {
1092 match octets[0] {
1094 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),
1101 }
1102 })
1103 }
1104 }
1105 }
1106 IpAddr::V6(ipv6) => {
1107 let segments = ipv6.segments();
1108
1109 if ipv6.is_loopback() {
1111 return "ipv6_loopback".to_string();
1112 }
1113
1114 if segments[0] & 0xffc0 == 0xfe80 {
1116 return "ipv6_link_local".to_string();
1117 }
1118
1119 if segments[0] & 0xfe00 == 0xfc00 {
1121 return "ipv6_unique_local".to_string();
1122 }
1123
1124 if segments[0] & 0xff00 == 0xff00 {
1126 return "ipv6_multicast".to_string();
1127 }
1128
1129 format!("ipv6_global_{:x}", segments[0] / 0x1000)
1131 }
1132 }
1133 } else {
1134 "invalid_ip".to_string()
1135 }
1136 }
1137
1138 fn get_system_language(&self) -> String {
1140 "en-US".to_string()
1142 }
1143
1144 fn get_timezone_offset(&self) -> String {
1146 "-05:00".to_string() }
1149
1150 fn get_hardware_concurrency(&self) -> String {
1152 "4".to_string()
1154 }
1155
1156 fn get_connection_info(&self) -> String {
1158 "wifi".to_string()
1160 }
1161
1162 fn get_client_capabilities(&self) -> String {
1164 "webgl2_canvas_audio".to_string()
1166 }
1167
1168 fn lookup_maxmind_geolocation(&self, ip: &std::net::Ipv4Addr) -> Option<String> {
1170 use std::path::Path;
1171
1172 let db_path =
1174 std::env::var("MAXMIND_DB_PATH").unwrap_or_else(|_| "GeoLite2-City.mmdb".to_string());
1175
1176 if !Path::new(&db_path).exists() {
1177 tracing::warn!(
1178 "MaxMind database not found at {}, falling back to basic geolocation",
1179 db_path
1180 );
1181 return None;
1182 }
1183
1184 match maxminddb::Reader::open_readfile(&db_path) {
1185 Ok(reader) => {
1186 match reader.lookup((*ip).into()) {
1187 Ok(result) => match result.decode::<maxminddb::geoip2::City>() {
1188 Ok(Some(city)) => {
1189 let mut location_parts = Vec::new();
1190
1191 let location = &city.location;
1193 if let (Some(lat), Some(lon)) = (location.latitude, location.longitude)
1194 {
1195 location_parts.push(format!("coords:{:.4},{:.4}", lat, lon));
1196 }
1197
1198 if location_parts.is_empty() {
1201 None
1202 } else {
1203 Some(location_parts.join("|"))
1204 }
1205 }
1206 Ok(None) => {
1207 tracing::debug!("MaxMind lookup returned no data for {}", ip);
1208 None
1209 }
1210 Err(e) => {
1211 tracing::debug!("MaxMind decode failed for {}: {}", ip, e);
1212 None
1213 }
1214 },
1215 Err(e) => {
1216 tracing::debug!("MaxMind lookup failed for {}: {}", ip, e);
1217 None
1218 }
1219 }
1220 }
1221 Err(e) => {
1222 tracing::warn!("Failed to open MaxMind database: {}", e);
1223 None
1224 }
1225 }
1226 }
1227}
1228
1229pub struct RiskCalculator;
1235
1236impl Default for RiskCalculator {
1237 fn default() -> Self {
1238 Self::new()
1239 }
1240}
1241
1242impl RiskCalculator {
1243 pub fn new() -> Self {
1244 Self
1245 }
1246
1247 pub fn calculate_risk(
1249 &self,
1250 device_info: &DeviceInfo,
1251 metadata: &RequestMetadata,
1252 _session_history: &[Session],
1253 threat_intel_manager: Option<&ThreatFeedManager>,
1254 ) -> u8 {
1255 let mut risk_score = 0u8;
1256
1257 if !device_info.is_trusted {
1259 risk_score += 20;
1260 }
1261
1262 if let Some(ip) = &metadata.ip_address
1264 && self.is_suspicious_ip(ip, threat_intel_manager)
1265 {
1266 risk_score += 30;
1267 }
1268
1269 if let Some(location) = &metadata.geolocation {
1271 let mut geo_risk = 0;
1272
1273 if let Some(country) = &location.country {
1275 let country_lower = country.to_lowercase();
1276
1277 let high_risk_countries =
1279 ["tor", "anonymous", "vpn", "proxy", "hosting", "datacenter"];
1280
1281 for indicator in &high_risk_countries {
1282 if country_lower.contains(indicator) {
1283 geo_risk += 30;
1284 break;
1285 }
1286 }
1287
1288 geo_risk += self.assess_country_threat_level(&country_lower) as u8;
1290
1291 let elevated_risk_patterns = ["cloud", "aws", "azure", "gcp"];
1293 for pattern in &elevated_risk_patterns {
1294 if country_lower.contains(pattern) {
1295 geo_risk += 20;
1296 break;
1297 }
1298 }
1299 }
1300
1301 if let (Some(lat), Some(lon)) = (location.latitude, location.longitude) {
1303 if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
1305 geo_risk += 25; }
1307
1308 if (lat * 100.0).fract().abs() < 0.01 && (lon * 100.0).fract().abs() < 0.01 {
1310 geo_risk += 15; }
1312 }
1313
1314 if let Some(region) = &location.region {
1316 let region_lower = region.to_lowercase();
1317 if region_lower.contains("hosting") || region_lower.contains("datacenter") {
1318 geo_risk += 20;
1319 }
1320 }
1321
1322 if let Some(city) = &location.city {
1324 let city_lower = city.to_lowercase();
1325 if city_lower.contains("server") || city_lower.contains("datacenter") {
1326 geo_risk += 15;
1327 }
1328 }
1329
1330 risk_score += geo_risk;
1331 }
1332
1333 risk_score.min(100)
1339 }
1340
1341 fn is_suspicious_ip(&self, ip: &str, threat_intel_manager: Option<&ThreatFeedManager>) -> bool {
1343 use std::net::IpAddr;
1344 use std::str::FromStr;
1345
1346 if let Ok(ip_addr) = IpAddr::from_str(ip) {
1348 match ip_addr {
1349 IpAddr::V4(ipv4) => {
1350 let octets = ipv4.octets();
1351
1352 if self.check_malicious_ip_feeds(&ipv4, threat_intel_manager) {
1354 return true;
1355 }
1356
1357 let suspicious_ranges = [
1359 (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), ];
1367
1368 for (net, _, _, _, _) in &suspicious_ranges {
1369 if octets[0] == *net {
1370 return true;
1371 }
1372 }
1373
1374 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)
1380 {
1381 return true;
1383 }
1384
1385 if octets[3] == 0 || octets[3] == 255 {
1387 return true;
1388 }
1389
1390 if self.check_proxy_vpn_databases(&ipv4) {
1392 return true;
1393 }
1394
1395 let proxy_ports_in_ip = [
1397 80, 443, 8080, 3128, 1080, 8000, 8888, 9050, ];
1399
1400 for &port in &proxy_ports_in_ip {
1401 if octets[2] == (port / 256) as u8 && octets[3] == (port % 256) as u8 {
1402 return true;
1403 }
1404 }
1405
1406 false
1407 }
1408 IpAddr::V6(ipv6) => {
1409 let segments = ipv6.segments();
1410
1411 if self.check_tor_exit_nodes(&ipv6) {
1413 return true;
1414 }
1415
1416 if segments[0] == 0x2001 && segments[1] == 0x67c {
1418 return true;
1420 }
1421
1422 let mut sequential_count = 0;
1424 for i in 1..segments.len() {
1425 if segments[i] == segments[i - 1] + 1 {
1426 sequential_count += 1;
1427 }
1428 }
1429 if sequential_count >= 4 {
1430 return true;
1432 }
1433
1434 if segments[0] == 0x2001 && segments[1] == 0x470 {
1436 return true;
1438 }
1439
1440 false
1441 }
1442 }
1443 } else {
1444 true }
1446 }
1447
1448 fn assess_country_threat_level(&self, country: &str) -> u32 {
1450 use std::path::Path;
1451
1452 let threat_db_path = std::env::var("COUNTRY_THREAT_DB_PATH")
1454 .unwrap_or_else(|_| "country-threats.csv".to_string());
1455
1456 if Path::new(&threat_db_path).exists() {
1457 if let Ok(contents) = std::fs::read_to_string(&threat_db_path) {
1459 let mut csv_reader = csv::Reader::from_reader(contents.as_bytes());
1460
1461 for result in csv_reader.records() {
1462 if let Ok(record) = result
1463 && record.len() >= 2
1464 {
1465 let threat_country = record[0].to_lowercase();
1466 if let Ok(risk_score) = record[1].parse::<u32>()
1467 && country.contains(&threat_country)
1468 {
1469 tracing::debug!(
1470 "Country threat match: {} -> risk {}",
1471 country,
1472 risk_score
1473 );
1474 return risk_score;
1475 }
1476 }
1477 }
1478 }
1479 }
1480
1481 0 }
1484
1485 fn check_malicious_ip_feeds(
1487 &self,
1488 ip: &std::net::Ipv4Addr,
1489 threat_intel_manager: Option<&ThreatFeedManager>,
1490 ) -> bool {
1491 if let Some(threat_manager) = threat_intel_manager {
1493 return threat_manager.is_malicious_ip(&std::net::IpAddr::V4(*ip));
1494 }
1495
1496 use std::path::Path;
1498
1499 let feed_paths = [
1501 std::env::var("MALICIOUS_IPS_DB_PATH")
1502 .unwrap_or_else(|_| "malicious-ips.txt".to_string()),
1503 std::env::var("BOTNET_IPS_DB_PATH").unwrap_or_else(|_| "botnet-ips.txt".to_string()),
1504 std::env::var("TOR_EXIT_NODES_DB_PATH").unwrap_or_else(|_| "tor-exits.txt".to_string()),
1505 ];
1506
1507 for feed_path in &feed_paths {
1508 if Path::new(feed_path).exists()
1509 && let Ok(contents) = std::fs::read_to_string(feed_path)
1510 {
1511 for line in contents.lines() {
1512 let line = line.trim();
1513 if line.is_empty() || line.starts_with('#') {
1514 continue;
1515 }
1516
1517 if line == ip.to_string() {
1519 tracing::warn!("Malicious IP detected: {} (source: {})", ip, feed_path);
1520 return true;
1521 }
1522
1523 if line.contains('/')
1525 && let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1526 && network.contains(*ip)
1527 {
1528 tracing::warn!(
1529 "Malicious network detected: {} in {} (source: {})",
1530 ip,
1531 network,
1532 feed_path
1533 );
1534 return true;
1535 }
1536 }
1537 }
1538 }
1539
1540 false
1541 }
1542
1543 fn check_proxy_vpn_databases(&self, ip: &std::net::Ipv4Addr) -> bool {
1545 use std::path::Path;
1546
1547 let db_sources = [
1549 ("VPN_DATABASE_PATH", "vpn-ranges.txt"),
1550 ("PROXY_DATABASE_PATH", "proxy-ips.txt"),
1551 ("DATACENTER_DATABASE_PATH", "datacenter-ranges.txt"),
1552 ("HOSTING_DATABASE_PATH", "hosting-providers.txt"),
1553 ];
1554
1555 for (env_var, default_file) in &db_sources {
1556 let db_path = std::env::var(env_var).unwrap_or_else(|_| default_file.to_string());
1557
1558 if Path::new(&db_path).exists()
1559 && let Ok(contents) = std::fs::read_to_string(&db_path)
1560 {
1561 for line in contents.lines() {
1562 let line = line.trim();
1563 if line.is_empty() || line.starts_with('#') {
1564 continue;
1565 }
1566
1567 if line.contains('/') {
1569 if let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1571 && network.contains(*ip)
1572 {
1573 tracing::info!(
1574 "Proxy/VPN detected: {} in {} (source: {})",
1575 ip,
1576 network,
1577 db_path
1578 );
1579 return true;
1580 }
1581 } else if line.contains('-') {
1582 let parts: Vec<&str> = line.split('-').collect();
1584 if parts.len() == 2
1585 && let (Ok(start_ip), Ok(end_ip)) = (
1586 parts[0].trim().parse::<std::net::Ipv4Addr>(),
1587 parts[1].trim().parse::<std::net::Ipv4Addr>(),
1588 )
1589 {
1590 let ip_u32 = u32::from(*ip);
1591 let start_u32 = u32::from(start_ip);
1592 let end_u32 = u32::from(end_ip);
1593
1594 if ip_u32 >= start_u32 && ip_u32 <= end_u32 {
1595 tracing::info!(
1596 "Proxy/VPN range detected: {} in {}-{} (source: {})",
1597 ip,
1598 start_ip,
1599 end_ip,
1600 db_path
1601 );
1602 return true;
1603 }
1604 }
1605 } else if line == ip.to_string() {
1606 tracing::info!("Proxy/VPN exact match: {} (source: {})", ip, db_path);
1608 return true;
1609 }
1610 }
1611 }
1612 }
1613
1614 false
1615 }
1616
1617 fn check_tor_exit_nodes(&self, ip: &std::net::Ipv6Addr) -> bool {
1619 use std::path::Path;
1620
1621 let tor_db_path = std::env::var("TOR_EXIT_NODES_IPV6_PATH")
1623 .unwrap_or_else(|_| "tor-exits-ipv6.txt".to_string());
1624
1625 if Path::new(&tor_db_path).exists()
1626 && let Ok(contents) = std::fs::read_to_string(&tor_db_path)
1627 {
1628 for line in contents.lines() {
1629 let line = line.trim();
1630 if line.is_empty() || line.starts_with('#') {
1631 continue;
1632 }
1633
1634 if let Ok(tor_ip) = line.parse::<std::net::Ipv6Addr>()
1636 && tor_ip == *ip
1637 {
1638 tracing::warn!("Tor exit node detected: {}", ip);
1639 return true;
1640 }
1641
1642 if line.contains('/')
1644 && let Ok(network) = line.parse::<ipnetwork::Ipv6Network>()
1645 && network.contains(*ip)
1646 {
1647 tracing::warn!("Tor exit network detected: {} in {}", ip, network);
1648 return true;
1649 }
1650 }
1651 }
1652
1653 if let Some(ipv4) = ip.to_ipv4() {
1655 let tor_v4_path = std::env::var("TOR_EXIT_NODES_IPV4_PATH")
1656 .unwrap_or_else(|_| "tor-exits-ipv4.txt".to_string());
1657
1658 if Path::new(&tor_v4_path).exists()
1659 && let Ok(contents) = std::fs::read_to_string(&tor_v4_path)
1660 {
1661 for line in contents.lines() {
1662 let line = line.trim();
1663 if line == ipv4.to_string() {
1664 tracing::warn!("Tor exit node detected (IPv4-mapped): {}", ip);
1665 return true;
1666 }
1667 }
1668 }
1669 }
1670
1671 false
1672 }
1673}
1674
1675impl Default for SessionConfig {
1676 fn default() -> Self {
1677 Self {
1678 default_duration: Duration::from_secs(3600), max_duration: Duration::from_secs(86400), idle_timeout: Duration::from_secs(1800), rotate_on_privilege_escalation: true,
1682 rotate_periodically: true,
1683 rotation_interval: Duration::from_secs(1800), max_concurrent_sessions: Some(5),
1685 track_device_fingerprints: true,
1686 enforce_geographic_restrictions: false,
1687 allowed_countries: vec![],
1688 security_policy: SessionSecurityPolicy::default(),
1689 }
1690 }
1691}
1692
1693impl Default for SessionSecurityPolicy {
1694 fn default() -> Self {
1695 Self {
1696 require_mfa_for_new_devices: true,
1697 require_reauth_for_sensitive_ops: true,
1698 reauth_timeout: Duration::from_secs(300), max_risk_score: 70,
1700 auto_suspend_suspicious: true,
1701 verify_location_changes: true,
1702 limit_concurrent_sessions: true,
1703 }
1704 }
1705}
1706
1707#[cfg(test)]
1708mod tests {
1709 use super::*;
1710
1711 #[test]
1712 fn test_device_fingerprint_generation() {
1713 let generator = DeviceFingerprintGenerator::new();
1714 let metadata = RequestMetadata {
1715 user_agent: Some("Mozilla/5.0".to_string()),
1716 ..Default::default()
1717 };
1718
1719 let fp1 = generator.generate_fingerprint(&metadata);
1720 let fp2 = generator.generate_fingerprint(&metadata);
1721
1722 assert_eq!(fp1, fp2);
1723 assert!(fp1.starts_with("fp_"));
1724 }
1725
1726 #[test]
1727 fn test_risk_calculation() {
1728 let calculator = RiskCalculator::new();
1729 let device_info = DeviceInfo {
1730 fingerprint: "test".to_string(),
1731 device_type: "desktop".to_string(),
1732 operating_system: None,
1733 browser: None,
1734 screen_resolution: None,
1735 timezone: None,
1736 language: None,
1737 is_trusted: false,
1738 device_name: None,
1739 is_mobile: false,
1740 ip_address: None,
1741 };
1742
1743 let metadata = RequestMetadata::default();
1744 let history = vec![];
1745
1746 let risk = calculator.calculate_risk(&device_info, &metadata, &history, None);
1747 assert!(risk >= 20); }
1749
1750 #[test]
1751 fn test_session_config_builder_for_web_app() {
1752 let config = SessionConfigBuilder::for_web_app().build();
1753 assert_eq!(config.default_duration, Duration::from_secs(3600));
1754 assert_eq!(config.max_duration, Duration::from_secs(86400));
1755 assert_eq!(config.max_concurrent_sessions, Some(5));
1756 assert!(config.track_device_fingerprints);
1757 }
1758
1759 #[test]
1760 fn test_session_config_builder_for_api_service() {
1761 let config = SessionConfigBuilder::for_api_service().build();
1762 assert_eq!(config.default_duration, Duration::from_secs(900));
1763 assert!(config.max_concurrent_sessions.is_none());
1764 assert!(!config.track_device_fingerprints);
1765 assert!(!config.rotate_periodically);
1766 }
1767
1768 #[test]
1769 fn test_session_config_builder_for_high_security() {
1770 let config = SessionConfigBuilder::for_high_security()
1771 .allowed_countries(vec!["US".into()])
1772 .build();
1773 assert_eq!(config.default_duration, Duration::from_secs(1800));
1774 assert_eq!(config.max_concurrent_sessions, Some(1));
1775 assert!(config.enforce_geographic_restrictions);
1776 assert_eq!(config.allowed_countries, vec!["US".to_string()]);
1777 assert!(config.security_policy.require_mfa_for_new_devices);
1778 }
1779}