Skip to main content

auth_framework/session/
manager.rs

1//! Comprehensive session management with security hardening.
2//!
3//! This module provides secure session management with features like
4//! session rotation, concurrent session limits, device tracking,
5//! and advanced security protections.
6
7use 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// Additional imports for session security
16
17/// Session information
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct Session {
20    /// Unique session ID
21    pub id: String,
22    /// User ID this session belongs to
23    pub user_id: String,
24    /// When the session was created
25    pub created_at: SystemTime,
26    /// When the session was last accessed
27    pub last_accessed: SystemTime,
28    /// When the session expires
29    pub expires_at: SystemTime,
30    /// Session state
31    pub state: SessionState,
32    /// Device information
33    pub device_info: DeviceInfo,
34    /// Security metadata
35    pub security_metadata: SecurityMetadata,
36    /// Session data (custom application data)
37    pub data: HashMap<String, String>,
38    /// MFA verification status
39    pub mfa_verified: bool,
40    /// Permissions cache (for performance)
41    pub cached_permissions: Option<Vec<String>>,
42    /// Last activity details
43    pub last_activity: ActivityInfo,
44}
45
46impl Session {
47    /// Create a new active session for the given user with sensible defaults.
48    ///
49    /// Sets `created_at` / `last_accessed` to *now*, `state` to [`SessionState::Active`],
50    /// and all optional fields to empty / default values.
51    ///
52    /// # Example
53    ///
54    /// ```rust,ignore
55    /// use auth_framework::session::Session;
56    /// use std::time::{Duration, SystemTime};
57    ///
58    /// let session = Session::new("user-123", Duration::from_secs(3600));
59    /// assert_eq!(session.user_id, "user-123");
60    /// assert_eq!(session.state, SessionState::Active);
61    /// ```
62    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/// Session state
87#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
88pub enum SessionState {
89    Active,
90    Expired,
91    Revoked,
92    Suspended,
93    RequiresMfa,
94    RequiresReauth,
95    /// Session credentials need to be rotated (from `security::SecureSession`)
96    RequiresRotation,
97    /// Session is considered high-risk and may need step-up authentication
98    HighRisk,
99}
100
101/// Device information for session tracking
102#[derive(Debug, Clone, Serialize, Deserialize)]
103pub struct DeviceInfo {
104    /// Device fingerprint (unique identifier)
105    pub fingerprint: String,
106    /// Device type (mobile, desktop, tablet, etc.)
107    pub device_type: String,
108    /// Operating system
109    pub operating_system: Option<String>,
110    /// Browser information
111    pub browser: Option<String>,
112    /// Screen resolution
113    pub screen_resolution: Option<String>,
114    /// Timezone
115    pub timezone: Option<String>,
116    /// Language preferences
117    pub language: Option<String>,
118    /// Whether this is a trusted device
119    pub is_trusted: bool,
120    /// Device name (user-assigned)
121    pub device_name: Option<String>,
122    /// Whether device is a mobile device
123    pub is_mobile: bool,
124    /// IP address associated with this device
125    pub ip_address: Option<String>,
126}
127
128impl DeviceInfo {
129    /// A placeholder for when device info is unknown.
130    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/// Security metadata for sessions
148#[derive(Debug, Clone, Serialize, Deserialize, Default)]
149pub struct SecurityMetadata {
150    /// IP address when session was created
151    pub creation_ip: String,
152    /// Current IP address
153    pub current_ip: String,
154    /// Geographic location when created
155    pub creation_location: Option<GeolocationInfo>,
156    /// Current geographic location
157    pub current_location: Option<GeolocationInfo>,
158    /// Security flags
159    pub security_flags: Vec<SecurityFlag>,
160    /// Risk score (0-100)
161    pub risk_score: u8,
162    /// Whether location has changed
163    pub location_changed: bool,
164    /// Whether IP has changed
165    pub ip_changed: bool,
166    /// Number of failed authentication attempts
167    pub failed_auth_attempts: u32,
168}
169
170/// Security flags for sessions
171#[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/// Activity information
184#[derive(Debug, Clone, Serialize, Deserialize)]
185pub struct ActivityInfo {
186    /// Last endpoint accessed
187    pub endpoint: Option<String>,
188    /// Last action performed
189    pub action: Option<String>,
190    /// Request metadata
191    pub request_metadata: Option<RequestMetadata>,
192    /// Activity timestamp
193    pub timestamp: SystemTime,
194}
195
196/// Session configuration
197#[derive(Debug, Clone)]
198pub struct SessionConfig {
199    /// Default session duration
200    pub default_duration: Duration,
201    /// Maximum session duration
202    pub max_duration: Duration,
203    /// Session idle timeout
204    pub idle_timeout: Duration,
205    /// Whether to rotate session IDs on privilege escalation
206    pub rotate_on_privilege_escalation: bool,
207    /// Whether to rotate session IDs periodically
208    pub rotate_periodically: bool,
209    /// Rotation interval
210    pub rotation_interval: Duration,
211    /// Maximum concurrent sessions per user
212    pub max_concurrent_sessions: Option<u32>,
213    /// Whether to track device fingerprints
214    pub track_device_fingerprints: bool,
215    /// Whether to enforce geographic restrictions
216    pub enforce_geographic_restrictions: bool,
217    /// Allowed countries (if geographic restrictions enabled)
218    pub allowed_countries: Vec<String>,
219    /// Security policy
220    pub security_policy: SessionSecurityPolicy,
221}
222
223/// Session security policy
224impl SessionConfig {
225    /// Create a new builder for SessionConfig
226    pub fn builder() -> SessionConfigBuilder {
227        SessionConfigBuilder::default()
228    }
229}
230
231/// A builder for SessionConfig
232#[derive(Default)]
233pub struct SessionConfigBuilder {
234    config: SessionConfig,
235}
236
237impl SessionConfigBuilder {
238    /// Set the default session duration.
239    ///
240    /// # Example
241    /// ```rust,ignore
242    /// use std::time::Duration;
243    /// let config = SessionConfigBuilder::default()
244    ///     .default_duration(Duration::from_secs(3600))
245    ///     .build();
246    /// ```
247    pub fn default_duration(mut self, duration: std::time::Duration) -> Self {
248        self.config.default_duration = duration;
249        self
250    }
251
252    /// Set the maximum session duration.
253    ///
254    /// # Example
255    /// ```rust,ignore
256    /// let config = SessionConfigBuilder::default()
257    ///     .max_duration(Duration::from_secs(86400))
258    ///     .build();
259    /// ```
260    pub fn max_duration(mut self, duration: std::time::Duration) -> Self {
261        self.config.max_duration = duration;
262        self
263    }
264
265    /// Set the session idle timeout.
266    ///
267    /// # Example
268    /// ```rust,ignore
269    /// let config = SessionConfigBuilder::default()
270    ///     .idle_timeout(Duration::from_secs(900))
271    ///     .build();
272    /// ```
273    pub fn idle_timeout(mut self, timeout: std::time::Duration) -> Self {
274        self.config.idle_timeout = timeout;
275        self
276    }
277
278    /// Set whether to rotate session IDs on privilege escalation.
279    ///
280    /// # Example
281    /// ```rust,ignore
282    /// let config = SessionConfigBuilder::default()
283    ///     .rotate_on_privilege_escalation(true)
284    ///     .build();
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    /// Set whether to rotate session IDs periodically.
292    ///
293    /// # Example
294    /// ```rust,ignore
295    /// let config = SessionConfigBuilder::default()
296    ///     .rotate_periodically(true)
297    ///     .rotation_interval(Duration::from_secs(3600))
298    ///     .build();
299    /// ```
300    pub fn rotate_periodically(mut self, rotate: bool) -> Self {
301        self.config.rotate_periodically = rotate;
302        self
303    }
304
305    /// Set the rotation interval.
306    ///
307    /// # Example
308    /// ```rust,ignore
309    /// let config = SessionConfigBuilder::default()
310    ///     .rotate_periodically(true)
311    ///     .rotation_interval(Duration::from_secs(1800))
312    ///     .build();
313    /// ```
314    pub fn rotation_interval(mut self, interval: std::time::Duration) -> Self {
315        self.config.rotation_interval = interval;
316        self
317    }
318
319    /// Set the maximum concurrent sessions per user.
320    ///
321    /// # Example
322    /// ```rust,ignore
323    /// let config = SessionConfigBuilder::default()
324    ///     .max_concurrent_sessions(5)
325    ///     .build();
326    /// ```
327    pub fn max_concurrent_sessions(mut self, max: u32) -> Self {
328        self.config.max_concurrent_sessions = Some(max);
329        self
330    }
331
332    /// Set the list of allowed countries (ISO 3166-1 alpha-2 codes).
333    ///
334    /// Only meaningful when `enforce_geographic_restrictions` is enabled
335    /// (e.g. via [`for_high_security()`](Self::for_high_security)).
336    pub fn allowed_countries(mut self, countries: Vec<String>) -> Self {
337        self.config.allowed_countries = countries;
338        self
339    }
340
341    /// Preset for typical web applications.
342    ///
343    /// 1-hour default sessions, 24-hour max, 30-minute idle, 5 concurrent.
344    ///
345    /// # Example
346    /// ```rust,ignore
347    /// let config = SessionConfigBuilder::for_web_app().build();
348    /// ```
349    pub fn for_web_app() -> Self {
350        Self {
351            config: SessionConfig {
352                default_duration: Duration::from_secs(3600), // 1 hour
353                max_duration: Duration::from_secs(86400),    // 24 hours
354                idle_timeout: Duration::from_secs(1800),     // 30 minutes
355                rotate_on_privilege_escalation: true,
356                rotate_periodically: true,
357                rotation_interval: Duration::from_secs(1800), // 30 minutes
358                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    /// Preset for stateless API services.
368    ///
369    /// Short-lived sessions (15-min default, 1-hour max, 10-min idle),
370    /// no rotation, no fingerprinting — optimised for machine-to-machine
371    /// or single-page-app API calls.
372    ///
373    /// # Example
374    /// ```rust,ignore
375    /// let config = SessionConfigBuilder::for_api_service().build();
376    /// ```
377    pub fn for_api_service() -> Self {
378        Self {
379            config: SessionConfig {
380                default_duration: Duration::from_secs(900), // 15 minutes
381                max_duration: Duration::from_secs(3600),    // 1 hour
382                idle_timeout: Duration::from_secs(600),     // 10 minutes
383                rotate_on_privilege_escalation: true,
384                rotate_periodically: false,
385                rotation_interval: Duration::from_secs(3600),
386                max_concurrent_sessions: None, // unlimited
387                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    /// Preset for high-security environments (finance, healthcare).
404    ///
405    /// 30-minute sessions, 5-minute idle, aggressive rotation, single
406    /// concurrent session, MFA enforced on every new device.
407    ///
408    /// # Example
409    /// ```rust,ignore
410    /// let config = SessionConfigBuilder::for_high_security().build();
411    /// ```
412    pub fn for_high_security() -> Self {
413        Self {
414            config: SessionConfig {
415                default_duration: Duration::from_secs(1800), // 30 minutes
416                max_duration: Duration::from_secs(7200),     // 2 hours
417                idle_timeout: Duration::from_secs(300),      // 5 minutes
418                rotate_on_privilege_escalation: true,
419                rotate_periodically: true,
420                rotation_interval: Duration::from_secs(900), // 15 minutes
421                max_concurrent_sessions: Some(1),
422                track_device_fingerprints: true,
423                enforce_geographic_restrictions: true,
424                allowed_countries: vec![], // caller must set
425                security_policy: SessionSecurityPolicy {
426                    require_mfa_for_new_devices: true,
427                    require_reauth_for_sensitive_ops: true,
428                    reauth_timeout: Duration::from_secs(120), // 2 minutes
429                    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    /// Build the [`SessionConfig`].
439    ///
440    /// # Example
441    /// ```rust,ignore
442    /// let config = SessionConfigBuilder::default()
443    ///     .default_duration(Duration::from_secs(7200))
444    ///     .max_concurrent_sessions(3)
445    ///     .build();
446    /// ```
447    pub fn build(self) -> SessionConfig {
448        self.config
449    }
450}
451
452#[derive(Debug, Clone)]
453pub struct SessionSecurityPolicy {
454    /// Require MFA for new devices
455    pub require_mfa_for_new_devices: bool,
456    /// Require re-auth for sensitive operations
457    pub require_reauth_for_sensitive_ops: bool,
458    /// Timeout for re-auth requirement
459    pub reauth_timeout: Duration,
460    /// Maximum risk score allowed
461    pub max_risk_score: u8,
462    /// Whether to auto-suspend suspicious sessions
463    pub auto_suspend_suspicious: bool,
464    /// Whether to require verification after location change
465    pub verify_location_changes: bool,
466    /// Whether to limit concurrent sessions
467    pub limit_concurrent_sessions: bool,
468}
469
470/// Session storage trait
471#[async_trait]
472pub trait SessionStorage: Send + Sync {
473    /// Create a new session
474    async fn create_session(&self, session: &Session) -> Result<()>;
475
476    /// Get session by ID
477    async fn get_session(&self, session_id: &str) -> Result<Option<Session>>;
478
479    /// Update existing session
480    async fn update_session(&self, session: &Session) -> Result<()>;
481
482    /// Delete session
483    async fn delete_session(&self, session_id: &str) -> Result<()>;
484
485    /// Get all sessions for a user
486    async fn get_user_sessions(&self, user_id: &str) -> Result<Vec<Session>>;
487
488    /// Get active sessions count for a user
489    async fn count_active_sessions(&self, user_id: &str) -> Result<u32>;
490
491    /// Clean up expired sessions
492    async fn cleanup_expired_sessions(&self) -> Result<u32>;
493
494    /// Find sessions by device fingerprint
495    async fn find_sessions_by_device(&self, device_fingerprint: &str) -> Result<Vec<Session>>;
496
497    /// Find sessions by IP address
498    async fn find_sessions_by_ip(&self, ip_address: &str) -> Result<Vec<Session>>;
499}
500
501/// Main session manager
502pub 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    /// Create a new session manager.
513    ///
514    /// The `storage` backend persists session data, `config` specifies lifetimes
515    /// and security policies, and `audit_logger` records session lifecycle events.
516    pub fn new(storage: S, config: SessionConfig, audit_logger: AuditLogger<A>) -> Self {
517        // Initialize automated threat intelligence if enabled
518        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                            // Start automated feed management in background
531                            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    /// Create a new session
576    pub async fn create_session(
577        &self,
578        user_id: &str,
579        mut device_info: DeviceInfo,
580        metadata: RequestMetadata,
581    ) -> Result<Session> {
582        // Generate device fingerprint if not already present
583        if device_info.fingerprint.is_empty() {
584            device_info.fingerprint = self.fingerprint_generator.generate_fingerprint(&metadata);
585        }
586
587        // Check concurrent session limits
588        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        // Calculate risk score
599        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        // Check if this is a new device
612        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        // Log session creation
659        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    /// Validate and refresh a session
685    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        // Check absolute maximum session lifetime
698        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        // Check if session is expired
707        if session.expires_at <= now {
708            session.state = SessionState::Expired;
709            self.storage.update_session(&session).await?;
710            return Ok(None);
711        }
712
713        // Validate device fingerprint for security
714        let current_fingerprint = self.fingerprint_generator.generate_fingerprint(&metadata);
715        if current_fingerprint != session.device_info.fingerprint {
716            // Device fingerprint mismatch - potential session hijacking
717            session.state = SessionState::RequiresMfa;
718            self.storage.update_session(&session).await?;
719
720            // Log security event
721            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        // Check if session is idle too long
735        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        // Check session state
745        match session.state {
746            SessionState::Expired | SessionState::Revoked | SessionState::Suspended => {
747                return Ok(None);
748            }
749            SessionState::RequiresMfa | SessionState::RequiresReauth => {
750                // Return session but caller needs to handle MFA/reauth
751                return Ok(Some(session));
752            }
753            SessionState::Active | SessionState::RequiresRotation | SessionState::HighRisk => {}
754        }
755
756        // Update security metadata
757        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            // Check if location verification is required
765            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        // Update last accessed time and activity
775        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        // Check if session rotation is needed
784        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            // Delete old session and create new one
791            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    /// Revoke a session
801    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            // Log session revocation
807            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    /// Revoke all sessions for a user
825    pub async fn revoke_all_user_sessions(&self, user_id: &str) -> Result<u32> {
826        let sessions = self.storage.get_user_sessions(user_id).await?;
827        let mut revoked_count = 0;
828
829        for mut session in sessions {
830            if session.state == SessionState::Active {
831                session.state = SessionState::Revoked;
832                self.storage.update_session(&session).await?;
833                revoked_count += 1;
834            }
835        }
836
837        Ok(revoked_count)
838    }
839
840    /// List sessions for a user.
841    ///
842    /// When `include_inactive` is `false`, only [`SessionState::Active`]
843    /// sessions are returned.
844    ///
845    /// Prefer [`list_user_sessions`](Self::list_user_sessions) with a
846    /// [`SessionFilter`](crate::auth_operations::SessionFilter) for
847    /// self-documenting call sites.
848    pub async fn get_user_sessions(
849        &self,
850        user_id: &str,
851        include_inactive: bool,
852    ) -> Result<Vec<Session>> {
853        let mut sessions = self.storage.get_user_sessions(user_id).await?;
854
855        if !include_inactive {
856            sessions.retain(|s| s.state == SessionState::Active);
857        }
858
859        Ok(sessions)
860    }
861
862    /// List sessions for a user with a typed [`SessionFilter`](crate::auth_operations::SessionFilter).
863    ///
864    /// ```rust,ignore
865    /// use auth_framework::auth_operations::SessionFilter;
866    ///
867    /// let active = mgr.list_user_sessions(user_id, SessionFilter::ActiveOnly).await?;
868    /// ```
869    pub async fn list_user_sessions(
870        &self,
871        user_id: &str,
872        filter: crate::auth_operations::SessionFilter,
873    ) -> Result<Vec<Session>> {
874        self.get_user_sessions(user_id, filter.include_inactive())
875            .await
876    }
877
878    /// Remove all expired sessions from storage and return how many were cleaned up.
879    pub async fn cleanup_expired_sessions(&self) -> Result<u32> {
880        self.storage.cleanup_expired_sessions().await
881    }
882
883    /// Compute a device fingerprint from the request metadata (IP, User-Agent, etc.).
884    pub fn generate_device_fingerprint(&self, metadata: &RequestMetadata) -> String {
885        self.fingerprint_generator.generate_fingerprint(metadata)
886    }
887
888    /// Check whether `metadata` produces a fingerprint matching the session's stored value.
889    pub fn validate_device_fingerprint(
890        &self,
891        session: &Session,
892        metadata: &RequestMetadata,
893    ) -> bool {
894        let current_fingerprint = self.fingerprint_generator.generate_fingerprint(metadata);
895        current_fingerprint == session.device_info.fingerprint
896    }
897
898    /// Suspend suspicious sessions
899    pub async fn suspend_session(&self, session_id: &str, reason: &str) -> Result<()> {
900        if let Some(mut session) = self.storage.get_session(session_id).await? {
901            session.state = SessionState::Suspended;
902            session
903                .security_metadata
904                .security_flags
905                .push(SecurityFlag::SuspiciousActivity);
906
907            self.storage.update_session(&session).await?;
908
909            // Log suspension
910            let mut details = HashMap::new();
911            details.insert("suspension_reason".to_string(), reason.to_string());
912
913            self.audit_logger
914                .log_event(
915                    crate::audit::AuditEvent::builder(
916                        crate::audit::AuditEventType::AccountLocked,
917                        format!("Session suspended: {}", reason),
918                    )
919                    .user_id(session.user_id)
920                    .session_id(session_id)
921                    .outcome(crate::audit::EventOutcome::Success)
922                    .risk_level(crate::audit::RiskLevel::High)
923                    .details(details)
924                    .with_actor("system", "security_monitor")
925                    .build(),
926                )
927                .await?;
928        }
929        Ok(())
930    }
931
932    /// Update session data
933    pub async fn update_session_data(
934        &self,
935        session_id: &str,
936        key: &str,
937        value: &str,
938    ) -> Result<()> {
939        if let Some(mut session) = self.storage.get_session(session_id).await? {
940            session.data.insert(key.to_string(), value.to_string());
941            session.last_accessed = SystemTime::now();
942            self.storage.update_session(&session).await?;
943        }
944        Ok(())
945    }
946
947    /// Generate a new session ID
948    fn generate_session_id(&self) -> String {
949        format!("sess_{}", uuid::Uuid::new_v4())
950    }
951
952    /// Check if session should be rotated
953    fn should_rotate_session(&self, session: &Session) -> bool {
954        if !self.config.rotate_periodically {
955            return false;
956        }
957
958        let session_age = SystemTime::now()
959            .duration_since(session.created_at)
960            .unwrap_or_default();
961
962        session_age > self.config.rotation_interval
963    }
964
965    /// Get user session history for risk calculation
966    async fn get_user_session_history(&self, user_id: &str) -> Result<Vec<Session>> {
967        // This would typically be a more sophisticated query
968        // For now, just return recent sessions
969        self.storage.get_user_sessions(user_id).await
970    }
971}
972
973/// Generates device fingerprints for session tracking and anomaly detection.
974///
975/// Fingerprints are derived from user-agent strings and other request metadata
976/// to identify returning devices without storing sensitive client information.
977pub struct DeviceFingerprintGenerator;
978
979impl Default for DeviceFingerprintGenerator {
980    fn default() -> Self {
981        Self::new()
982    }
983}
984
985impl DeviceFingerprintGenerator {
986    pub fn new() -> Self {
987        Self
988    }
989
990    /// Generate device fingerprint from request metadata
991    pub fn generate_fingerprint(&self, metadata: &RequestMetadata) -> String {
992        let mut fingerprint_data = Vec::new();
993
994        if let Some(ua) = &metadata.user_agent {
995            fingerprint_data.push(ua.clone());
996        }
997
998        // Comprehensive device fingerprinting implementation
999        self.add_advanced_fingerprinting_data(&mut fingerprint_data, metadata);
1000
1001        let fingerprint_string = fingerprint_data.join("|");
1002        format!("fp_{:x}", crc32fast::hash(fingerprint_string.as_bytes()))
1003    }
1004
1005    /// Add advanced fingerprinting data based on available metadata
1006    fn add_advanced_fingerprinting_data(
1007        &self,
1008        fingerprint_data: &mut Vec<String>,
1009        metadata: &RequestMetadata,
1010    ) {
1011        // Screen characteristics (if available)
1012        if let Some(ref ip) = metadata.ip_address {
1013            // Extract geographical and ISP information from IP
1014            fingerprint_data.push(format!("geo:{}", self.get_ip_geolocation(ip)));
1015        }
1016
1017        // Browser/client characteristics
1018        fingerprint_data.push(format!("lang:{}", self.get_system_language()));
1019        fingerprint_data.push(format!("tz:{}", self.get_timezone_offset()));
1020        fingerprint_data.push(format!("hw:{}", self.get_hardware_concurrency()));
1021
1022        // Network characteristics
1023        fingerprint_data.push(format!("conn:{}", self.get_connection_info()));
1024
1025        // Additional entropy sources
1026        fingerprint_data.push(format!("caps:{}", self.get_client_capabilities()));
1027    }
1028
1029    /// Get IP geolocation information for fingerprinting
1030    fn get_ip_geolocation(&self, ip: &str) -> String {
1031        use std::net::IpAddr;
1032        use std::str::FromStr;
1033
1034        // Parse IP address for classification
1035        if let Ok(ip_addr) = IpAddr::from_str(ip) {
1036            match ip_addr {
1037                IpAddr::V4(ipv4) => {
1038                    let octets = ipv4.octets();
1039
1040                    // RFC 1918 private networks
1041                    if (octets[0] == 10)
1042                        || (octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31)
1043                        || (octets[0] == 192 && octets[1] == 168)
1044                    {
1045                        return "private_rfc1918".to_string();
1046                    }
1047
1048                    // Loopback
1049                    if octets[0] == 127 {
1050                        return "loopback".to_string();
1051                    }
1052
1053                    // Link-local (169.254.x.x)
1054                    if octets[0] == 169 && octets[1] == 254 {
1055                        return "link_local".to_string();
1056                    }
1057
1058                    // Multicast
1059                    if octets[0] >= 224 && octets[0] <= 239 {
1060                        return "multicast".to_string();
1061                    }
1062
1063                    // Known public DNS servers
1064                    match (octets[0], octets[1], octets[2], octets[3]) {
1065                        (8, 8, 8, 8) | (8, 8, 4, 4) => "google_dns".to_string(),
1066                        (1, 1, 1, 1) | (1, 0, 0, 1) => "cloudflare_dns".to_string(),
1067                        (208, 67, 222, 222) | (208, 67, 220, 220) => "opendns".to_string(),
1068                        _ => {
1069                            // Real MaxMind GeoIP2 database integration
1070                            self.lookup_maxmind_geolocation(&ipv4).unwrap_or_else(|| {
1071                                // Fallback to basic regional classification
1072                                match octets[0] {
1073                                    1..=23 => "apnic_region".to_string(),    // APNIC (Asia-Pacific)
1074                                    24..=49 => "arin_region".to_string(),    // ARIN (North America)
1075                                    50..=99 => "ripe_region".to_string(), // RIPE (Europe/Middle East)
1076                                    100..=127 => "mixed_region".to_string(), // Various registries
1077                                    128..=191 => "arin_region".to_string(), // ARIN
1078                                    192..=223 => "ripe_apnic_region".to_string(), // RIPE/APNIC
1079                                    _ => format!("public_class_{}", octets[0] / 64),
1080                                }
1081                            })
1082                        }
1083                    }
1084                }
1085                IpAddr::V6(ipv6) => {
1086                    let segments = ipv6.segments();
1087
1088                    // IPv6 loopback
1089                    if ipv6.is_loopback() {
1090                        return "ipv6_loopback".to_string();
1091                    }
1092
1093                    // IPv6 link-local (fe80::/10)
1094                    if segments[0] & 0xffc0 == 0xfe80 {
1095                        return "ipv6_link_local".to_string();
1096                    }
1097
1098                    // IPv6 unique local (fc00::/7)
1099                    if segments[0] & 0xfe00 == 0xfc00 {
1100                        return "ipv6_unique_local".to_string();
1101                    }
1102
1103                    // IPv6 multicast (ff00::/8)
1104                    if segments[0] & 0xff00 == 0xff00 {
1105                        return "ipv6_multicast".to_string();
1106                    }
1107
1108                    // Global unicast
1109                    format!("ipv6_global_{:x}", segments[0] / 0x1000)
1110                }
1111            }
1112        } else {
1113            "invalid_ip".to_string()
1114        }
1115    }
1116
1117    /// Get system language for fingerprinting
1118    fn get_system_language(&self) -> String {
1119        // Would be extracted from Accept-Language header or client info
1120        "en-US".to_string()
1121    }
1122
1123    /// Get timezone offset for fingerprinting
1124    fn get_timezone_offset(&self) -> String {
1125        // Would be provided by client-side JavaScript
1126        "-05:00".to_string() // EST example
1127    }
1128
1129    /// Get hardware concurrency for fingerprinting
1130    fn get_hardware_concurrency(&self) -> String {
1131        // Would be provided by client via navigator.hardwareConcurrency
1132        "4".to_string()
1133    }
1134
1135    /// Get connection information for fingerprinting
1136    fn get_connection_info(&self) -> String {
1137        // Would include connection speed, type, etc.
1138        "wifi".to_string()
1139    }
1140
1141    /// Get client capabilities for fingerprinting
1142    fn get_client_capabilities(&self) -> String {
1143        // Would include supported features, WebGL renderer, etc.
1144        "webgl2_canvas_audio".to_string()
1145    }
1146
1147    /// Lookup IP geolocation using MaxMind GeoIP2 database
1148    fn lookup_maxmind_geolocation(&self, ip: &std::net::Ipv4Addr) -> Option<String> {
1149        // Path to MaxMind GeoLite2-City.mmdb (configurable via environment)
1150        let db_path =
1151            std::env::var("MAXMIND_DB_PATH").unwrap_or_else(|_| "GeoLite2-City.mmdb".to_string());
1152        self.lookup_maxmind_geolocation_at(&db_path, ip)
1153    }
1154
1155    /// [`Self::lookup_maxmind_geolocation`] against an explicit database path.
1156    fn lookup_maxmind_geolocation_at(
1157        &self,
1158        db_path: &str,
1159        ip: &std::net::Ipv4Addr,
1160    ) -> Option<String> {
1161        use std::path::Path;
1162
1163        if !Path::new(&db_path).exists() {
1164            tracing::warn!(
1165                "MaxMind database not found at {}, falling back to basic geolocation",
1166                db_path
1167            );
1168            return None;
1169        }
1170
1171        match maxminddb::Reader::open_readfile(db_path) {
1172            Ok(reader) => {
1173                match reader.lookup((*ip).into()) {
1174                    Ok(result) => match result.decode::<maxminddb::geoip2::City>() {
1175                        Ok(Some(city)) => {
1176                            let mut location_parts = Vec::new();
1177
1178                            // Extract location coordinates from MaxMind data
1179                            let location = &city.location;
1180                            if let (Some(lat), Some(lon)) = (location.latitude, location.longitude)
1181                            {
1182                                location_parts.push(format!("coords:{:.4},{:.4}", lat, lon));
1183                            }
1184
1185                            // Note: Full MaxMind geo-parsing requires accessing complex nested structures
1186                            // For now, we focus on coordinates which are most reliable
1187                            if location_parts.is_empty() {
1188                                None
1189                            } else {
1190                                Some(location_parts.join("|"))
1191                            }
1192                        }
1193                        Ok(None) => {
1194                            tracing::debug!("MaxMind lookup returned no data for {}", ip);
1195                            None
1196                        }
1197                        Err(e) => {
1198                            tracing::debug!("MaxMind decode failed for {}: {}", ip, e);
1199                            None
1200                        }
1201                    },
1202                    Err(e) => {
1203                        tracing::debug!("MaxMind lookup failed for {}: {}", ip, e);
1204                        None
1205                    }
1206                }
1207            }
1208            Err(e) => {
1209                tracing::warn!("Failed to open MaxMind database: {}", e);
1210                None
1211            }
1212        }
1213    }
1214}
1215
1216/// Calculates session risk scores based on device, location, and behavioral factors.
1217///
1218/// Risk scores range from 0 (no risk) to 100 (maximum risk) and are used by
1219/// [`SessionSecurityPolicy`] to trigger automatic session suspension or
1220/// step-up authentication.
1221pub struct RiskCalculator;
1222
1223impl Default for RiskCalculator {
1224    fn default() -> Self {
1225        Self::new()
1226    }
1227}
1228
1229impl RiskCalculator {
1230    pub fn new() -> Self {
1231        Self
1232    }
1233
1234    /// Calculate risk score (0-100) for a session
1235    pub fn calculate_risk(
1236        &self,
1237        device_info: &DeviceInfo,
1238        metadata: &RequestMetadata,
1239        _session_history: &[Session],
1240        threat_intel_manager: Option<&ThreatFeedManager>,
1241    ) -> u8 {
1242        let mut risk_score = 0u8;
1243
1244        // Check for new device
1245        if !device_info.is_trusted {
1246            risk_score += 20;
1247        }
1248
1249        // Check IP reputation (simplified)
1250        if let Some(ip) = &metadata.ip_address
1251            && self.is_suspicious_ip(ip, threat_intel_manager)
1252        {
1253            risk_score += 30;
1254        }
1255
1256        // Check geolocation anomalies
1257        if let Some(location) = &metadata.geolocation {
1258            let mut geo_risk = 0;
1259
1260            // Check country-based risk
1261            if let Some(country) = &location.country {
1262                let country_lower = country.to_lowercase();
1263
1264                // High-risk indicators in country names
1265                let high_risk_countries =
1266                    ["tor", "anonymous", "vpn", "proxy", "hosting", "datacenter"];
1267
1268                for indicator in &high_risk_countries {
1269                    if country_lower.contains(indicator) {
1270                        geo_risk += 30;
1271                        break;
1272                    }
1273                }
1274
1275                // Real threat intelligence integration for geographic risk
1276                geo_risk += self.assess_country_threat_level(&country_lower) as u8;
1277
1278                // Check against known high-risk hosting providers
1279                let elevated_risk_patterns = ["cloud", "aws", "azure", "gcp"];
1280                for pattern in &elevated_risk_patterns {
1281                    if country_lower.contains(pattern) {
1282                        geo_risk += 20;
1283                        break;
1284                    }
1285                }
1286            }
1287
1288            // Check for impossible travel (basic latitude/longitude analysis)
1289            if let (Some(lat), Some(lon)) = (location.latitude, location.longitude) {
1290                // Validate coordinate ranges
1291                if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
1292                    geo_risk += 25; // Invalid coordinates are suspicious
1293                }
1294
1295                // Detect datacenter coordinates (often round numbers)
1296                if (lat * 100.0).fract().abs() < 0.01 && (lon * 100.0).fract().abs() < 0.01 {
1297                    geo_risk += 15; // Suspiciously precise coordinates
1298                }
1299            }
1300
1301            // Region-based analysis
1302            if let Some(region) = &location.region {
1303                let region_lower = region.to_lowercase();
1304                if region_lower.contains("hosting") || region_lower.contains("datacenter") {
1305                    geo_risk += 20;
1306                }
1307            }
1308
1309            // City-based analysis
1310            if let Some(city) = &location.city {
1311                let city_lower = city.to_lowercase();
1312                if city_lower.contains("server") || city_lower.contains("datacenter") {
1313                    geo_risk += 15;
1314                }
1315            }
1316
1317            risk_score += geo_risk;
1318        }
1319
1320        // Check time-based anomalies
1321        // - Unusual login times
1322        // - Rapid geographic movement
1323        // - Multiple simultaneous sessions
1324
1325        risk_score.min(100)
1326    }
1327
1328    /// Check if IP address is suspicious
1329    fn is_suspicious_ip(&self, ip: &str, threat_intel_manager: Option<&ThreatFeedManager>) -> bool {
1330        use std::net::IpAddr;
1331        use std::str::FromStr;
1332
1333        // Parse IP address for analysis
1334        if let Ok(ip_addr) = IpAddr::from_str(ip) {
1335            match ip_addr {
1336                IpAddr::V4(ipv4) => {
1337                    let octets = ipv4.octets();
1338
1339                    // Real threat intelligence feeds integration
1340                    if self.check_malicious_ip_feeds(&ipv4, threat_intel_manager) {
1341                        return true;
1342                    }
1343
1344                    // Suspicious hosting ranges (example patterns)
1345                    let suspicious_ranges = [
1346                        // Known VPN/hosting provider ranges (examples)
1347                        (5, 0, 0, 0, 8),   // Various hosting
1348                        (31, 0, 0, 0, 8),  // Various hosting
1349                        (37, 0, 0, 0, 8),  // Various hosting
1350                        (46, 0, 0, 0, 8),  // Various hosting
1351                        (95, 0, 0, 0, 8),  // Various hosting
1352                        (185, 0, 0, 0, 8), // Various hosting
1353                    ];
1354
1355                    for (net, _, _, _, _) in &suspicious_ranges {
1356                        if octets[0] == *net {
1357                            return true;
1358                        }
1359                    }
1360
1361                    // Check for reserved/special ranges that shouldn't be used
1362                    if octets[0] == 0 ||                              // "This" network
1363                       (octets[0] == 100 && octets[1] >= 64 && octets[1] <= 127) || // Carrier-grade NAT
1364                       (octets[0] == 169 && octets[1] == 254) ||      // Link-local
1365                       (octets[0] >= 224 && octets[0] <= 239) ||      // Multicast
1366                       (octets[0] >= 240)
1367                    {
1368                        // Reserved/experimental
1369                        return true;
1370                    }
1371
1372                    // Detect potential port scans (suspicious patterns in last octet)
1373                    if octets[3] == 0 || octets[3] == 255 {
1374                        return true;
1375                    }
1376
1377                    // Real specialized databases for proxy/VPN detection
1378                    if self.check_proxy_vpn_databases(&ipv4) {
1379                        return true;
1380                    }
1381
1382                    // Fallback proxy port pattern detection
1383                    let proxy_ports_in_ip = [
1384                        80, 443, 8080, 3128, 1080, 8000, 8888, 9050, // Common proxy ports
1385                    ];
1386
1387                    for &port in &proxy_ports_in_ip {
1388                        if octets[2] == (port / 256) as u8 && octets[3] == (port % 256) as u8 {
1389                            return true;
1390                        }
1391                    }
1392
1393                    false
1394                }
1395                IpAddr::V6(ipv6) => {
1396                    let segments = ipv6.segments();
1397
1398                    // Real-time Tor exit node detection
1399                    if self.check_tor_exit_nodes(&ipv6) {
1400                        return true;
1401                    }
1402
1403                    // Fallback static range checks
1404                    if segments[0] == 0x2001 && segments[1] == 0x67c {
1405                        // Example known Tor range (static fallback)
1406                        return true;
1407                    }
1408
1409                    // Suspicious IPv6 patterns (overly sequential or predictable)
1410                    let mut sequential_count = 0;
1411                    for i in 1..segments.len() {
1412                        if segments[i] == segments[i - 1] + 1 {
1413                            sequential_count += 1;
1414                        }
1415                    }
1416                    if sequential_count >= 4 {
1417                        // Too many sequential segments
1418                        return true;
1419                    }
1420
1421                    // Check for tunnel brokers (often used for anonymity)
1422                    if segments[0] == 0x2001 && segments[1] == 0x470 {
1423                        // Hurricane Electric
1424                        return true;
1425                    }
1426
1427                    false
1428                }
1429            }
1430        } else {
1431            true // Invalid IP format is suspicious
1432        }
1433    }
1434
1435    /// Assess threat level for a country using threat intelligence feeds
1436    fn assess_country_threat_level(&self, country: &str) -> u32 {
1437        use std::path::Path;
1438
1439        // Load country threat intelligence (configurable path)
1440        let threat_db_path = std::env::var("COUNTRY_THREAT_DB_PATH")
1441            .unwrap_or_else(|_| "country-threats.csv".to_string());
1442
1443        if Path::new(&threat_db_path).exists() {
1444            // Real implementation: Load from CSV threat feed
1445            if let Ok(contents) = std::fs::read_to_string(&threat_db_path) {
1446                let mut csv_reader = csv::Reader::from_reader(contents.as_bytes());
1447
1448                for result in csv_reader.records() {
1449                    if let Ok(record) = result
1450                        && record.len() >= 2
1451                    {
1452                        let threat_country = record[0].to_lowercase();
1453                        if let Ok(risk_score) = record[1].parse::<u32>()
1454                            && country.contains(&threat_country)
1455                        {
1456                            tracing::debug!(
1457                                "Country threat match: {} -> risk {}",
1458                                country,
1459                                risk_score
1460                            );
1461                            return risk_score;
1462                        }
1463                    }
1464                }
1465            }
1466        }
1467
1468        // No additional risk from country name patterns
1469        0 // No additional risk
1470    }
1471
1472    /// Check IP against malicious IP threat intelligence feeds
1473    fn check_malicious_ip_feeds(
1474        &self,
1475        ip: &std::net::Ipv4Addr,
1476        threat_intel_manager: Option<&ThreatFeedManager>,
1477    ) -> bool {
1478        // Try automated threat intelligence first
1479        if let Some(threat_manager) = threat_intel_manager {
1480            return threat_manager.is_malicious_ip(&std::net::IpAddr::V4(*ip));
1481        }
1482
1483        // Fall back to manual file checking for backward compatibility
1484        use std::path::Path;
1485
1486        // Load malicious IP feeds (multiple sources)
1487        let feed_paths = [
1488            std::env::var("MALICIOUS_IPS_DB_PATH")
1489                .unwrap_or_else(|_| "malicious-ips.txt".to_string()),
1490            std::env::var("BOTNET_IPS_DB_PATH").unwrap_or_else(|_| "botnet-ips.txt".to_string()),
1491            std::env::var("TOR_EXIT_NODES_DB_PATH").unwrap_or_else(|_| "tor-exits.txt".to_string()),
1492        ];
1493
1494        for feed_path in &feed_paths {
1495            if Path::new(feed_path).exists()
1496                && let Ok(contents) = std::fs::read_to_string(feed_path)
1497            {
1498                for line in contents.lines() {
1499                    let line = line.trim();
1500                    if line.is_empty() || line.starts_with('#') {
1501                        continue;
1502                    }
1503
1504                    // Check exact IP match
1505                    if line == ip.to_string() {
1506                        tracing::warn!("Malicious IP detected: {} (source: {})", ip, feed_path);
1507                        return true;
1508                    }
1509
1510                    // Check CIDR network match
1511                    if line.contains('/')
1512                        && let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1513                        && network.contains(*ip)
1514                    {
1515                        tracing::warn!(
1516                            "Malicious network detected: {} in {} (source: {})",
1517                            ip,
1518                            network,
1519                            feed_path
1520                        );
1521                        return true;
1522                    }
1523                }
1524            }
1525        }
1526
1527        false
1528    }
1529
1530    /// Check against specialized proxy/VPN databases
1531    fn check_proxy_vpn_databases(&self, ip: &std::net::Ipv4Addr) -> bool {
1532        use std::path::Path;
1533
1534        // Multiple specialized databases for proxy/VPN detection
1535        let db_sources = [
1536            ("VPN_DATABASE_PATH", "vpn-ranges.txt"),
1537            ("PROXY_DATABASE_PATH", "proxy-ips.txt"),
1538            ("DATACENTER_DATABASE_PATH", "datacenter-ranges.txt"),
1539            ("HOSTING_DATABASE_PATH", "hosting-providers.txt"),
1540        ];
1541
1542        for (env_var, default_file) in &db_sources {
1543            let db_path = std::env::var(env_var).unwrap_or_else(|_| default_file.to_string());
1544
1545            if Path::new(&db_path).exists()
1546                && let Ok(contents) = std::fs::read_to_string(&db_path)
1547            {
1548                for line in contents.lines() {
1549                    let line = line.trim();
1550                    if line.is_empty() || line.starts_with('#') {
1551                        continue;
1552                    }
1553
1554                    // Support multiple formats: IP, CIDR, IP ranges
1555                    if line.contains('/') {
1556                        // CIDR notation
1557                        if let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1558                            && network.contains(*ip)
1559                        {
1560                            tracing::info!(
1561                                "Proxy/VPN detected: {} in {} (source: {})",
1562                                ip,
1563                                network,
1564                                db_path
1565                            );
1566                            return true;
1567                        }
1568                    } else if line.contains('-') {
1569                        // IP range format: 1.2.3.4-1.2.3.10
1570                        let parts: Vec<&str> = line.split('-').collect();
1571                        if parts.len() == 2
1572                            && let (Ok(start_ip), Ok(end_ip)) = (
1573                                parts[0].trim().parse::<std::net::Ipv4Addr>(),
1574                                parts[1].trim().parse::<std::net::Ipv4Addr>(),
1575                            )
1576                        {
1577                            let ip_u32 = u32::from(*ip);
1578                            let start_u32 = u32::from(start_ip);
1579                            let end_u32 = u32::from(end_ip);
1580
1581                            if ip_u32 >= start_u32 && ip_u32 <= end_u32 {
1582                                tracing::info!(
1583                                    "Proxy/VPN range detected: {} in {}-{} (source: {})",
1584                                    ip,
1585                                    start_ip,
1586                                    end_ip,
1587                                    db_path
1588                                );
1589                                return true;
1590                            }
1591                        }
1592                    } else if line == ip.to_string() {
1593                        // Exact IP match
1594                        tracing::info!("Proxy/VPN exact match: {} (source: {})", ip, db_path);
1595                        return true;
1596                    }
1597                }
1598            }
1599        }
1600
1601        false
1602    }
1603
1604    /// Check against real-time Tor exit node lists
1605    fn check_tor_exit_nodes(&self, ip: &std::net::Ipv6Addr) -> bool {
1606        use std::path::Path;
1607
1608        // Real-time Tor exit node detection
1609        let tor_db_path = std::env::var("TOR_EXIT_NODES_IPV6_PATH")
1610            .unwrap_or_else(|_| "tor-exits-ipv6.txt".to_string());
1611
1612        if Path::new(&tor_db_path).exists()
1613            && let Ok(contents) = std::fs::read_to_string(&tor_db_path)
1614        {
1615            for line in contents.lines() {
1616                let line = line.trim();
1617                if line.is_empty() || line.starts_with('#') {
1618                    continue;
1619                }
1620
1621                // Check IPv6 exact match
1622                if let Ok(tor_ip) = line.parse::<std::net::Ipv6Addr>()
1623                    && tor_ip == *ip
1624                {
1625                    tracing::warn!("Tor exit node detected: {}", ip);
1626                    return true;
1627                }
1628
1629                // Check IPv6 network match
1630                if line.contains('/')
1631                    && let Ok(network) = line.parse::<ipnetwork::Ipv6Network>()
1632                    && network.contains(*ip)
1633                {
1634                    tracing::warn!("Tor exit network detected: {} in {}", ip, network);
1635                    return true;
1636                }
1637            }
1638        }
1639
1640        // Also check IPv4-mapped IPv6 addresses for Tor
1641        if let Some(ipv4) = ip.to_ipv4() {
1642            let tor_v4_path = std::env::var("TOR_EXIT_NODES_IPV4_PATH")
1643                .unwrap_or_else(|_| "tor-exits-ipv4.txt".to_string());
1644
1645            if Path::new(&tor_v4_path).exists()
1646                && let Ok(contents) = std::fs::read_to_string(&tor_v4_path)
1647            {
1648                for line in contents.lines() {
1649                    let line = line.trim();
1650                    if line == ipv4.to_string() {
1651                        tracing::warn!("Tor exit node detected (IPv4-mapped): {}", ip);
1652                        return true;
1653                    }
1654                }
1655            }
1656        }
1657
1658        false
1659    }
1660}
1661
1662impl Default for SessionConfig {
1663    fn default() -> Self {
1664        Self {
1665            default_duration: Duration::from_secs(3600), // 1 hour
1666            max_duration: Duration::from_secs(86400),    // 24 hours
1667            idle_timeout: Duration::from_secs(1800),     // 30 minutes
1668            rotate_on_privilege_escalation: true,
1669            rotate_periodically: true,
1670            rotation_interval: Duration::from_secs(1800), // 30 minutes
1671            max_concurrent_sessions: Some(5),
1672            track_device_fingerprints: true,
1673            enforce_geographic_restrictions: false,
1674            allowed_countries: vec![],
1675            security_policy: SessionSecurityPolicy::default(),
1676        }
1677    }
1678}
1679
1680impl Default for SessionSecurityPolicy {
1681    fn default() -> Self {
1682        Self {
1683            require_mfa_for_new_devices: true,
1684            require_reauth_for_sensitive_ops: true,
1685            reauth_timeout: Duration::from_secs(300), // 5 minutes
1686            max_risk_score: 70,
1687            auto_suspend_suspicious: true,
1688            verify_location_changes: true,
1689            limit_concurrent_sessions: true,
1690        }
1691    }
1692}
1693
1694#[cfg(test)]
1695mod tests {
1696    use super::*;
1697
1698    #[test]
1699    fn test_device_fingerprint_generation() {
1700        let generator = DeviceFingerprintGenerator::new();
1701        let metadata = RequestMetadata {
1702            user_agent: Some("Mozilla/5.0".to_string()),
1703            ..Default::default()
1704        };
1705
1706        let fp1 = generator.generate_fingerprint(&metadata);
1707        let fp2 = generator.generate_fingerprint(&metadata);
1708
1709        assert_eq!(fp1, fp2);
1710        assert!(fp1.starts_with("fp_"));
1711    }
1712
1713    #[test]
1714    fn test_risk_calculation() {
1715        let calculator = RiskCalculator::new();
1716        let device_info = DeviceInfo {
1717            fingerprint: "test".to_string(),
1718            device_type: "desktop".to_string(),
1719            operating_system: None,
1720            browser: None,
1721            screen_resolution: None,
1722            timezone: None,
1723            language: None,
1724            is_trusted: false,
1725            device_name: None,
1726            is_mobile: false,
1727            ip_address: None,
1728        };
1729
1730        let metadata = RequestMetadata::default();
1731        let history = vec![];
1732
1733        let risk = calculator.calculate_risk(&device_info, &metadata, &history, None);
1734        assert!(risk >= 20); // Should have at least 20 for untrusted device
1735    }
1736
1737    #[test]
1738    fn test_session_config_builder_for_web_app() {
1739        let config = SessionConfigBuilder::for_web_app().build();
1740        assert_eq!(config.default_duration, Duration::from_secs(3600));
1741        assert_eq!(config.max_duration, Duration::from_secs(86400));
1742        assert_eq!(config.max_concurrent_sessions, Some(5));
1743        assert!(config.track_device_fingerprints);
1744    }
1745
1746    #[test]
1747    fn test_session_config_builder_for_api_service() {
1748        let config = SessionConfigBuilder::for_api_service().build();
1749        assert_eq!(config.default_duration, Duration::from_secs(900));
1750        assert!(config.max_concurrent_sessions.is_none());
1751        assert!(!config.track_device_fingerprints);
1752        assert!(!config.rotate_periodically);
1753    }
1754
1755    #[test]
1756    fn test_session_config_builder_for_high_security() {
1757        let config = SessionConfigBuilder::for_high_security()
1758            .allowed_countries(vec!["US".into()])
1759            .build();
1760        assert_eq!(config.default_duration, Duration::from_secs(1800));
1761        assert_eq!(config.max_concurrent_sessions, Some(1));
1762        assert!(config.enforce_geographic_restrictions);
1763        assert_eq!(config.allowed_countries, vec!["US".to_string()]);
1764        assert!(config.security_policy.require_mfa_for_new_devices);
1765    }
1766
1767    // No test here performs a real MaxMind lookup (that needs a third-party
1768    // .mmdb fixture). These cover the open path: a missing or unreadable
1769    // database must yield `None`, never a panic.
1770    #[test]
1771    fn maxmind_geolocation_none_for_missing_or_garbage_database() {
1772        let generator = DeviceFingerprintGenerator::new();
1773        let ip = std::net::Ipv4Addr::new(8, 8, 8, 8);
1774        let dir = tempfile::tempdir().unwrap();
1775
1776        let missing = dir.path().join("missing.mmdb");
1777        assert_eq!(
1778            generator.lookup_maxmind_geolocation_at(missing.to_str().unwrap(), &ip),
1779            None
1780        );
1781
1782        let garbage_inputs: [(&str, &[u8]); 3] = [
1783            ("empty.mmdb", b""),
1784            ("garbage.mmdb", b"this is not a MaxMind database at all"),
1785            ("truncated.mmdb", b"\xAB\xCD\xEFMaxMind.com\x00"),
1786        ];
1787        for (name, bytes) in garbage_inputs {
1788            let path = dir.path().join(name);
1789            std::fs::write(&path, bytes).unwrap();
1790            // Positive control: see the twin test in secure_session_config.rs.
1791            assert!(
1792                maxminddb::Reader::open_readfile(&path).is_err(),
1793                "{name}: maxminddb accepted garbage bytes"
1794            );
1795            assert_eq!(
1796                generator.lookup_maxmind_geolocation_at(path.to_str().unwrap(), &ip),
1797                None,
1798                "{name}"
1799            );
1800        }
1801    }
1802}