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    /// **Deprecated: has no effect.** Nothing in the session manager rotates a session on
206    /// privilege escalation (there is no escalation event to hook), so setting this does not
207    /// do what its name says. Use [`Self::rotate_periodically`] for rotation.
208    pub rotate_on_privilege_escalation: bool,
209    /// Whether to rotate session IDs periodically
210    pub rotate_periodically: bool,
211    /// Rotation interval
212    pub rotation_interval: Duration,
213    /// Maximum concurrent sessions per user
214    pub max_concurrent_sessions: Option<u32>,
215    /// Whether to track device fingerprints
216    pub track_device_fingerprints: bool,
217    /// Whether to enforce geographic restrictions
218    pub enforce_geographic_restrictions: bool,
219    /// Allowed countries (if geographic restrictions enabled)
220    pub allowed_countries: Vec<String>,
221    /// Security policy
222    pub security_policy: SessionSecurityPolicy,
223}
224
225/// Session security policy
226impl SessionConfig {
227    /// Create a new builder for SessionConfig
228    pub fn builder() -> SessionConfigBuilder {
229        SessionConfigBuilder::default()
230    }
231}
232
233/// A builder for SessionConfig
234#[derive(Default)]
235pub struct SessionConfigBuilder {
236    config: SessionConfig,
237}
238
239impl SessionConfigBuilder {
240    /// Set the default session duration.
241    ///
242    /// # Example
243    /// ```rust,ignore
244    /// use std::time::Duration;
245    /// let config = SessionConfigBuilder::default()
246    ///     .default_duration(Duration::from_secs(3600))
247    ///     .build();
248    /// ```
249    pub fn default_duration(mut self, duration: std::time::Duration) -> Self {
250        self.config.default_duration = duration;
251        self
252    }
253
254    /// Set the maximum session duration.
255    ///
256    /// # Example
257    /// ```rust,ignore
258    /// let config = SessionConfigBuilder::default()
259    ///     .max_duration(Duration::from_secs(86400))
260    ///     .build();
261    /// ```
262    pub fn max_duration(mut self, duration: std::time::Duration) -> Self {
263        self.config.max_duration = duration;
264        self
265    }
266
267    /// Set the session idle timeout.
268    ///
269    /// # Example
270    /// ```rust,ignore
271    /// let config = SessionConfigBuilder::default()
272    ///     .idle_timeout(Duration::from_secs(900))
273    ///     .build();
274    /// ```
275    pub fn idle_timeout(mut self, timeout: std::time::Duration) -> Self {
276        self.config.idle_timeout = timeout;
277        self
278    }
279
280    /// **Deprecated: has no effect.** Sessions are not rotated on privilege escalation;
281    /// use [`Self::rotate_periodically`] instead.
282    #[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    /// 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 of a user's sessions that are still usable, whatever their state
825    /// (active, suspended, awaiting MFA / re-authentication / rotation, high-risk). Sessions
826    /// that are already `Expired` or `Revoked` are left as they are and not counted.
827    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    /// List sessions for a user.
843    ///
844    /// When `include_inactive` is `false`, only [`SessionState::Active`]
845    /// sessions are returned.
846    ///
847    /// Prefer [`list_user_sessions`](Self::list_user_sessions) with a
848    /// [`SessionFilter`](crate::auth_operations::SessionFilter) for
849    /// self-documenting call sites.
850    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    /// List sessions for a user with a typed [`SessionFilter`](crate::auth_operations::SessionFilter).
865    ///
866    /// ```rust,ignore
867    /// use auth_framework::auth_operations::SessionFilter;
868    ///
869    /// let active = mgr.list_user_sessions(user_id, SessionFilter::ActiveOnly).await?;
870    /// ```
871    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    /// Remove all expired sessions from storage and return how many were cleaned up.
881    pub async fn cleanup_expired_sessions(&self) -> Result<u32> {
882        self.storage.cleanup_expired_sessions().await
883    }
884
885    /// Compute a device fingerprint from the request metadata (IP, User-Agent, etc.).
886    pub fn generate_device_fingerprint(&self, metadata: &RequestMetadata) -> String {
887        self.fingerprint_generator.generate_fingerprint(metadata)
888    }
889
890    /// Check whether `metadata` produces a fingerprint matching the session's stored value.
891    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    /// Suspend suspicious sessions
901    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            // Log suspension
912            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    /// Update session data
935    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    /// Generate a new session ID
950    fn generate_session_id(&self) -> String {
951        format!("sess_{}", uuid::Uuid::new_v4())
952    }
953
954    /// Check if session should be rotated
955    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    /// Get user session history for risk calculation
968    async fn get_user_session_history(&self, user_id: &str) -> Result<Vec<Session>> {
969        // This would typically be a more sophisticated query
970        // For now, just return recent sessions
971        self.storage.get_user_sessions(user_id).await
972    }
973}
974
975/// Generates device fingerprints for session tracking and anomaly detection.
976///
977/// Fingerprints are derived from user-agent strings and other request metadata
978/// to identify returning devices without storing sensitive client information.
979pub 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    /// Generate device fingerprint from request metadata
993    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        // Comprehensive device fingerprinting implementation
1001        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    /// Add advanced fingerprinting data based on available metadata
1008    fn add_advanced_fingerprinting_data(
1009        &self,
1010        fingerprint_data: &mut Vec<String>,
1011        metadata: &RequestMetadata,
1012    ) {
1013        // Screen characteristics (if available)
1014        if let Some(ref ip) = metadata.ip_address {
1015            // Extract geographical and ISP information from IP
1016            fingerprint_data.push(format!("geo:{}", self.get_ip_geolocation(ip)));
1017        }
1018
1019        // Browser/client characteristics
1020        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        // Network characteristics
1025        fingerprint_data.push(format!("conn:{}", self.get_connection_info()));
1026
1027        // Additional entropy sources
1028        fingerprint_data.push(format!("caps:{}", self.get_client_capabilities()));
1029    }
1030
1031    /// Get IP geolocation information for fingerprinting
1032    fn get_ip_geolocation(&self, ip: &str) -> String {
1033        use std::net::IpAddr;
1034        use std::str::FromStr;
1035
1036        // Parse IP address for classification
1037        if let Ok(ip_addr) = IpAddr::from_str(ip) {
1038            match ip_addr {
1039                IpAddr::V4(ipv4) => {
1040                    let octets = ipv4.octets();
1041
1042                    // RFC 1918 private networks
1043                    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                    // Loopback
1051                    if octets[0] == 127 {
1052                        return "loopback".to_string();
1053                    }
1054
1055                    // Link-local (169.254.x.x)
1056                    if octets[0] == 169 && octets[1] == 254 {
1057                        return "link_local".to_string();
1058                    }
1059
1060                    // Multicast
1061                    if octets[0] >= 224 && octets[0] <= 239 {
1062                        return "multicast".to_string();
1063                    }
1064
1065                    // Known public DNS servers
1066                    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                            // Real MaxMind GeoIP2 database integration
1072                            self.lookup_maxmind_geolocation(&ipv4).unwrap_or_else(|| {
1073                                // Fallback to basic regional classification
1074                                match octets[0] {
1075                                    1..=23 => "apnic_region".to_string(),    // APNIC (Asia-Pacific)
1076                                    24..=49 => "arin_region".to_string(),    // ARIN (North America)
1077                                    50..=99 => "ripe_region".to_string(), // RIPE (Europe/Middle East)
1078                                    100..=127 => "mixed_region".to_string(), // Various registries
1079                                    128..=191 => "arin_region".to_string(), // ARIN
1080                                    192..=223 => "ripe_apnic_region".to_string(), // RIPE/APNIC
1081                                    _ => format!("public_class_{}", octets[0] / 64),
1082                                }
1083                            })
1084                        }
1085                    }
1086                }
1087                IpAddr::V6(ipv6) => {
1088                    let segments = ipv6.segments();
1089
1090                    // IPv6 loopback
1091                    if ipv6.is_loopback() {
1092                        return "ipv6_loopback".to_string();
1093                    }
1094
1095                    // IPv6 link-local (fe80::/10)
1096                    if segments[0] & 0xffc0 == 0xfe80 {
1097                        return "ipv6_link_local".to_string();
1098                    }
1099
1100                    // IPv6 unique local (fc00::/7)
1101                    if segments[0] & 0xfe00 == 0xfc00 {
1102                        return "ipv6_unique_local".to_string();
1103                    }
1104
1105                    // IPv6 multicast (ff00::/8)
1106                    if segments[0] & 0xff00 == 0xff00 {
1107                        return "ipv6_multicast".to_string();
1108                    }
1109
1110                    // Global unicast
1111                    format!("ipv6_global_{:x}", segments[0] / 0x1000)
1112                }
1113            }
1114        } else {
1115            "invalid_ip".to_string()
1116        }
1117    }
1118
1119    /// Get system language for fingerprinting
1120    fn get_system_language(&self) -> String {
1121        // Would be extracted from Accept-Language header or client info
1122        "en-US".to_string()
1123    }
1124
1125    /// Get timezone offset for fingerprinting
1126    fn get_timezone_offset(&self) -> String {
1127        // Would be provided by client-side JavaScript
1128        "-05:00".to_string() // EST example
1129    }
1130
1131    /// Get hardware concurrency for fingerprinting
1132    fn get_hardware_concurrency(&self) -> String {
1133        // Would be provided by client via navigator.hardwareConcurrency
1134        "4".to_string()
1135    }
1136
1137    /// Get connection information for fingerprinting
1138    fn get_connection_info(&self) -> String {
1139        // Would include connection speed, type, etc.
1140        "wifi".to_string()
1141    }
1142
1143    /// Get client capabilities for fingerprinting
1144    fn get_client_capabilities(&self) -> String {
1145        // Would include supported features, WebGL renderer, etc.
1146        "webgl2_canvas_audio".to_string()
1147    }
1148
1149    /// Lookup IP geolocation using MaxMind GeoIP2 database
1150    fn lookup_maxmind_geolocation(&self, ip: &std::net::Ipv4Addr) -> Option<String> {
1151        // Path to MaxMind GeoLite2-City.mmdb (configurable via environment)
1152        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    /// [`Self::lookup_maxmind_geolocation`] against an explicit database path.
1158    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                            // Extract location coordinates from MaxMind data
1181                            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                            // Note: Full MaxMind geo-parsing requires accessing complex nested structures
1188                            // For now, we focus on coordinates which are most reliable
1189                            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
1218/// Calculates session risk scores based on device, location, and behavioral factors.
1219///
1220/// Risk scores range from 0 (no risk) to 100 (maximum risk) and are used by
1221/// [`SessionSecurityPolicy`] to trigger automatic session suspension or
1222/// step-up authentication.
1223pub 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    /// Calculate risk score (0-100) for a session
1237    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        // Check for new device
1247        if !device_info.is_trusted {
1248            risk_score += 20;
1249        }
1250
1251        // Check IP reputation (simplified)
1252        if let Some(ip) = &metadata.ip_address
1253            && self.is_suspicious_ip(ip, threat_intel_manager)
1254        {
1255            risk_score += 30;
1256        }
1257
1258        // Check geolocation anomalies
1259        if let Some(location) = &metadata.geolocation {
1260            let mut geo_risk = 0;
1261
1262            // Check country-based risk
1263            if let Some(country) = &location.country {
1264                let country_lower = country.to_lowercase();
1265
1266                // High-risk indicators in country names
1267                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                // Real threat intelligence integration for geographic risk
1278                geo_risk += self.assess_country_threat_level(&country_lower) as u8;
1279
1280                // Check against known high-risk hosting providers
1281                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            // Check for impossible travel (basic latitude/longitude analysis)
1291            if let (Some(lat), Some(lon)) = (location.latitude, location.longitude) {
1292                // Validate coordinate ranges
1293                if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
1294                    geo_risk += 25; // Invalid coordinates are suspicious
1295                }
1296
1297                // Detect datacenter coordinates (often round numbers)
1298                if (lat * 100.0).fract().abs() < 0.01 && (lon * 100.0).fract().abs() < 0.01 {
1299                    geo_risk += 15; // Suspiciously precise coordinates
1300                }
1301            }
1302
1303            // Region-based analysis
1304            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            // City-based analysis
1312            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        // Check time-based anomalies
1323        // - Unusual login times
1324        // - Rapid geographic movement
1325        // - Multiple simultaneous sessions
1326
1327        risk_score.min(100)
1328    }
1329
1330    /// Check if IP address is suspicious
1331    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        // Parse IP address for analysis
1336        if let Ok(ip_addr) = IpAddr::from_str(ip) {
1337            match ip_addr {
1338                IpAddr::V4(ipv4) => {
1339                    let octets = ipv4.octets();
1340
1341                    // Real threat intelligence feeds integration
1342                    if self.check_malicious_ip_feeds(&ipv4, threat_intel_manager) {
1343                        return true;
1344                    }
1345
1346                    // Suspicious hosting ranges (example patterns)
1347                    let suspicious_ranges = [
1348                        // Known VPN/hosting provider ranges (examples)
1349                        (5, 0, 0, 0, 8),   // Various hosting
1350                        (31, 0, 0, 0, 8),  // Various hosting
1351                        (37, 0, 0, 0, 8),  // Various hosting
1352                        (46, 0, 0, 0, 8),  // Various hosting
1353                        (95, 0, 0, 0, 8),  // Various hosting
1354                        (185, 0, 0, 0, 8), // Various hosting
1355                    ];
1356
1357                    for (net, _, _, _, _) in &suspicious_ranges {
1358                        if octets[0] == *net {
1359                            return true;
1360                        }
1361                    }
1362
1363                    // Check for reserved/special ranges that shouldn't be used
1364                    if octets[0] == 0 ||                              // "This" network
1365                       (octets[0] == 100 && octets[1] >= 64 && octets[1] <= 127) || // Carrier-grade NAT
1366                       (octets[0] == 169 && octets[1] == 254) ||      // Link-local
1367                       (octets[0] >= 224 && octets[0] <= 239) ||      // Multicast
1368                       (octets[0] >= 240)
1369                    {
1370                        // Reserved/experimental
1371                        return true;
1372                    }
1373
1374                    // Detect potential port scans (suspicious patterns in last octet)
1375                    if octets[3] == 0 || octets[3] == 255 {
1376                        return true;
1377                    }
1378
1379                    // Real specialized databases for proxy/VPN detection
1380                    if self.check_proxy_vpn_databases(&ipv4) {
1381                        return true;
1382                    }
1383
1384                    // Fallback proxy port pattern detection
1385                    let proxy_ports_in_ip = [
1386                        80, 443, 8080, 3128, 1080, 8000, 8888, 9050, // Common proxy ports
1387                    ];
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                    // Real-time Tor exit node detection
1401                    if self.check_tor_exit_nodes(&ipv6) {
1402                        return true;
1403                    }
1404
1405                    // Fallback static range checks
1406                    if segments[0] == 0x2001 && segments[1] == 0x67c {
1407                        // Example known Tor range (static fallback)
1408                        return true;
1409                    }
1410
1411                    // Suspicious IPv6 patterns (overly sequential or predictable)
1412                    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                        // Too many sequential segments
1420                        return true;
1421                    }
1422
1423                    // Check for tunnel brokers (often used for anonymity)
1424                    if segments[0] == 0x2001 && segments[1] == 0x470 {
1425                        // Hurricane Electric
1426                        return true;
1427                    }
1428
1429                    false
1430                }
1431            }
1432        } else {
1433            true // Invalid IP format is suspicious
1434        }
1435    }
1436
1437    /// Assess threat level for a country using threat intelligence feeds
1438    fn assess_country_threat_level(&self, country: &str) -> u32 {
1439        use std::path::Path;
1440
1441        // Load country threat intelligence (configurable path)
1442        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            // Real implementation: Load from CSV threat feed
1447            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        // No additional risk from country name patterns
1471        0 // No additional risk
1472    }
1473
1474    /// Check IP against malicious IP threat intelligence feeds
1475    fn check_malicious_ip_feeds(
1476        &self,
1477        ip: &std::net::Ipv4Addr,
1478        threat_intel_manager: Option<&ThreatFeedManager>,
1479    ) -> bool {
1480        // Try automated threat intelligence first
1481        if let Some(threat_manager) = threat_intel_manager {
1482            return threat_manager.is_malicious_ip(&std::net::IpAddr::V4(*ip));
1483        }
1484
1485        // Fall back to manual file checking for backward compatibility
1486        use std::path::Path;
1487
1488        // Load malicious IP feeds (multiple sources)
1489        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                    // Check exact IP match
1507                    if line == ip.to_string() {
1508                        tracing::warn!("Malicious IP detected: {} (source: {})", ip, feed_path);
1509                        return true;
1510                    }
1511
1512                    // Check CIDR network match
1513                    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    /// Check against specialized proxy/VPN databases
1533    fn check_proxy_vpn_databases(&self, ip: &std::net::Ipv4Addr) -> bool {
1534        use std::path::Path;
1535
1536        // Multiple specialized databases for proxy/VPN detection
1537        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                    // Support multiple formats: IP, CIDR, IP ranges
1557                    if line.contains('/') {
1558                        // CIDR notation
1559                        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                        // IP range format: 1.2.3.4-1.2.3.10
1572                        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                        // Exact IP match
1596                        tracing::info!("Proxy/VPN exact match: {} (source: {})", ip, db_path);
1597                        return true;
1598                    }
1599                }
1600            }
1601        }
1602
1603        false
1604    }
1605
1606    /// Check against real-time Tor exit node lists
1607    fn check_tor_exit_nodes(&self, ip: &std::net::Ipv6Addr) -> bool {
1608        use std::path::Path;
1609
1610        // Real-time Tor exit node detection
1611        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                // Check IPv6 exact match
1624                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                // Check IPv6 network match
1632                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        // Also check IPv4-mapped IPv6 addresses for Tor
1643        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), // 1 hour
1668            max_duration: Duration::from_secs(86400),    // 24 hours
1669            idle_timeout: Duration::from_secs(1800),     // 30 minutes
1670            rotate_on_privilege_escalation: true,
1671            rotate_periodically: true,
1672            rotation_interval: Duration::from_secs(1800), // 30 minutes
1673            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), // 5 minutes
1688            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); // Should have at least 20 for untrusted device
1737    }
1738
1739    /// Minimal in-memory session storage for tests.
1740    #[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        // a terminal session is left as it is and not counted; another user's session is untouched
1812        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    // No test here performs a real MaxMind lookup (that needs a third-party
1871    // .mmdb fixture). These cover the open path: a missing or unreadable
1872    // database must yield `None`, never a panic.
1873    #[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            // Positive control: see the twin test in secure_session_config.rs.
1894            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}