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(Debug, 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 Session {
47 pub fn new(user_id: impl Into<String>, lifetime: Duration) -> Self {
63 let now = SystemTime::now();
64 Self {
65 id: uuid::Uuid::new_v4().to_string(),
66 user_id: user_id.into(),
67 created_at: now,
68 last_accessed: now,
69 expires_at: now + lifetime,
70 state: SessionState::Active,
71 device_info: DeviceInfo::unknown(),
72 security_metadata: SecurityMetadata::default(),
73 data: HashMap::new(),
74 mfa_verified: false,
75 cached_permissions: None,
76 last_activity: ActivityInfo {
77 endpoint: None,
78 action: None,
79 request_metadata: None,
80 timestamp: now,
81 },
82 }
83 }
84}
85
86#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
88pub enum SessionState {
89 Active,
90 Expired,
91 Revoked,
92 Suspended,
93 RequiresMfa,
94 RequiresReauth,
95 RequiresRotation,
97 HighRisk,
99}
100
101#[derive(Debug, Clone, Serialize, Deserialize)]
103pub struct DeviceInfo {
104 pub fingerprint: String,
106 pub device_type: String,
108 pub operating_system: Option<String>,
110 pub browser: Option<String>,
112 pub screen_resolution: Option<String>,
114 pub timezone: Option<String>,
116 pub language: Option<String>,
118 pub is_trusted: bool,
120 pub device_name: Option<String>,
122 pub is_mobile: bool,
124 pub ip_address: Option<String>,
126}
127
128impl DeviceInfo {
129 pub fn unknown() -> Self {
131 Self {
132 fingerprint: String::new(),
133 device_type: "unknown".into(),
134 operating_system: None,
135 browser: None,
136 screen_resolution: None,
137 timezone: None,
138 language: None,
139 is_trusted: false,
140 device_name: None,
141 is_mobile: false,
142 ip_address: None,
143 }
144 }
145}
146
147#[derive(Debug, Clone, Serialize, Deserialize, Default)]
149pub struct SecurityMetadata {
150 pub creation_ip: String,
152 pub current_ip: String,
154 pub creation_location: Option<GeolocationInfo>,
156 pub current_location: Option<GeolocationInfo>,
158 pub security_flags: Vec<SecurityFlag>,
160 pub risk_score: u8,
162 pub location_changed: bool,
164 pub ip_changed: bool,
166 pub failed_auth_attempts: u32,
168}
169
170#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
172pub enum SecurityFlag {
173 SuspiciousActivity,
174 LocationAnomaly,
175 DeviceAnomaly,
176 TimeAnomaly,
177 ConcurrentSessionLimit,
178 BruteForceAttempt,
179 RequiresVerification,
180 ElevatedPrivileges,
181}
182
183#[derive(Debug, Clone, Serialize, Deserialize)]
185pub struct ActivityInfo {
186 pub endpoint: Option<String>,
188 pub action: Option<String>,
190 pub request_metadata: Option<RequestMetadata>,
192 pub timestamp: SystemTime,
194}
195
196#[derive(Debug, Clone)]
198pub struct SessionConfig {
199 pub default_duration: Duration,
201 pub max_duration: Duration,
203 pub idle_timeout: Duration,
205 pub rotate_on_privilege_escalation: bool,
209 pub rotate_periodically: bool,
211 pub rotation_interval: Duration,
213 pub max_concurrent_sessions: Option<u32>,
215 pub track_device_fingerprints: bool,
217 pub enforce_geographic_restrictions: bool,
219 pub allowed_countries: Vec<String>,
221 pub security_policy: SessionSecurityPolicy,
223}
224
225impl SessionConfig {
227 pub fn builder() -> SessionConfigBuilder {
229 SessionConfigBuilder::default()
230 }
231}
232
233#[derive(Default)]
235pub struct SessionConfigBuilder {
236 config: SessionConfig,
237}
238
239impl SessionConfigBuilder {
240 pub fn default_duration(mut self, duration: std::time::Duration) -> Self {
250 self.config.default_duration = duration;
251 self
252 }
253
254 pub fn max_duration(mut self, duration: std::time::Duration) -> Self {
263 self.config.max_duration = duration;
264 self
265 }
266
267 pub fn idle_timeout(mut self, timeout: std::time::Duration) -> Self {
276 self.config.idle_timeout = timeout;
277 self
278 }
279
280 #[deprecated(
283 since = "0.6.0",
284 note = "has no effect: sessions are not rotated on privilege escalation; use rotate_periodically"
285 )]
286 pub fn rotate_on_privilege_escalation(mut self, rotate: bool) -> Self {
287 self.config.rotate_on_privilege_escalation = rotate;
288 self
289 }
290
291 pub fn rotate_periodically(mut self, rotate: bool) -> Self {
301 self.config.rotate_periodically = rotate;
302 self
303 }
304
305 pub fn rotation_interval(mut self, interval: std::time::Duration) -> Self {
315 self.config.rotation_interval = interval;
316 self
317 }
318
319 pub fn max_concurrent_sessions(mut self, max: u32) -> Self {
328 self.config.max_concurrent_sessions = Some(max);
329 self
330 }
331
332 pub fn allowed_countries(mut self, countries: Vec<String>) -> Self {
337 self.config.allowed_countries = countries;
338 self
339 }
340
341 pub fn for_web_app() -> Self {
350 Self {
351 config: SessionConfig {
352 default_duration: Duration::from_secs(3600), max_duration: Duration::from_secs(86400), idle_timeout: Duration::from_secs(1800), rotate_on_privilege_escalation: true,
356 rotate_periodically: true,
357 rotation_interval: Duration::from_secs(1800), max_concurrent_sessions: Some(5),
359 track_device_fingerprints: true,
360 enforce_geographic_restrictions: false,
361 allowed_countries: vec![],
362 security_policy: SessionSecurityPolicy::default(),
363 },
364 }
365 }
366
367 pub fn for_api_service() -> Self {
378 Self {
379 config: SessionConfig {
380 default_duration: Duration::from_secs(900), max_duration: Duration::from_secs(3600), idle_timeout: Duration::from_secs(600), rotate_on_privilege_escalation: true,
384 rotate_periodically: false,
385 rotation_interval: Duration::from_secs(3600),
386 max_concurrent_sessions: None, track_device_fingerprints: false,
388 enforce_geographic_restrictions: false,
389 allowed_countries: vec![],
390 security_policy: SessionSecurityPolicy {
391 require_mfa_for_new_devices: false,
392 require_reauth_for_sensitive_ops: false,
393 reauth_timeout: Duration::from_secs(300),
394 max_risk_score: 90,
395 auto_suspend_suspicious: false,
396 verify_location_changes: false,
397 limit_concurrent_sessions: false,
398 },
399 },
400 }
401 }
402
403 pub fn for_high_security() -> Self {
413 Self {
414 config: SessionConfig {
415 default_duration: Duration::from_secs(1800), max_duration: Duration::from_secs(7200), idle_timeout: Duration::from_secs(300), rotate_on_privilege_escalation: true,
419 rotate_periodically: true,
420 rotation_interval: Duration::from_secs(900), max_concurrent_sessions: Some(1),
422 track_device_fingerprints: true,
423 enforce_geographic_restrictions: true,
424 allowed_countries: vec![], security_policy: SessionSecurityPolicy {
426 require_mfa_for_new_devices: true,
427 require_reauth_for_sensitive_ops: true,
428 reauth_timeout: Duration::from_secs(120), max_risk_score: 40,
430 auto_suspend_suspicious: true,
431 verify_location_changes: true,
432 limit_concurrent_sessions: true,
433 },
434 },
435 }
436 }
437
438 pub fn build(self) -> SessionConfig {
448 self.config
449 }
450}
451
452#[derive(Debug, Clone)]
453pub struct SessionSecurityPolicy {
454 pub require_mfa_for_new_devices: bool,
456 pub require_reauth_for_sensitive_ops: bool,
458 pub reauth_timeout: Duration,
460 pub max_risk_score: u8,
462 pub auto_suspend_suspicious: bool,
464 pub verify_location_changes: bool,
466 pub limit_concurrent_sessions: bool,
468}
469
470#[async_trait]
472pub trait SessionStorage: Send + Sync {
473 async fn create_session(&self, session: &Session) -> Result<()>;
475
476 async fn get_session(&self, session_id: &str) -> Result<Option<Session>>;
478
479 async fn update_session(&self, session: &Session) -> Result<()>;
481
482 async fn delete_session(&self, session_id: &str) -> Result<()>;
484
485 async fn get_user_sessions(&self, user_id: &str) -> Result<Vec<Session>>;
487
488 async fn count_active_sessions(&self, user_id: &str) -> Result<u32>;
490
491 async fn cleanup_expired_sessions(&self) -> Result<u32>;
493
494 async fn find_sessions_by_device(&self, device_fingerprint: &str) -> Result<Vec<Session>>;
496
497 async fn find_sessions_by_ip(&self, ip_address: &str) -> Result<Vec<Session>>;
499}
500
501pub struct SessionManager<S: SessionStorage, A: AuditStorage> {
503 storage: S,
504 config: SessionConfig,
505 audit_logger: AuditLogger<A>,
506 fingerprint_generator: DeviceFingerprintGenerator,
507 risk_calculator: RiskCalculator,
508 threat_intel_manager: Option<ThreatFeedManager>,
509}
510
511impl<S: SessionStorage, A: AuditStorage> SessionManager<S, A> {
512 pub fn new(storage: S, config: SessionConfig, audit_logger: AuditLogger<A>) -> Self {
517 let threat_intel_manager = if std::env::var("THREAT_INTEL_ENABLED")
519 .unwrap_or_else(|_| "false".to_string())
520 .to_lowercase()
521 == "true"
522 {
523 match ThreatIntelConfig::from_env_and_config() {
524 Ok(intel_config) => {
525 tracing::info!(
526 "🟢 Automated threat intelligence enabled - feeds will update automatically"
527 );
528 match ThreatFeedManager::new(intel_config) {
529 Ok(manager) => {
530 if let Err(e) = manager.start_automated_updates() {
532 tracing::error!(
533 "Failed to start automated threat feed updates: {}",
534 e
535 );
536 None
537 } else {
538 tracing::info!(
539 "✅ Threat intelligence automation started successfully"
540 );
541 Some(manager)
542 }
543 }
544 Err(e) => {
545 tracing::error!(
546 "Failed to initialize threat intelligence manager: {}",
547 e
548 );
549 None
550 }
551 }
552 }
553 Err(e) => {
554 tracing::error!("Failed to load threat intelligence configuration: {}", e);
555 None
556 }
557 }
558 } else {
559 tracing::info!(
560 "🔴 Automated threat intelligence disabled (THREAT_INTEL_ENABLED=false)"
561 );
562 None
563 };
564
565 Self {
566 storage,
567 config,
568 audit_logger,
569 fingerprint_generator: DeviceFingerprintGenerator::new(),
570 risk_calculator: RiskCalculator::new(),
571 threat_intel_manager,
572 }
573 }
574
575 pub async fn create_session(
577 &self,
578 user_id: &str,
579 mut device_info: DeviceInfo,
580 metadata: RequestMetadata,
581 ) -> Result<Session> {
582 if device_info.fingerprint.is_empty() {
584 device_info.fingerprint = self.fingerprint_generator.generate_fingerprint(&metadata);
585 }
586
587 if let Some(max_sessions) = self.config.max_concurrent_sessions {
589 let active_count = self.storage.count_active_sessions(user_id).await?;
590 if active_count >= max_sessions {
591 return Err(AuthError::TooManyConcurrentSessions);
592 }
593 }
594
595 let now = SystemTime::now();
596 let session_id = self.generate_session_id();
597
598 let risk_score = self.risk_calculator.calculate_risk(
600 &device_info,
601 &metadata,
602 &self.get_user_session_history(user_id).await?,
603 self.threat_intel_manager.as_ref(),
604 );
605
606 let mut security_flags = Vec::new();
607 if risk_score > 70 {
608 security_flags.push(SecurityFlag::SuspiciousActivity);
609 }
610
611 let existing_sessions = self
613 .storage
614 .find_sessions_by_device(&device_info.fingerprint)
615 .await?;
616 let is_new_device = existing_sessions.is_empty();
617
618 if is_new_device && self.config.security_policy.require_mfa_for_new_devices {
619 security_flags.push(SecurityFlag::RequiresVerification);
620 }
621
622 let session = Session {
623 id: session_id.clone(),
624 user_id: user_id.to_string(),
625 created_at: now,
626 last_accessed: now,
627 expires_at: now + self.config.default_duration,
628 state: if security_flags.contains(&SecurityFlag::RequiresVerification) {
629 SessionState::RequiresMfa
630 } else {
631 SessionState::Active
632 },
633 device_info: device_info.clone(),
634 security_metadata: SecurityMetadata {
635 creation_ip: metadata.ip_address.clone().unwrap_or_default(),
636 current_ip: metadata.ip_address.clone().unwrap_or_default(),
637 creation_location: metadata.geolocation.clone(),
638 current_location: metadata.geolocation.clone(),
639 security_flags,
640 risk_score,
641 location_changed: false,
642 ip_changed: false,
643 failed_auth_attempts: 0,
644 },
645 data: HashMap::new(),
646 mfa_verified: false,
647 cached_permissions: None,
648 last_activity: ActivityInfo {
649 endpoint: metadata.endpoint.clone(),
650 action: Some("session_created".to_string()),
651 request_metadata: Some(metadata.clone()),
652 timestamp: now,
653 },
654 };
655
656 self.storage.create_session(&session).await?;
657
658 self.audit_logger
660 .log_event({
661 let mut ev = crate::audit::AuditEvent::builder(
662 crate::audit::AuditEventType::LoginSuccess,
663 "Session created",
664 )
665 .user_id(user_id)
666 .outcome(crate::audit::EventOutcome::Success)
667 .risk_level(if risk_score > 70 {
668 crate::audit::RiskLevel::High
669 } else {
670 crate::audit::RiskLevel::Low
671 })
672 .request_metadata(metadata)
673 .with_actor("user", user_id)
674 .build();
675 ev.session_id = Some(session_id);
676 ev.timestamp = now;
677 ev
678 })
679 .await?;
680
681 Ok(session)
682 }
683
684 pub async fn validate_session(
686 &self,
687 session_id: &str,
688 metadata: RequestMetadata,
689 ) -> Result<Option<Session>> {
690 let mut session = match self.storage.get_session(session_id).await? {
691 Some(session) => session,
692 None => return Ok(None),
693 };
694
695 let now = SystemTime::now();
696
697 if let Ok(age) = now.duration_since(session.created_at)
699 && age > self.config.max_duration
700 {
701 session.state = SessionState::Expired;
702 self.storage.update_session(&session).await?;
703 return Ok(None);
704 }
705
706 if session.expires_at <= now {
708 session.state = SessionState::Expired;
709 self.storage.update_session(&session).await?;
710 return Ok(None);
711 }
712
713 let current_fingerprint = self.fingerprint_generator.generate_fingerprint(&metadata);
715 if current_fingerprint != session.device_info.fingerprint {
716 session.state = SessionState::RequiresMfa;
718 self.storage.update_session(&session).await?;
719
720 self.audit_logger
722 .log_suspicious_activity(
723 Some(&session.user_id),
724 "device_fingerprint_mismatch",
725 &format!(
726 "Session ID: {}, Expected: {}, Got: {}",
727 session_id, session.device_info.fingerprint, current_fingerprint
728 ),
729 metadata.clone(),
730 )
731 .await?;
732 }
733
734 let idle_duration = now
736 .duration_since(session.last_accessed)
737 .unwrap_or_default();
738 if idle_duration > self.config.idle_timeout {
739 session.state = SessionState::Expired;
740 self.storage.update_session(&session).await?;
741 return Ok(None);
742 }
743
744 match session.state {
746 SessionState::Expired | SessionState::Revoked | SessionState::Suspended => {
747 return Ok(None);
748 }
749 SessionState::RequiresMfa | SessionState::RequiresReauth => {
750 return Ok(Some(session));
752 }
753 SessionState::Active | SessionState::RequiresRotation | SessionState::HighRisk => {}
754 }
755
756 let current_ip = metadata.ip_address.clone().unwrap_or_default();
758 let ip_changed = current_ip != session.security_metadata.current_ip;
759
760 if ip_changed {
761 session.security_metadata.ip_changed = true;
762 session.security_metadata.current_ip = current_ip;
763
764 if self.config.security_policy.verify_location_changes {
766 session
767 .security_metadata
768 .security_flags
769 .push(SecurityFlag::LocationAnomaly);
770 session.state = SessionState::RequiresReauth;
771 }
772 }
773
774 session.last_accessed = now;
776 session.last_activity = ActivityInfo {
777 endpoint: metadata.endpoint.clone(),
778 action: Some("session_validated".to_string()),
779 request_metadata: Some(metadata),
780 timestamp: now,
781 };
782
783 let should_rotate = self.should_rotate_session(&session);
785 if should_rotate {
786 let new_session_id = self.generate_session_id();
787 let old_session_id = session.id.clone();
788 session.id = new_session_id;
789
790 self.storage.delete_session(&old_session_id).await?;
792 self.storage.create_session(&session).await?;
793 } else {
794 self.storage.update_session(&session).await?;
795 }
796
797 Ok(Some(session))
798 }
799
800 pub async fn revoke_session(&self, session_id: &str) -> Result<()> {
802 if let Some(mut session) = self.storage.get_session(session_id).await? {
803 session.state = SessionState::Revoked;
804 self.storage.update_session(&session).await?;
805
806 self.audit_logger
808 .log_event(
809 crate::audit::AuditEvent::builder(
810 crate::audit::AuditEventType::Logout,
811 "Session revoked",
812 )
813 .user_id(session.user_id)
814 .session_id(session_id)
815 .outcome(crate::audit::EventOutcome::Success)
816 .with_actor("system", "session_manager")
817 .build(),
818 )
819 .await?;
820 }
821 Ok(())
822 }
823
824 pub async fn revoke_all_user_sessions(&self, user_id: &str) -> Result<u32> {
828 let sessions = self.storage.get_user_sessions(user_id).await?;
829 let mut revoked_count = 0;
830
831 for mut session in sessions {
832 if !matches!(session.state, SessionState::Expired | SessionState::Revoked) {
833 session.state = SessionState::Revoked;
834 self.storage.update_session(&session).await?;
835 revoked_count += 1;
836 }
837 }
838
839 Ok(revoked_count)
840 }
841
842 pub async fn get_user_sessions(
851 &self,
852 user_id: &str,
853 include_inactive: bool,
854 ) -> Result<Vec<Session>> {
855 let mut sessions = self.storage.get_user_sessions(user_id).await?;
856
857 if !include_inactive {
858 sessions.retain(|s| s.state == SessionState::Active);
859 }
860
861 Ok(sessions)
862 }
863
864 pub async fn list_user_sessions(
872 &self,
873 user_id: &str,
874 filter: crate::auth_operations::SessionFilter,
875 ) -> Result<Vec<Session>> {
876 self.get_user_sessions(user_id, filter.include_inactive())
877 .await
878 }
879
880 pub async fn cleanup_expired_sessions(&self) -> Result<u32> {
882 self.storage.cleanup_expired_sessions().await
883 }
884
885 pub fn generate_device_fingerprint(&self, metadata: &RequestMetadata) -> String {
887 self.fingerprint_generator.generate_fingerprint(metadata)
888 }
889
890 pub fn validate_device_fingerprint(
892 &self,
893 session: &Session,
894 metadata: &RequestMetadata,
895 ) -> bool {
896 let current_fingerprint = self.fingerprint_generator.generate_fingerprint(metadata);
897 current_fingerprint == session.device_info.fingerprint
898 }
899
900 pub async fn suspend_session(&self, session_id: &str, reason: &str) -> Result<()> {
902 if let Some(mut session) = self.storage.get_session(session_id).await? {
903 session.state = SessionState::Suspended;
904 session
905 .security_metadata
906 .security_flags
907 .push(SecurityFlag::SuspiciousActivity);
908
909 self.storage.update_session(&session).await?;
910
911 let mut details = HashMap::new();
913 details.insert("suspension_reason".to_string(), reason.to_string());
914
915 self.audit_logger
916 .log_event(
917 crate::audit::AuditEvent::builder(
918 crate::audit::AuditEventType::AccountLocked,
919 format!("Session suspended: {}", reason),
920 )
921 .user_id(session.user_id)
922 .session_id(session_id)
923 .outcome(crate::audit::EventOutcome::Success)
924 .risk_level(crate::audit::RiskLevel::High)
925 .details(details)
926 .with_actor("system", "security_monitor")
927 .build(),
928 )
929 .await?;
930 }
931 Ok(())
932 }
933
934 pub async fn update_session_data(
936 &self,
937 session_id: &str,
938 key: &str,
939 value: &str,
940 ) -> Result<()> {
941 if let Some(mut session) = self.storage.get_session(session_id).await? {
942 session.data.insert(key.to_string(), value.to_string());
943 session.last_accessed = SystemTime::now();
944 self.storage.update_session(&session).await?;
945 }
946 Ok(())
947 }
948
949 fn generate_session_id(&self) -> String {
951 format!("sess_{}", uuid::Uuid::new_v4())
952 }
953
954 fn should_rotate_session(&self, session: &Session) -> bool {
956 if !self.config.rotate_periodically {
957 return false;
958 }
959
960 let session_age = SystemTime::now()
961 .duration_since(session.created_at)
962 .unwrap_or_default();
963
964 session_age > self.config.rotation_interval
965 }
966
967 async fn get_user_session_history(&self, user_id: &str) -> Result<Vec<Session>> {
969 self.storage.get_user_sessions(user_id).await
972 }
973}
974
975pub struct DeviceFingerprintGenerator;
980
981impl Default for DeviceFingerprintGenerator {
982 fn default() -> Self {
983 Self::new()
984 }
985}
986
987impl DeviceFingerprintGenerator {
988 pub fn new() -> Self {
989 Self
990 }
991
992 pub fn generate_fingerprint(&self, metadata: &RequestMetadata) -> String {
994 let mut fingerprint_data = Vec::new();
995
996 if let Some(ua) = &metadata.user_agent {
997 fingerprint_data.push(ua.clone());
998 }
999
1000 self.add_advanced_fingerprinting_data(&mut fingerprint_data, metadata);
1002
1003 let fingerprint_string = fingerprint_data.join("|");
1004 format!("fp_{:x}", crc32fast::hash(fingerprint_string.as_bytes()))
1005 }
1006
1007 fn add_advanced_fingerprinting_data(
1009 &self,
1010 fingerprint_data: &mut Vec<String>,
1011 metadata: &RequestMetadata,
1012 ) {
1013 if let Some(ref ip) = metadata.ip_address {
1015 fingerprint_data.push(format!("geo:{}", self.get_ip_geolocation(ip)));
1017 }
1018
1019 fingerprint_data.push(format!("lang:{}", self.get_system_language()));
1021 fingerprint_data.push(format!("tz:{}", self.get_timezone_offset()));
1022 fingerprint_data.push(format!("hw:{}", self.get_hardware_concurrency()));
1023
1024 fingerprint_data.push(format!("conn:{}", self.get_connection_info()));
1026
1027 fingerprint_data.push(format!("caps:{}", self.get_client_capabilities()));
1029 }
1030
1031 fn get_ip_geolocation(&self, ip: &str) -> String {
1033 use std::net::IpAddr;
1034 use std::str::FromStr;
1035
1036 if let Ok(ip_addr) = IpAddr::from_str(ip) {
1038 match ip_addr {
1039 IpAddr::V4(ipv4) => {
1040 let octets = ipv4.octets();
1041
1042 if (octets[0] == 10)
1044 || (octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31)
1045 || (octets[0] == 192 && octets[1] == 168)
1046 {
1047 return "private_rfc1918".to_string();
1048 }
1049
1050 if octets[0] == 127 {
1052 return "loopback".to_string();
1053 }
1054
1055 if octets[0] == 169 && octets[1] == 254 {
1057 return "link_local".to_string();
1058 }
1059
1060 if octets[0] >= 224 && octets[0] <= 239 {
1062 return "multicast".to_string();
1063 }
1064
1065 match (octets[0], octets[1], octets[2], octets[3]) {
1067 (8, 8, 8, 8) | (8, 8, 4, 4) => "google_dns".to_string(),
1068 (1, 1, 1, 1) | (1, 0, 0, 1) => "cloudflare_dns".to_string(),
1069 (208, 67, 222, 222) | (208, 67, 220, 220) => "opendns".to_string(),
1070 _ => {
1071 self.lookup_maxmind_geolocation(&ipv4).unwrap_or_else(|| {
1073 match octets[0] {
1075 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),
1082 }
1083 })
1084 }
1085 }
1086 }
1087 IpAddr::V6(ipv6) => {
1088 let segments = ipv6.segments();
1089
1090 if ipv6.is_loopback() {
1092 return "ipv6_loopback".to_string();
1093 }
1094
1095 if segments[0] & 0xffc0 == 0xfe80 {
1097 return "ipv6_link_local".to_string();
1098 }
1099
1100 if segments[0] & 0xfe00 == 0xfc00 {
1102 return "ipv6_unique_local".to_string();
1103 }
1104
1105 if segments[0] & 0xff00 == 0xff00 {
1107 return "ipv6_multicast".to_string();
1108 }
1109
1110 format!("ipv6_global_{:x}", segments[0] / 0x1000)
1112 }
1113 }
1114 } else {
1115 "invalid_ip".to_string()
1116 }
1117 }
1118
1119 fn get_system_language(&self) -> String {
1121 "en-US".to_string()
1123 }
1124
1125 fn get_timezone_offset(&self) -> String {
1127 "-05:00".to_string() }
1130
1131 fn get_hardware_concurrency(&self) -> String {
1133 "4".to_string()
1135 }
1136
1137 fn get_connection_info(&self) -> String {
1139 "wifi".to_string()
1141 }
1142
1143 fn get_client_capabilities(&self) -> String {
1145 "webgl2_canvas_audio".to_string()
1147 }
1148
1149 fn lookup_maxmind_geolocation(&self, ip: &std::net::Ipv4Addr) -> Option<String> {
1151 let db_path =
1153 std::env::var("MAXMIND_DB_PATH").unwrap_or_else(|_| "GeoLite2-City.mmdb".to_string());
1154 self.lookup_maxmind_geolocation_at(&db_path, ip)
1155 }
1156
1157 fn lookup_maxmind_geolocation_at(
1159 &self,
1160 db_path: &str,
1161 ip: &std::net::Ipv4Addr,
1162 ) -> Option<String> {
1163 use std::path::Path;
1164
1165 if !Path::new(&db_path).exists() {
1166 tracing::warn!(
1167 "MaxMind database not found at {}, falling back to basic geolocation",
1168 db_path
1169 );
1170 return None;
1171 }
1172
1173 match maxminddb::Reader::open_readfile(db_path) {
1174 Ok(reader) => {
1175 match reader.lookup((*ip).into()) {
1176 Ok(result) => match result.decode::<maxminddb::geoip2::City>() {
1177 Ok(Some(city)) => {
1178 let mut location_parts = Vec::new();
1179
1180 let location = &city.location;
1182 if let (Some(lat), Some(lon)) = (location.latitude, location.longitude)
1183 {
1184 location_parts.push(format!("coords:{:.4},{:.4}", lat, lon));
1185 }
1186
1187 if location_parts.is_empty() {
1190 None
1191 } else {
1192 Some(location_parts.join("|"))
1193 }
1194 }
1195 Ok(None) => {
1196 tracing::debug!("MaxMind lookup returned no data for {}", ip);
1197 None
1198 }
1199 Err(e) => {
1200 tracing::debug!("MaxMind decode failed for {}: {}", ip, e);
1201 None
1202 }
1203 },
1204 Err(e) => {
1205 tracing::debug!("MaxMind lookup failed for {}: {}", ip, e);
1206 None
1207 }
1208 }
1209 }
1210 Err(e) => {
1211 tracing::warn!("Failed to open MaxMind database: {}", e);
1212 None
1213 }
1214 }
1215 }
1216}
1217
1218pub struct RiskCalculator;
1224
1225impl Default for RiskCalculator {
1226 fn default() -> Self {
1227 Self::new()
1228 }
1229}
1230
1231impl RiskCalculator {
1232 pub fn new() -> Self {
1233 Self
1234 }
1235
1236 pub fn calculate_risk(
1238 &self,
1239 device_info: &DeviceInfo,
1240 metadata: &RequestMetadata,
1241 _session_history: &[Session],
1242 threat_intel_manager: Option<&ThreatFeedManager>,
1243 ) -> u8 {
1244 let mut risk_score = 0u8;
1245
1246 if !device_info.is_trusted {
1248 risk_score += 20;
1249 }
1250
1251 if let Some(ip) = &metadata.ip_address
1253 && self.is_suspicious_ip(ip, threat_intel_manager)
1254 {
1255 risk_score += 30;
1256 }
1257
1258 if let Some(location) = &metadata.geolocation {
1260 let mut geo_risk = 0;
1261
1262 if let Some(country) = &location.country {
1264 let country_lower = country.to_lowercase();
1265
1266 let high_risk_countries =
1268 ["tor", "anonymous", "vpn", "proxy", "hosting", "datacenter"];
1269
1270 for indicator in &high_risk_countries {
1271 if country_lower.contains(indicator) {
1272 geo_risk += 30;
1273 break;
1274 }
1275 }
1276
1277 geo_risk += self.assess_country_threat_level(&country_lower) as u8;
1279
1280 let elevated_risk_patterns = ["cloud", "aws", "azure", "gcp"];
1282 for pattern in &elevated_risk_patterns {
1283 if country_lower.contains(pattern) {
1284 geo_risk += 20;
1285 break;
1286 }
1287 }
1288 }
1289
1290 if let (Some(lat), Some(lon)) = (location.latitude, location.longitude) {
1292 if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
1294 geo_risk += 25; }
1296
1297 if (lat * 100.0).fract().abs() < 0.01 && (lon * 100.0).fract().abs() < 0.01 {
1299 geo_risk += 15; }
1301 }
1302
1303 if let Some(region) = &location.region {
1305 let region_lower = region.to_lowercase();
1306 if region_lower.contains("hosting") || region_lower.contains("datacenter") {
1307 geo_risk += 20;
1308 }
1309 }
1310
1311 if let Some(city) = &location.city {
1313 let city_lower = city.to_lowercase();
1314 if city_lower.contains("server") || city_lower.contains("datacenter") {
1315 geo_risk += 15;
1316 }
1317 }
1318
1319 risk_score += geo_risk;
1320 }
1321
1322 risk_score.min(100)
1328 }
1329
1330 fn is_suspicious_ip(&self, ip: &str, threat_intel_manager: Option<&ThreatFeedManager>) -> bool {
1332 use std::net::IpAddr;
1333 use std::str::FromStr;
1334
1335 if let Ok(ip_addr) = IpAddr::from_str(ip) {
1337 match ip_addr {
1338 IpAddr::V4(ipv4) => {
1339 let octets = ipv4.octets();
1340
1341 if self.check_malicious_ip_feeds(&ipv4, threat_intel_manager) {
1343 return true;
1344 }
1345
1346 let suspicious_ranges = [
1348 (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), ];
1356
1357 for (net, _, _, _, _) in &suspicious_ranges {
1358 if octets[0] == *net {
1359 return true;
1360 }
1361 }
1362
1363 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)
1369 {
1370 return true;
1372 }
1373
1374 if octets[3] == 0 || octets[3] == 255 {
1376 return true;
1377 }
1378
1379 if self.check_proxy_vpn_databases(&ipv4) {
1381 return true;
1382 }
1383
1384 let proxy_ports_in_ip = [
1386 80, 443, 8080, 3128, 1080, 8000, 8888, 9050, ];
1388
1389 for &port in &proxy_ports_in_ip {
1390 if octets[2] == (port / 256) as u8 && octets[3] == (port % 256) as u8 {
1391 return true;
1392 }
1393 }
1394
1395 false
1396 }
1397 IpAddr::V6(ipv6) => {
1398 let segments = ipv6.segments();
1399
1400 if self.check_tor_exit_nodes(&ipv6) {
1402 return true;
1403 }
1404
1405 if segments[0] == 0x2001 && segments[1] == 0x67c {
1407 return true;
1409 }
1410
1411 let mut sequential_count = 0;
1413 for i in 1..segments.len() {
1414 if segments[i] == segments[i - 1] + 1 {
1415 sequential_count += 1;
1416 }
1417 }
1418 if sequential_count >= 4 {
1419 return true;
1421 }
1422
1423 if segments[0] == 0x2001 && segments[1] == 0x470 {
1425 return true;
1427 }
1428
1429 false
1430 }
1431 }
1432 } else {
1433 true }
1435 }
1436
1437 fn assess_country_threat_level(&self, country: &str) -> u32 {
1439 use std::path::Path;
1440
1441 let threat_db_path = std::env::var("COUNTRY_THREAT_DB_PATH")
1443 .unwrap_or_else(|_| "country-threats.csv".to_string());
1444
1445 if Path::new(&threat_db_path).exists() {
1446 if let Ok(contents) = std::fs::read_to_string(&threat_db_path) {
1448 let mut csv_reader = csv::Reader::from_reader(contents.as_bytes());
1449
1450 for result in csv_reader.records() {
1451 if let Ok(record) = result
1452 && record.len() >= 2
1453 {
1454 let threat_country = record[0].to_lowercase();
1455 if let Ok(risk_score) = record[1].parse::<u32>()
1456 && country.contains(&threat_country)
1457 {
1458 tracing::debug!(
1459 "Country threat match: {} -> risk {}",
1460 country,
1461 risk_score
1462 );
1463 return risk_score;
1464 }
1465 }
1466 }
1467 }
1468 }
1469
1470 0 }
1473
1474 fn check_malicious_ip_feeds(
1476 &self,
1477 ip: &std::net::Ipv4Addr,
1478 threat_intel_manager: Option<&ThreatFeedManager>,
1479 ) -> bool {
1480 if let Some(threat_manager) = threat_intel_manager {
1482 return threat_manager.is_malicious_ip(&std::net::IpAddr::V4(*ip));
1483 }
1484
1485 use std::path::Path;
1487
1488 let feed_paths = [
1490 std::env::var("MALICIOUS_IPS_DB_PATH")
1491 .unwrap_or_else(|_| "malicious-ips.txt".to_string()),
1492 std::env::var("BOTNET_IPS_DB_PATH").unwrap_or_else(|_| "botnet-ips.txt".to_string()),
1493 std::env::var("TOR_EXIT_NODES_DB_PATH").unwrap_or_else(|_| "tor-exits.txt".to_string()),
1494 ];
1495
1496 for feed_path in &feed_paths {
1497 if Path::new(feed_path).exists()
1498 && let Ok(contents) = std::fs::read_to_string(feed_path)
1499 {
1500 for line in contents.lines() {
1501 let line = line.trim();
1502 if line.is_empty() || line.starts_with('#') {
1503 continue;
1504 }
1505
1506 if line == ip.to_string() {
1508 tracing::warn!("Malicious IP detected: {} (source: {})", ip, feed_path);
1509 return true;
1510 }
1511
1512 if line.contains('/')
1514 && let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1515 && network.contains(*ip)
1516 {
1517 tracing::warn!(
1518 "Malicious network detected: {} in {} (source: {})",
1519 ip,
1520 network,
1521 feed_path
1522 );
1523 return true;
1524 }
1525 }
1526 }
1527 }
1528
1529 false
1530 }
1531
1532 fn check_proxy_vpn_databases(&self, ip: &std::net::Ipv4Addr) -> bool {
1534 use std::path::Path;
1535
1536 let db_sources = [
1538 ("VPN_DATABASE_PATH", "vpn-ranges.txt"),
1539 ("PROXY_DATABASE_PATH", "proxy-ips.txt"),
1540 ("DATACENTER_DATABASE_PATH", "datacenter-ranges.txt"),
1541 ("HOSTING_DATABASE_PATH", "hosting-providers.txt"),
1542 ];
1543
1544 for (env_var, default_file) in &db_sources {
1545 let db_path = std::env::var(env_var).unwrap_or_else(|_| default_file.to_string());
1546
1547 if Path::new(&db_path).exists()
1548 && let Ok(contents) = std::fs::read_to_string(&db_path)
1549 {
1550 for line in contents.lines() {
1551 let line = line.trim();
1552 if line.is_empty() || line.starts_with('#') {
1553 continue;
1554 }
1555
1556 if line.contains('/') {
1558 if let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1560 && network.contains(*ip)
1561 {
1562 tracing::info!(
1563 "Proxy/VPN detected: {} in {} (source: {})",
1564 ip,
1565 network,
1566 db_path
1567 );
1568 return true;
1569 }
1570 } else if line.contains('-') {
1571 let parts: Vec<&str> = line.split('-').collect();
1573 if parts.len() == 2
1574 && let (Ok(start_ip), Ok(end_ip)) = (
1575 parts[0].trim().parse::<std::net::Ipv4Addr>(),
1576 parts[1].trim().parse::<std::net::Ipv4Addr>(),
1577 )
1578 {
1579 let ip_u32 = u32::from(*ip);
1580 let start_u32 = u32::from(start_ip);
1581 let end_u32 = u32::from(end_ip);
1582
1583 if ip_u32 >= start_u32 && ip_u32 <= end_u32 {
1584 tracing::info!(
1585 "Proxy/VPN range detected: {} in {}-{} (source: {})",
1586 ip,
1587 start_ip,
1588 end_ip,
1589 db_path
1590 );
1591 return true;
1592 }
1593 }
1594 } else if line == ip.to_string() {
1595 tracing::info!("Proxy/VPN exact match: {} (source: {})", ip, db_path);
1597 return true;
1598 }
1599 }
1600 }
1601 }
1602
1603 false
1604 }
1605
1606 fn check_tor_exit_nodes(&self, ip: &std::net::Ipv6Addr) -> bool {
1608 use std::path::Path;
1609
1610 let tor_db_path = std::env::var("TOR_EXIT_NODES_IPV6_PATH")
1612 .unwrap_or_else(|_| "tor-exits-ipv6.txt".to_string());
1613
1614 if Path::new(&tor_db_path).exists()
1615 && let Ok(contents) = std::fs::read_to_string(&tor_db_path)
1616 {
1617 for line in contents.lines() {
1618 let line = line.trim();
1619 if line.is_empty() || line.starts_with('#') {
1620 continue;
1621 }
1622
1623 if let Ok(tor_ip) = line.parse::<std::net::Ipv6Addr>()
1625 && tor_ip == *ip
1626 {
1627 tracing::warn!("Tor exit node detected: {}", ip);
1628 return true;
1629 }
1630
1631 if line.contains('/')
1633 && let Ok(network) = line.parse::<ipnetwork::Ipv6Network>()
1634 && network.contains(*ip)
1635 {
1636 tracing::warn!("Tor exit network detected: {} in {}", ip, network);
1637 return true;
1638 }
1639 }
1640 }
1641
1642 if let Some(ipv4) = ip.to_ipv4() {
1644 let tor_v4_path = std::env::var("TOR_EXIT_NODES_IPV4_PATH")
1645 .unwrap_or_else(|_| "tor-exits-ipv4.txt".to_string());
1646
1647 if Path::new(&tor_v4_path).exists()
1648 && let Ok(contents) = std::fs::read_to_string(&tor_v4_path)
1649 {
1650 for line in contents.lines() {
1651 let line = line.trim();
1652 if line == ipv4.to_string() {
1653 tracing::warn!("Tor exit node detected (IPv4-mapped): {}", ip);
1654 return true;
1655 }
1656 }
1657 }
1658 }
1659
1660 false
1661 }
1662}
1663
1664impl Default for SessionConfig {
1665 fn default() -> Self {
1666 Self {
1667 default_duration: Duration::from_secs(3600), max_duration: Duration::from_secs(86400), idle_timeout: Duration::from_secs(1800), rotate_on_privilege_escalation: true,
1671 rotate_periodically: true,
1672 rotation_interval: Duration::from_secs(1800), max_concurrent_sessions: Some(5),
1674 track_device_fingerprints: true,
1675 enforce_geographic_restrictions: false,
1676 allowed_countries: vec![],
1677 security_policy: SessionSecurityPolicy::default(),
1678 }
1679 }
1680}
1681
1682impl Default for SessionSecurityPolicy {
1683 fn default() -> Self {
1684 Self {
1685 require_mfa_for_new_devices: true,
1686 require_reauth_for_sensitive_ops: true,
1687 reauth_timeout: Duration::from_secs(300), max_risk_score: 70,
1689 auto_suspend_suspicious: true,
1690 verify_location_changes: true,
1691 limit_concurrent_sessions: true,
1692 }
1693 }
1694}
1695
1696#[cfg(test)]
1697mod tests {
1698 use super::*;
1699
1700 #[test]
1701 fn test_device_fingerprint_generation() {
1702 let generator = DeviceFingerprintGenerator::new();
1703 let metadata = RequestMetadata {
1704 user_agent: Some("Mozilla/5.0".to_string()),
1705 ..Default::default()
1706 };
1707
1708 let fp1 = generator.generate_fingerprint(&metadata);
1709 let fp2 = generator.generate_fingerprint(&metadata);
1710
1711 assert_eq!(fp1, fp2);
1712 assert!(fp1.starts_with("fp_"));
1713 }
1714
1715 #[test]
1716 fn test_risk_calculation() {
1717 let calculator = RiskCalculator::new();
1718 let device_info = DeviceInfo {
1719 fingerprint: "test".to_string(),
1720 device_type: "desktop".to_string(),
1721 operating_system: None,
1722 browser: None,
1723 screen_resolution: None,
1724 timezone: None,
1725 language: None,
1726 is_trusted: false,
1727 device_name: None,
1728 is_mobile: false,
1729 ip_address: None,
1730 };
1731
1732 let metadata = RequestMetadata::default();
1733 let history = vec![];
1734
1735 let risk = calculator.calculate_risk(&device_info, &metadata, &history, None);
1736 assert!(risk >= 20); }
1738
1739 #[derive(Default)]
1741 struct TestSessionStorage {
1742 sessions: std::sync::Mutex<std::collections::HashMap<String, Session>>,
1743 }
1744
1745 #[async_trait::async_trait]
1746 impl SessionStorage for TestSessionStorage {
1747 async fn create_session(&self, session: &Session) -> Result<()> {
1748 self.sessions
1749 .lock()
1750 .unwrap()
1751 .insert(session.id.clone(), session.clone());
1752 Ok(())
1753 }
1754 async fn get_session(&self, id: &str) -> Result<Option<Session>> {
1755 Ok(self.sessions.lock().unwrap().get(id).cloned())
1756 }
1757 async fn update_session(&self, session: &Session) -> Result<()> {
1758 self.create_session(session).await
1759 }
1760 async fn delete_session(&self, id: &str) -> Result<()> {
1761 self.sessions.lock().unwrap().remove(id);
1762 Ok(())
1763 }
1764 async fn get_user_sessions(&self, user_id: &str) -> Result<Vec<Session>> {
1765 Ok(self
1766 .sessions
1767 .lock()
1768 .unwrap()
1769 .values()
1770 .filter(|s| s.user_id == user_id)
1771 .cloned()
1772 .collect())
1773 }
1774 async fn count_active_sessions(&self, _user_id: &str) -> Result<u32> {
1775 Ok(0)
1776 }
1777 async fn cleanup_expired_sessions(&self) -> Result<u32> {
1778 Ok(0)
1779 }
1780 async fn find_sessions_by_device(&self, _fp: &str) -> Result<Vec<Session>> {
1781 Ok(vec![])
1782 }
1783 async fn find_sessions_by_ip(&self, _ip: &str) -> Result<Vec<Session>> {
1784 Ok(vec![])
1785 }
1786 }
1787
1788 #[tokio::test]
1789 async fn revoke_all_user_sessions_ends_every_live_session_whatever_its_state() {
1790 use crate::audit::{AuditLogger, TracingAuditStorage};
1791 let manager = SessionManager::new(
1792 TestSessionStorage::default(),
1793 SessionConfigBuilder::for_web_app().build(),
1794 AuditLogger::new(TracingAuditStorage),
1795 );
1796 let live_states = [
1797 SessionState::Active,
1798 SessionState::Suspended,
1799 SessionState::RequiresMfa,
1800 SessionState::RequiresReauth,
1801 SessionState::RequiresRotation,
1802 SessionState::HighRisk,
1803 ];
1804 let mut ids = Vec::new();
1805 for state in live_states.iter().cloned() {
1806 let mut s = Session::new("victim", Duration::from_secs(3600));
1807 s.state = state;
1808 manager.storage.create_session(&s).await.unwrap();
1809 ids.push(s.id);
1810 }
1811 let mut expired = Session::new("victim", Duration::from_secs(3600));
1813 expired.state = SessionState::Expired;
1814 manager.storage.create_session(&expired).await.unwrap();
1815 let other = Session::new("someone-else", Duration::from_secs(3600));
1816 manager.storage.create_session(&other).await.unwrap();
1817
1818 let revoked = manager.revoke_all_user_sessions("victim").await.unwrap();
1819 assert_eq!(revoked as usize, live_states.len());
1820 for (id, state) in ids.iter().zip(live_states.iter()) {
1821 let after = manager.storage.get_session(id).await.unwrap().unwrap();
1822 assert_eq!(after.state, SessionState::Revoked, "was {state:?}");
1823 }
1824 let expired_after = manager
1825 .storage
1826 .get_session(&expired.id)
1827 .await
1828 .unwrap()
1829 .unwrap();
1830 assert_eq!(expired_after.state, SessionState::Expired);
1831 let other_after = manager
1832 .storage
1833 .get_session(&other.id)
1834 .await
1835 .unwrap()
1836 .unwrap();
1837 assert_eq!(other_after.state, SessionState::Active);
1838 }
1839
1840 #[test]
1841 fn test_session_config_builder_for_web_app() {
1842 let config = SessionConfigBuilder::for_web_app().build();
1843 assert_eq!(config.default_duration, Duration::from_secs(3600));
1844 assert_eq!(config.max_duration, Duration::from_secs(86400));
1845 assert_eq!(config.max_concurrent_sessions, Some(5));
1846 assert!(config.track_device_fingerprints);
1847 }
1848
1849 #[test]
1850 fn test_session_config_builder_for_api_service() {
1851 let config = SessionConfigBuilder::for_api_service().build();
1852 assert_eq!(config.default_duration, Duration::from_secs(900));
1853 assert!(config.max_concurrent_sessions.is_none());
1854 assert!(!config.track_device_fingerprints);
1855 assert!(!config.rotate_periodically);
1856 }
1857
1858 #[test]
1859 fn test_session_config_builder_for_high_security() {
1860 let config = SessionConfigBuilder::for_high_security()
1861 .allowed_countries(vec!["US".into()])
1862 .build();
1863 assert_eq!(config.default_duration, Duration::from_secs(1800));
1864 assert_eq!(config.max_concurrent_sessions, Some(1));
1865 assert!(config.enforce_geographic_restrictions);
1866 assert_eq!(config.allowed_countries, vec!["US".to_string()]);
1867 assert!(config.security_policy.require_mfa_for_new_devices);
1868 }
1869
1870 #[test]
1874 fn maxmind_geolocation_none_for_missing_or_garbage_database() {
1875 let generator = DeviceFingerprintGenerator::new();
1876 let ip = std::net::Ipv4Addr::new(8, 8, 8, 8);
1877 let dir = tempfile::tempdir().unwrap();
1878
1879 let missing = dir.path().join("missing.mmdb");
1880 assert_eq!(
1881 generator.lookup_maxmind_geolocation_at(missing.to_str().unwrap(), &ip),
1882 None
1883 );
1884
1885 let garbage_inputs: [(&str, &[u8]); 3] = [
1886 ("empty.mmdb", b""),
1887 ("garbage.mmdb", b"this is not a MaxMind database at all"),
1888 ("truncated.mmdb", b"\xAB\xCD\xEFMaxMind.com\x00"),
1889 ];
1890 for (name, bytes) in garbage_inputs {
1891 let path = dir.path().join(name);
1892 std::fs::write(&path, bytes).unwrap();
1893 assert!(
1895 maxminddb::Reader::open_readfile(&path).is_err(),
1896 "{name}: maxminddb accepted garbage bytes"
1897 );
1898 assert_eq!(
1899 generator.lookup_maxmind_geolocation_at(path.to_str().unwrap(), &ip),
1900 None,
1901 "{name}"
1902 );
1903 }
1904 }
1905}