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    /// **Deprecated: has no effect.** Nothing in the session manager rotates a session on
225    /// privilege escalation (there is no escalation event to hook), so setting this does not
226    /// do what its name says. Use [`Self::rotate_periodically`] for rotation.
227    pub rotate_on_privilege_escalation: bool,
228    /// Whether to rotate session IDs periodically
229    pub rotate_periodically: bool,
230    /// Rotation interval
231    pub rotation_interval: Duration,
232    /// Maximum concurrent sessions per user
233    pub max_concurrent_sessions: Option<u32>,
234    /// Whether to track device fingerprints
235    pub track_device_fingerprints: bool,
236    /// Whether to enforce geographic restrictions
237    pub enforce_geographic_restrictions: bool,
238    /// Allowed countries (if geographic restrictions enabled)
239    pub allowed_countries: Vec<String>,
240    /// Security policy
241    pub security_policy: SessionSecurityPolicy,
242}
243
244/// Session security policy
245impl SessionConfig {
246    /// Create a new builder for SessionConfig
247    pub fn builder() -> SessionConfigBuilder {
248        SessionConfigBuilder::default()
249    }
250}
251
252/// A builder for SessionConfig
253#[derive(Default)]
254pub struct SessionConfigBuilder {
255    config: SessionConfig,
256}
257
258impl SessionConfigBuilder {
259    /// Set the default session duration.
260    ///
261    /// # Example
262    /// ```rust,ignore
263    /// use std::time::Duration;
264    /// let config = SessionConfigBuilder::default()
265    ///     .default_duration(Duration::from_secs(3600))
266    ///     .build();
267    /// ```
268    pub fn default_duration(mut self, duration: std::time::Duration) -> Self {
269        self.config.default_duration = duration;
270        self
271    }
272
273    /// Set the maximum session duration.
274    ///
275    /// # Example
276    /// ```rust,ignore
277    /// let config = SessionConfigBuilder::default()
278    ///     .max_duration(Duration::from_secs(86400))
279    ///     .build();
280    /// ```
281    pub fn max_duration(mut self, duration: std::time::Duration) -> Self {
282        self.config.max_duration = duration;
283        self
284    }
285
286    /// Set the session idle timeout.
287    ///
288    /// # Example
289    /// ```rust,ignore
290    /// let config = SessionConfigBuilder::default()
291    ///     .idle_timeout(Duration::from_secs(900))
292    ///     .build();
293    /// ```
294    pub fn idle_timeout(mut self, timeout: std::time::Duration) -> Self {
295        self.config.idle_timeout = timeout;
296        self
297    }
298
299    /// **Deprecated: has no effect.** Sessions are not rotated on privilege escalation;
300    /// use [`Self::rotate_periodically`] instead.
301    #[deprecated(
302        since = "0.6.0",
303        note = "has no effect: sessions are not rotated on privilege escalation; use rotate_periodically"
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                        session_id, session.device_info.fingerprint, current_fingerprint
747                    ),
748                    metadata.clone(),
749                )
750                .await?;
751        }
752
753        // Check if session is idle too long
754        let idle_duration = now
755            .duration_since(session.last_accessed)
756            .unwrap_or_default();
757        if idle_duration > self.config.idle_timeout {
758            session.state = SessionState::Expired;
759            self.storage.update_session(&session).await?;
760            return Ok(None);
761        }
762
763        // Check session state
764        match session.state {
765            SessionState::Expired | SessionState::Revoked | SessionState::Suspended => {
766                return Ok(None);
767            }
768            SessionState::RequiresMfa | SessionState::RequiresReauth => {
769                // Return session but caller needs to handle MFA/reauth
770                return Ok(Some(session));
771            }
772            SessionState::Active | SessionState::RequiresRotation | SessionState::HighRisk => {}
773        }
774
775        // Update security metadata
776        let current_ip = metadata.ip_address.clone().unwrap_or_default();
777        let ip_changed = current_ip != session.security_metadata.current_ip;
778
779        if ip_changed {
780            session.security_metadata.ip_changed = true;
781            session.security_metadata.current_ip = current_ip;
782
783            // Check if location verification is required
784            if self.config.security_policy.verify_location_changes {
785                session
786                    .security_metadata
787                    .security_flags
788                    .push(SecurityFlag::LocationAnomaly);
789                session.state = SessionState::RequiresReauth;
790            }
791        }
792
793        // Update last accessed time and activity
794        session.last_accessed = now;
795        session.last_activity = ActivityInfo {
796            endpoint: metadata.endpoint.clone(),
797            action: Some("session_validated".to_string()),
798            request_metadata: Some(metadata),
799            timestamp: now,
800        };
801
802        // Check if session rotation is needed
803        let should_rotate = self.should_rotate_session(&session);
804        if should_rotate {
805            let new_session_id = self.generate_session_id();
806            let old_session_id = session.id.clone();
807            session.id = new_session_id;
808
809            // Delete old session and create new one
810            self.storage.delete_session(&old_session_id).await?;
811            self.storage.create_session(&session).await?;
812        } else {
813            self.storage.update_session(&session).await?;
814        }
815
816        Ok(Some(session))
817    }
818
819    /// Revoke a session
820    pub async fn revoke_session(&self, session_id: &str) -> Result<()> {
821        if let Some(mut session) = self.storage.get_session(session_id).await? {
822            session.state = SessionState::Revoked;
823            self.storage.update_session(&session).await?;
824
825            // Log session revocation
826            self.audit_logger
827                .log_event(
828                    crate::audit::AuditEvent::builder(
829                        crate::audit::AuditEventType::Logout,
830                        "Session revoked",
831                    )
832                    .user_id(session.user_id)
833                    .session_id(session_id)
834                    .outcome(crate::audit::EventOutcome::Success)
835                    .with_actor("system", "session_manager")
836                    .build(),
837                )
838                .await?;
839        }
840        Ok(())
841    }
842
843    /// Revoke all of a user's sessions that are still usable, whatever their state
844    /// (active, suspended, awaiting MFA / re-authentication / rotation, high-risk). Sessions
845    /// that are already `Expired` or `Revoked` are left as they are and not counted.
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 !matches!(session.state, SessionState::Expired | SessionState::Revoked) {
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        // Path to MaxMind GeoLite2-City.mmdb (configurable via environment)
1171        let db_path =
1172            std::env::var("MAXMIND_DB_PATH").unwrap_or_else(|_| "GeoLite2-City.mmdb".to_string());
1173        self.lookup_maxmind_geolocation_at(&db_path, ip)
1174    }
1175
1176    /// [`Self::lookup_maxmind_geolocation`] against an explicit database path.
1177    fn lookup_maxmind_geolocation_at(
1178        &self,
1179        db_path: &str,
1180        ip: &std::net::Ipv4Addr,
1181    ) -> Option<String> {
1182        use std::path::Path;
1183
1184        if !Path::new(&db_path).exists() {
1185            tracing::warn!(
1186                "MaxMind database not found at {}, falling back to basic geolocation",
1187                db_path
1188            );
1189            return None;
1190        }
1191
1192        match maxminddb::Reader::open_readfile(db_path) {
1193            Ok(reader) => {
1194                match reader.lookup((*ip).into()) {
1195                    Ok(result) => match result.decode::<maxminddb::geoip2::City>() {
1196                        Ok(Some(city)) => {
1197                            let mut location_parts = Vec::new();
1198
1199                            // Extract location coordinates from MaxMind data
1200                            let location = &city.location;
1201                            if let (Some(lat), Some(lon)) = (location.latitude, location.longitude)
1202                            {
1203                                location_parts.push(format!("coords:{:.4},{:.4}", lat, lon));
1204                            }
1205
1206                            // Note: Full MaxMind geo-parsing requires accessing complex nested structures
1207                            // For now, we focus on coordinates which are most reliable
1208                            if location_parts.is_empty() {
1209                                None
1210                            } else {
1211                                Some(location_parts.join("|"))
1212                            }
1213                        }
1214                        Ok(None) => {
1215                            tracing::debug!("MaxMind lookup returned no data for {}", ip);
1216                            None
1217                        }
1218                        Err(e) => {
1219                            tracing::debug!("MaxMind decode failed for {}: {}", ip, e);
1220                            None
1221                        }
1222                    },
1223                    Err(e) => {
1224                        tracing::debug!("MaxMind lookup failed for {}: {}", ip, e);
1225                        None
1226                    }
1227                }
1228            }
1229            Err(e) => {
1230                tracing::warn!("Failed to open MaxMind database: {}", e);
1231                None
1232            }
1233        }
1234    }
1235}
1236
1237/// Calculates session risk scores based on device, location, and behavioral factors.
1238///
1239/// Risk scores range from 0 (no risk) to 100 (maximum risk) and are used by
1240/// [`SessionSecurityPolicy`] to trigger automatic session suspension or
1241/// step-up authentication.
1242pub struct RiskCalculator;
1243
1244impl Default for RiskCalculator {
1245    fn default() -> Self {
1246        Self::new()
1247    }
1248}
1249
1250impl RiskCalculator {
1251    pub fn new() -> Self {
1252        Self
1253    }
1254
1255    /// Calculate risk score (0-100) for a session
1256    pub fn calculate_risk(
1257        &self,
1258        device_info: &DeviceInfo,
1259        metadata: &RequestMetadata,
1260        _session_history: &[Session],
1261        threat_intel_manager: Option<&ThreatFeedManager>,
1262    ) -> u8 {
1263        let mut risk_score = 0u8;
1264
1265        // Check for new device
1266        if !device_info.is_trusted {
1267            risk_score += 20;
1268        }
1269
1270        // Check IP reputation (simplified)
1271        if let Some(ip) = &metadata.ip_address
1272            && self.is_suspicious_ip(ip, threat_intel_manager)
1273        {
1274            risk_score += 30;
1275        }
1276
1277        // Check geolocation anomalies
1278        if let Some(location) = &metadata.geolocation {
1279            let mut geo_risk = 0;
1280
1281            // Check country-based risk
1282            if let Some(country) = &location.country {
1283                let country_lower = country.to_lowercase();
1284
1285                // High-risk indicators in country names
1286                let high_risk_countries =
1287                    ["tor", "anonymous", "vpn", "proxy", "hosting", "datacenter"];
1288
1289                for indicator in &high_risk_countries {
1290                    if country_lower.contains(indicator) {
1291                        geo_risk += 30;
1292                        break;
1293                    }
1294                }
1295
1296                // Real threat intelligence integration for geographic risk
1297                geo_risk += self.assess_country_threat_level(&country_lower) as u8;
1298
1299                // Check against known high-risk hosting providers
1300                let elevated_risk_patterns = ["cloud", "aws", "azure", "gcp"];
1301                for pattern in &elevated_risk_patterns {
1302                    if country_lower.contains(pattern) {
1303                        geo_risk += 20;
1304                        break;
1305                    }
1306                }
1307            }
1308
1309            // Check for impossible travel (basic latitude/longitude analysis)
1310            if let (Some(lat), Some(lon)) = (location.latitude, location.longitude) {
1311                // Validate coordinate ranges
1312                if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
1313                    geo_risk += 25; // Invalid coordinates are suspicious
1314                }
1315
1316                // Detect datacenter coordinates (often round numbers)
1317                if (lat * 100.0).fract().abs() < 0.01 && (lon * 100.0).fract().abs() < 0.01 {
1318                    geo_risk += 15; // Suspiciously precise coordinates
1319                }
1320            }
1321
1322            // Region-based analysis
1323            if let Some(region) = &location.region {
1324                let region_lower = region.to_lowercase();
1325                if region_lower.contains("hosting") || region_lower.contains("datacenter") {
1326                    geo_risk += 20;
1327                }
1328            }
1329
1330            // City-based analysis
1331            if let Some(city) = &location.city {
1332                let city_lower = city.to_lowercase();
1333                if city_lower.contains("server") || city_lower.contains("datacenter") {
1334                    geo_risk += 15;
1335                }
1336            }
1337
1338            risk_score += geo_risk;
1339        }
1340
1341        // Check time-based anomalies
1342        // - Unusual login times
1343        // - Rapid geographic movement
1344        // - Multiple simultaneous sessions
1345
1346        risk_score.min(100)
1347    }
1348
1349    /// Check if IP address is suspicious
1350    fn is_suspicious_ip(&self, ip: &str, threat_intel_manager: Option<&ThreatFeedManager>) -> bool {
1351        use std::net::IpAddr;
1352        use std::str::FromStr;
1353
1354        // Parse IP address for analysis
1355        if let Ok(ip_addr) = IpAddr::from_str(ip) {
1356            match ip_addr {
1357                IpAddr::V4(ipv4) => {
1358                    let octets = ipv4.octets();
1359
1360                    // Real threat intelligence feeds integration
1361                    if self.check_malicious_ip_feeds(&ipv4, threat_intel_manager) {
1362                        return true;
1363                    }
1364
1365                    // Suspicious hosting ranges (example patterns)
1366                    let suspicious_ranges = [
1367                        // Known VPN/hosting provider ranges (examples)
1368                        (5, 0, 0, 0, 8),   // Various hosting
1369                        (31, 0, 0, 0, 8),  // Various hosting
1370                        (37, 0, 0, 0, 8),  // Various hosting
1371                        (46, 0, 0, 0, 8),  // Various hosting
1372                        (95, 0, 0, 0, 8),  // Various hosting
1373                        (185, 0, 0, 0, 8), // Various hosting
1374                    ];
1375
1376                    for (net, _, _, _, _) in &suspicious_ranges {
1377                        if octets[0] == *net {
1378                            return true;
1379                        }
1380                    }
1381
1382                    // Check for reserved/special ranges that shouldn't be used
1383                    if octets[0] == 0 ||                              // "This" network
1384                       (octets[0] == 100 && octets[1] >= 64 && octets[1] <= 127) || // Carrier-grade NAT
1385                       (octets[0] == 169 && octets[1] == 254) ||      // Link-local
1386                       (octets[0] >= 224 && octets[0] <= 239) ||      // Multicast
1387                       (octets[0] >= 240)
1388                    {
1389                        // Reserved/experimental
1390                        return true;
1391                    }
1392
1393                    // Detect potential port scans (suspicious patterns in last octet)
1394                    if octets[3] == 0 || octets[3] == 255 {
1395                        return true;
1396                    }
1397
1398                    // Real specialized databases for proxy/VPN detection
1399                    if self.check_proxy_vpn_databases(&ipv4) {
1400                        return true;
1401                    }
1402
1403                    // Fallback proxy port pattern detection
1404                    let proxy_ports_in_ip = [
1405                        80, 443, 8080, 3128, 1080, 8000, 8888, 9050, // Common proxy ports
1406                    ];
1407
1408                    for &port in &proxy_ports_in_ip {
1409                        if octets[2] == (port / 256) as u8 && octets[3] == (port % 256) as u8 {
1410                            return true;
1411                        }
1412                    }
1413
1414                    false
1415                }
1416                IpAddr::V6(ipv6) => {
1417                    let segments = ipv6.segments();
1418
1419                    // Real-time Tor exit node detection
1420                    if self.check_tor_exit_nodes(&ipv6) {
1421                        return true;
1422                    }
1423
1424                    // Fallback static range checks
1425                    if segments[0] == 0x2001 && segments[1] == 0x67c {
1426                        // Example known Tor range (static fallback)
1427                        return true;
1428                    }
1429
1430                    // Suspicious IPv6 patterns (overly sequential or predictable)
1431                    let mut sequential_count = 0;
1432                    for i in 1..segments.len() {
1433                        if segments[i] == segments[i - 1] + 1 {
1434                            sequential_count += 1;
1435                        }
1436                    }
1437                    if sequential_count >= 4 {
1438                        // Too many sequential segments
1439                        return true;
1440                    }
1441
1442                    // Check for tunnel brokers (often used for anonymity)
1443                    if segments[0] == 0x2001 && segments[1] == 0x470 {
1444                        // Hurricane Electric
1445                        return true;
1446                    }
1447
1448                    false
1449                }
1450            }
1451        } else {
1452            true // Invalid IP format is suspicious
1453        }
1454    }
1455
1456    /// Assess threat level for a country using threat intelligence feeds
1457    fn assess_country_threat_level(&self, country: &str) -> u32 {
1458        use std::path::Path;
1459
1460        // Load country threat intelligence (configurable path)
1461        let threat_db_path = std::env::var("COUNTRY_THREAT_DB_PATH")
1462            .unwrap_or_else(|_| "country-threats.csv".to_string());
1463
1464        if Path::new(&threat_db_path).exists() {
1465            // Real implementation: Load from CSV threat feed
1466            if let Ok(contents) = std::fs::read_to_string(&threat_db_path) {
1467                let mut csv_reader = csv::Reader::from_reader(contents.as_bytes());
1468
1469                for result in csv_reader.records() {
1470                    if let Ok(record) = result
1471                        && record.len() >= 2
1472                    {
1473                        let threat_country = record[0].to_lowercase();
1474                        if let Ok(risk_score) = record[1].parse::<u32>()
1475                            && country.contains(&threat_country)
1476                        {
1477                            tracing::debug!(
1478                                "Country threat match: {} -> risk {}",
1479                                country,
1480                                risk_score
1481                            );
1482                            return risk_score;
1483                        }
1484                    }
1485                }
1486            }
1487        }
1488
1489        // No additional risk from country name patterns
1490        0 // No additional risk
1491    }
1492
1493    /// Check IP against malicious IP threat intelligence feeds
1494    fn check_malicious_ip_feeds(
1495        &self,
1496        ip: &std::net::Ipv4Addr,
1497        threat_intel_manager: Option<&ThreatFeedManager>,
1498    ) -> bool {
1499        // Try automated threat intelligence first
1500        if let Some(threat_manager) = threat_intel_manager {
1501            return threat_manager.is_malicious_ip(&std::net::IpAddr::V4(*ip));
1502        }
1503
1504        // Fall back to manual file checking for backward compatibility
1505        use std::path::Path;
1506
1507        // Load malicious IP feeds (multiple sources)
1508        let feed_paths = [
1509            std::env::var("MALICIOUS_IPS_DB_PATH")
1510                .unwrap_or_else(|_| "malicious-ips.txt".to_string()),
1511            std::env::var("BOTNET_IPS_DB_PATH").unwrap_or_else(|_| "botnet-ips.txt".to_string()),
1512            std::env::var("TOR_EXIT_NODES_DB_PATH").unwrap_or_else(|_| "tor-exits.txt".to_string()),
1513        ];
1514
1515        for feed_path in &feed_paths {
1516            if Path::new(feed_path).exists()
1517                && let Ok(contents) = std::fs::read_to_string(feed_path)
1518            {
1519                for line in contents.lines() {
1520                    let line = line.trim();
1521                    if line.is_empty() || line.starts_with('#') {
1522                        continue;
1523                    }
1524
1525                    // Check exact IP match
1526                    if line == ip.to_string() {
1527                        tracing::warn!("Malicious IP detected: {} (source: {})", ip, feed_path);
1528                        return true;
1529                    }
1530
1531                    // Check CIDR network match
1532                    if line.contains('/')
1533                        && let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1534                        && network.contains(*ip)
1535                    {
1536                        tracing::warn!(
1537                            "Malicious network detected: {} in {} (source: {})",
1538                            ip,
1539                            network,
1540                            feed_path
1541                        );
1542                        return true;
1543                    }
1544                }
1545            }
1546        }
1547
1548        false
1549    }
1550
1551    /// Check against specialized proxy/VPN databases
1552    fn check_proxy_vpn_databases(&self, ip: &std::net::Ipv4Addr) -> bool {
1553        use std::path::Path;
1554
1555        // Multiple specialized databases for proxy/VPN detection
1556        let db_sources = [
1557            ("VPN_DATABASE_PATH", "vpn-ranges.txt"),
1558            ("PROXY_DATABASE_PATH", "proxy-ips.txt"),
1559            ("DATACENTER_DATABASE_PATH", "datacenter-ranges.txt"),
1560            ("HOSTING_DATABASE_PATH", "hosting-providers.txt"),
1561        ];
1562
1563        for (env_var, default_file) in &db_sources {
1564            let db_path = std::env::var(env_var).unwrap_or_else(|_| default_file.to_string());
1565
1566            if Path::new(&db_path).exists()
1567                && let Ok(contents) = std::fs::read_to_string(&db_path)
1568            {
1569                for line in contents.lines() {
1570                    let line = line.trim();
1571                    if line.is_empty() || line.starts_with('#') {
1572                        continue;
1573                    }
1574
1575                    // Support multiple formats: IP, CIDR, IP ranges
1576                    if line.contains('/') {
1577                        // CIDR notation
1578                        if let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1579                            && network.contains(*ip)
1580                        {
1581                            tracing::info!(
1582                                "Proxy/VPN detected: {} in {} (source: {})",
1583                                ip,
1584                                network,
1585                                db_path
1586                            );
1587                            return true;
1588                        }
1589                    } else if line.contains('-') {
1590                        // IP range format: 1.2.3.4-1.2.3.10
1591                        let parts: Vec<&str> = line.split('-').collect();
1592                        if parts.len() == 2
1593                            && let (Ok(start_ip), Ok(end_ip)) = (
1594                                parts[0].trim().parse::<std::net::Ipv4Addr>(),
1595                                parts[1].trim().parse::<std::net::Ipv4Addr>(),
1596                            )
1597                        {
1598                            let ip_u32 = u32::from(*ip);
1599                            let start_u32 = u32::from(start_ip);
1600                            let end_u32 = u32::from(end_ip);
1601
1602                            if ip_u32 >= start_u32 && ip_u32 <= end_u32 {
1603                                tracing::info!(
1604                                    "Proxy/VPN range detected: {} in {}-{} (source: {})",
1605                                    ip,
1606                                    start_ip,
1607                                    end_ip,
1608                                    db_path
1609                                );
1610                                return true;
1611                            }
1612                        }
1613                    } else if line == ip.to_string() {
1614                        // Exact IP match
1615                        tracing::info!("Proxy/VPN exact match: {} (source: {})", ip, db_path);
1616                        return true;
1617                    }
1618                }
1619            }
1620        }
1621
1622        false
1623    }
1624
1625    /// Check against real-time Tor exit node lists
1626    fn check_tor_exit_nodes(&self, ip: &std::net::Ipv6Addr) -> bool {
1627        use std::path::Path;
1628
1629        // Real-time Tor exit node detection
1630        let tor_db_path = std::env::var("TOR_EXIT_NODES_IPV6_PATH")
1631            .unwrap_or_else(|_| "tor-exits-ipv6.txt".to_string());
1632
1633        if Path::new(&tor_db_path).exists()
1634            && let Ok(contents) = std::fs::read_to_string(&tor_db_path)
1635        {
1636            for line in contents.lines() {
1637                let line = line.trim();
1638                if line.is_empty() || line.starts_with('#') {
1639                    continue;
1640                }
1641
1642                // Check IPv6 exact match
1643                if let Ok(tor_ip) = line.parse::<std::net::Ipv6Addr>()
1644                    && tor_ip == *ip
1645                {
1646                    tracing::warn!("Tor exit node detected: {}", ip);
1647                    return true;
1648                }
1649
1650                // Check IPv6 network match
1651                if line.contains('/')
1652                    && let Ok(network) = line.parse::<ipnetwork::Ipv6Network>()
1653                    && network.contains(*ip)
1654                {
1655                    tracing::warn!("Tor exit network detected: {} in {}", ip, network);
1656                    return true;
1657                }
1658            }
1659        }
1660
1661        // Also check IPv4-mapped IPv6 addresses for Tor
1662        if let Some(ipv4) = ip.to_ipv4() {
1663            let tor_v4_path = std::env::var("TOR_EXIT_NODES_IPV4_PATH")
1664                .unwrap_or_else(|_| "tor-exits-ipv4.txt".to_string());
1665
1666            if Path::new(&tor_v4_path).exists()
1667                && let Ok(contents) = std::fs::read_to_string(&tor_v4_path)
1668            {
1669                for line in contents.lines() {
1670                    let line = line.trim();
1671                    if line == ipv4.to_string() {
1672                        tracing::warn!("Tor exit node detected (IPv4-mapped): {}", ip);
1673                        return true;
1674                    }
1675                }
1676            }
1677        }
1678
1679        false
1680    }
1681}
1682
1683impl Default for SessionConfig {
1684    fn default() -> Self {
1685        Self {
1686            default_duration: Duration::from_secs(3600), // 1 hour
1687            max_duration: Duration::from_secs(86400),    // 24 hours
1688            idle_timeout: Duration::from_secs(1800),     // 30 minutes
1689            rotate_on_privilege_escalation: true,
1690            rotate_periodically: true,
1691            rotation_interval: Duration::from_secs(1800), // 30 minutes
1692            max_concurrent_sessions: Some(5),
1693            track_device_fingerprints: true,
1694            enforce_geographic_restrictions: false,
1695            allowed_countries: vec![],
1696            security_policy: SessionSecurityPolicy::default(),
1697        }
1698    }
1699}
1700
1701impl Default for SessionSecurityPolicy {
1702    fn default() -> Self {
1703        Self {
1704            require_mfa_for_new_devices: true,
1705            require_reauth_for_sensitive_ops: true,
1706            reauth_timeout: Duration::from_secs(300), // 5 minutes
1707            max_risk_score: 70,
1708            auto_suspend_suspicious: true,
1709            verify_location_changes: true,
1710            limit_concurrent_sessions: true,
1711        }
1712    }
1713}
1714
1715#[cfg(test)]
1716mod tests {
1717    use super::*;
1718
1719    #[test]
1720    fn test_device_fingerprint_generation() {
1721        let generator = DeviceFingerprintGenerator::new();
1722        let metadata = RequestMetadata {
1723            user_agent: Some("Mozilla/5.0".to_string()),
1724            ..Default::default()
1725        };
1726
1727        let fp1 = generator.generate_fingerprint(&metadata);
1728        let fp2 = generator.generate_fingerprint(&metadata);
1729
1730        assert_eq!(fp1, fp2);
1731        assert!(fp1.starts_with("fp_"));
1732    }
1733
1734    #[test]
1735    fn test_risk_calculation() {
1736        let calculator = RiskCalculator::new();
1737        let device_info = DeviceInfo {
1738            fingerprint: "test".to_string(),
1739            device_type: "desktop".to_string(),
1740            operating_system: None,
1741            browser: None,
1742            screen_resolution: None,
1743            timezone: None,
1744            language: None,
1745            is_trusted: false,
1746            device_name: None,
1747            is_mobile: false,
1748            ip_address: None,
1749        };
1750
1751        let metadata = RequestMetadata::default();
1752        let history = vec![];
1753
1754        let risk = calculator.calculate_risk(&device_info, &metadata, &history, None);
1755        assert!(risk >= 20); // Should have at least 20 for untrusted device
1756    }
1757
1758    /// Minimal in-memory session storage for tests.
1759    #[derive(Default)]
1760    struct TestSessionStorage {
1761        sessions: std::sync::Mutex<std::collections::HashMap<String, Session>>,
1762    }
1763
1764    #[async_trait::async_trait]
1765    impl SessionStorage for TestSessionStorage {
1766        async fn create_session(&self, session: &Session) -> Result<()> {
1767            self.sessions
1768                .lock()
1769                .unwrap()
1770                .insert(session.id.clone(), session.clone());
1771            Ok(())
1772        }
1773        async fn get_session(&self, id: &str) -> Result<Option<Session>> {
1774            Ok(self.sessions.lock().unwrap().get(id).cloned())
1775        }
1776        async fn update_session(&self, session: &Session) -> Result<()> {
1777            self.create_session(session).await
1778        }
1779        async fn delete_session(&self, id: &str) -> Result<()> {
1780            self.sessions.lock().unwrap().remove(id);
1781            Ok(())
1782        }
1783        async fn get_user_sessions(&self, user_id: &str) -> Result<Vec<Session>> {
1784            Ok(self
1785                .sessions
1786                .lock()
1787                .unwrap()
1788                .values()
1789                .filter(|s| s.user_id == user_id)
1790                .cloned()
1791                .collect())
1792        }
1793        async fn count_active_sessions(&self, _user_id: &str) -> Result<u32> {
1794            Ok(0)
1795        }
1796        async fn cleanup_expired_sessions(&self) -> Result<u32> {
1797            Ok(0)
1798        }
1799        async fn find_sessions_by_device(&self, _fp: &str) -> Result<Vec<Session>> {
1800            Ok(vec![])
1801        }
1802        async fn find_sessions_by_ip(&self, _ip: &str) -> Result<Vec<Session>> {
1803            Ok(vec![])
1804        }
1805    }
1806
1807    #[tokio::test]
1808    async fn revoke_all_user_sessions_ends_every_live_session_whatever_its_state() {
1809        use crate::audit::{AuditLogger, TracingAuditStorage};
1810        let manager = SessionManager::new(
1811            TestSessionStorage::default(),
1812            SessionConfigBuilder::for_web_app().build(),
1813            AuditLogger::new(TracingAuditStorage),
1814        );
1815        let live_states = [
1816            SessionState::Active,
1817            SessionState::Suspended,
1818            SessionState::RequiresMfa,
1819            SessionState::RequiresReauth,
1820            SessionState::RequiresRotation,
1821            SessionState::HighRisk,
1822        ];
1823        let mut ids = Vec::new();
1824        for state in live_states.iter().cloned() {
1825            let mut s = Session::new("victim", Duration::from_secs(3600));
1826            s.state = state;
1827            manager.storage.create_session(&s).await.unwrap();
1828            ids.push(s.id);
1829        }
1830        // a terminal session is left as it is and not counted; another user's session is untouched
1831        let mut expired = Session::new("victim", Duration::from_secs(3600));
1832        expired.state = SessionState::Expired;
1833        manager.storage.create_session(&expired).await.unwrap();
1834        let other = Session::new("someone-else", Duration::from_secs(3600));
1835        manager.storage.create_session(&other).await.unwrap();
1836
1837        let revoked = manager.revoke_all_user_sessions("victim").await.unwrap();
1838        assert_eq!(revoked as usize, live_states.len());
1839        for (id, state) in ids.iter().zip(live_states.iter()) {
1840            let after = manager.storage.get_session(id).await.unwrap().unwrap();
1841            assert_eq!(after.state, SessionState::Revoked, "was {state:?}");
1842        }
1843        let expired_after = manager
1844            .storage
1845            .get_session(&expired.id)
1846            .await
1847            .unwrap()
1848            .unwrap();
1849        assert_eq!(expired_after.state, SessionState::Expired);
1850        let other_after = manager
1851            .storage
1852            .get_session(&other.id)
1853            .await
1854            .unwrap()
1855            .unwrap();
1856        assert_eq!(other_after.state, SessionState::Active);
1857    }
1858
1859    #[test]
1860    fn test_session_config_builder_for_web_app() {
1861        let config = SessionConfigBuilder::for_web_app().build();
1862        assert_eq!(config.default_duration, Duration::from_secs(3600));
1863        assert_eq!(config.max_duration, Duration::from_secs(86400));
1864        assert_eq!(config.max_concurrent_sessions, Some(5));
1865        assert!(config.track_device_fingerprints);
1866    }
1867
1868    #[test]
1869    fn test_session_config_builder_for_api_service() {
1870        let config = SessionConfigBuilder::for_api_service().build();
1871        assert_eq!(config.default_duration, Duration::from_secs(900));
1872        assert!(config.max_concurrent_sessions.is_none());
1873        assert!(!config.track_device_fingerprints);
1874        assert!(!config.rotate_periodically);
1875    }
1876
1877    #[test]
1878    fn test_session_config_builder_for_high_security() {
1879        let config = SessionConfigBuilder::for_high_security()
1880            .allowed_countries(vec!["US".into()])
1881            .build();
1882        assert_eq!(config.default_duration, Duration::from_secs(1800));
1883        assert_eq!(config.max_concurrent_sessions, Some(1));
1884        assert!(config.enforce_geographic_restrictions);
1885        assert_eq!(config.allowed_countries, vec!["US".to_string()]);
1886        assert!(config.security_policy.require_mfa_for_new_devices);
1887    }
1888
1889    // No test here performs a real MaxMind lookup (that needs a third-party
1890    // .mmdb fixture). These cover the open path: a missing or unreadable
1891    // database must yield `None`, never a panic.
1892    #[test]
1893    fn maxmind_geolocation_none_for_missing_or_garbage_database() {
1894        let generator = DeviceFingerprintGenerator::new();
1895        let ip = std::net::Ipv4Addr::new(8, 8, 8, 8);
1896        let dir = tempfile::tempdir().unwrap();
1897
1898        let missing = dir.path().join("missing.mmdb");
1899        assert_eq!(
1900            generator.lookup_maxmind_geolocation_at(missing.to_str().unwrap(), &ip),
1901            None
1902        );
1903
1904        let garbage_inputs: [(&str, &[u8]); 3] = [
1905            ("empty.mmdb", b""),
1906            ("garbage.mmdb", b"this is not a MaxMind database at all"),
1907            ("truncated.mmdb", b"\xAB\xCD\xEFMaxMind.com\x00"),
1908        ];
1909        for (name, bytes) in garbage_inputs {
1910            let path = dir.path().join(name);
1911            std::fs::write(&path, bytes).unwrap();
1912            // Positive control: see the twin test in secure_session_config.rs.
1913            assert!(
1914                maxminddb::Reader::open_readfile(&path).is_err(),
1915                "{name}: maxminddb accepted garbage bytes"
1916            );
1917            assert_eq!(
1918                generator.lookup_maxmind_geolocation_at(path.to_str().unwrap(), &ip),
1919                None,
1920                "{name}"
1921            );
1922        }
1923    }
1924}