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