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                        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 of a user's sessions that are still usable, whatever their state
846    /// (active, suspended, awaiting MFA / re-authentication / rotation, high-risk). Sessions
847    /// that are already `Expired` or `Revoked` are left as they are and not counted.
848    pub async fn revoke_all_user_sessions(&self, user_id: &str) -> Result<u32> {
849        let sessions = self.storage.get_user_sessions(user_id).await?;
850        let mut revoked_count = 0;
851
852        for mut session in sessions {
853            if !matches!(session.state, SessionState::Expired | SessionState::Revoked) {
854                session.state = SessionState::Revoked;
855                self.storage.update_session(&session).await?;
856                revoked_count += 1;
857            }
858        }
859
860        Ok(revoked_count)
861    }
862
863    /// List sessions for a user.
864    ///
865    /// When `include_inactive` is `false`, only [`SessionState::Active`]
866    /// sessions are returned.
867    ///
868    /// Prefer [`list_user_sessions`](Self::list_user_sessions) with a
869    /// [`SessionFilter`](crate::auth_operations::SessionFilter) for
870    /// self-documenting call sites.
871    pub async fn get_user_sessions(
872        &self,
873        user_id: &str,
874        include_inactive: bool,
875    ) -> Result<Vec<Session>> {
876        let mut sessions = self.storage.get_user_sessions(user_id).await?;
877
878        if !include_inactive {
879            sessions.retain(|s| s.state == SessionState::Active);
880        }
881
882        Ok(sessions)
883    }
884
885    /// List sessions for a user with a typed [`SessionFilter`](crate::auth_operations::SessionFilter).
886    ///
887    /// ```rust,ignore
888    /// use auth_framework::auth_operations::SessionFilter;
889    ///
890    /// let active = mgr.list_user_sessions(user_id, SessionFilter::ActiveOnly).await?;
891    /// ```
892    pub async fn list_user_sessions(
893        &self,
894        user_id: &str,
895        filter: crate::auth_operations::SessionFilter,
896    ) -> Result<Vec<Session>> {
897        self.get_user_sessions(user_id, filter.include_inactive())
898            .await
899    }
900
901    /// Remove all expired sessions from storage and return how many were cleaned up.
902    pub async fn cleanup_expired_sessions(&self) -> Result<u32> {
903        self.storage.cleanup_expired_sessions().await
904    }
905
906    /// Compute a device fingerprint from the request metadata (IP, User-Agent, etc.).
907    pub fn generate_device_fingerprint(&self, metadata: &RequestMetadata) -> String {
908        self.fingerprint_generator.generate_fingerprint(metadata)
909    }
910
911    /// Check whether `metadata` produces a fingerprint matching the session's stored value.
912    pub fn validate_device_fingerprint(
913        &self,
914        session: &Session,
915        metadata: &RequestMetadata,
916    ) -> bool {
917        let current_fingerprint = self.fingerprint_generator.generate_fingerprint(metadata);
918        current_fingerprint == session.device_info.fingerprint
919    }
920
921    /// Suspend suspicious sessions
922    pub async fn suspend_session(&self, session_id: &str, reason: &str) -> Result<()> {
923        if let Some(mut session) = self.storage.get_session(session_id).await? {
924            session.state = SessionState::Suspended;
925            session
926                .security_metadata
927                .security_flags
928                .push(SecurityFlag::SuspiciousActivity);
929
930            self.storage.update_session(&session).await?;
931
932            // Log suspension
933            let mut details = HashMap::new();
934            details.insert("suspension_reason".to_string(), reason.to_string());
935
936            self.audit_logger
937                .log_event(
938                    crate::audit::AuditEvent::builder(
939                        crate::audit::AuditEventType::AccountLocked,
940                        format!("Session suspended: {}", reason),
941                    )
942                    .user_id(session.user_id)
943                    .session_id(session_id)
944                    .outcome(crate::audit::EventOutcome::Success)
945                    .risk_level(crate::audit::RiskLevel::High)
946                    .details(details)
947                    .with_actor("system", "security_monitor")
948                    .build(),
949                )
950                .await?;
951        }
952        Ok(())
953    }
954
955    /// Update session data
956    pub async fn update_session_data(
957        &self,
958        session_id: &str,
959        key: &str,
960        value: &str,
961    ) -> Result<()> {
962        if let Some(mut session) = self.storage.get_session(session_id).await? {
963            session.data.insert(key.to_string(), value.to_string());
964            session.last_accessed = SystemTime::now();
965            self.storage.update_session(&session).await?;
966        }
967        Ok(())
968    }
969
970    /// Generate a new session ID
971    fn generate_session_id(&self) -> String {
972        format!("sess_{}", uuid::Uuid::new_v4())
973    }
974
975    /// Check if session should be rotated
976    fn should_rotate_session(&self, session: &Session) -> bool {
977        if !self.config.rotate_periodically {
978            return false;
979        }
980
981        let session_age = SystemTime::now()
982            .duration_since(session.created_at)
983            .unwrap_or_default();
984
985        session_age > self.config.rotation_interval
986    }
987
988    /// Get user session history for risk calculation
989    async fn get_user_session_history(&self, user_id: &str) -> Result<Vec<Session>> {
990        // This would typically be a more sophisticated query
991        // For now, just return recent sessions
992        self.storage.get_user_sessions(user_id).await
993    }
994}
995
996/// Generates device fingerprints for session tracking and anomaly detection.
997///
998/// Fingerprints are derived from user-agent strings and other request metadata
999/// to identify returning devices without storing sensitive client information.
1000pub struct DeviceFingerprintGenerator;
1001
1002impl Default for DeviceFingerprintGenerator {
1003    fn default() -> Self {
1004        Self::new()
1005    }
1006}
1007
1008impl DeviceFingerprintGenerator {
1009    pub fn new() -> Self {
1010        Self
1011    }
1012
1013    /// Generate device fingerprint from request metadata
1014    pub fn generate_fingerprint(&self, metadata: &RequestMetadata) -> String {
1015        let mut fingerprint_data = Vec::new();
1016
1017        if let Some(ua) = &metadata.user_agent {
1018            fingerprint_data.push(ua.clone());
1019        }
1020
1021        // Comprehensive device fingerprinting implementation
1022        self.add_advanced_fingerprinting_data(&mut fingerprint_data, metadata);
1023
1024        let fingerprint_string = fingerprint_data.join("|");
1025        format!("fp_{:x}", crc32fast::hash(fingerprint_string.as_bytes()))
1026    }
1027
1028    /// Add advanced fingerprinting data based on available metadata
1029    fn add_advanced_fingerprinting_data(
1030        &self,
1031        fingerprint_data: &mut Vec<String>,
1032        metadata: &RequestMetadata,
1033    ) {
1034        // Screen characteristics (if available)
1035        if let Some(ref ip) = metadata.ip_address {
1036            // Extract geographical and ISP information from IP
1037            fingerprint_data.push(format!("geo:{}", self.get_ip_geolocation(ip)));
1038        }
1039
1040        // Browser/client characteristics
1041        fingerprint_data.push(format!("lang:{}", self.get_system_language()));
1042        fingerprint_data.push(format!("tz:{}", self.get_timezone_offset()));
1043        fingerprint_data.push(format!("hw:{}", self.get_hardware_concurrency()));
1044
1045        // Network characteristics
1046        fingerprint_data.push(format!("conn:{}", self.get_connection_info()));
1047
1048        // Additional entropy sources
1049        fingerprint_data.push(format!("caps:{}", self.get_client_capabilities()));
1050    }
1051
1052    /// Get IP geolocation information for fingerprinting
1053    fn get_ip_geolocation(&self, ip: &str) -> String {
1054        use std::net::IpAddr;
1055        use std::str::FromStr;
1056
1057        // Parse IP address for classification
1058        if let Ok(ip_addr) = IpAddr::from_str(ip) {
1059            match ip_addr {
1060                IpAddr::V4(ipv4) => {
1061                    let octets = ipv4.octets();
1062
1063                    // RFC 1918 private networks
1064                    if (octets[0] == 10)
1065                        || (octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31)
1066                        || (octets[0] == 192 && octets[1] == 168)
1067                    {
1068                        return "private_rfc1918".to_string();
1069                    }
1070
1071                    // Loopback
1072                    if octets[0] == 127 {
1073                        return "loopback".to_string();
1074                    }
1075
1076                    // Link-local (169.254.x.x)
1077                    if octets[0] == 169 && octets[1] == 254 {
1078                        return "link_local".to_string();
1079                    }
1080
1081                    // Multicast
1082                    if octets[0] >= 224 && octets[0] <= 239 {
1083                        return "multicast".to_string();
1084                    }
1085
1086                    // Known public DNS servers
1087                    match (octets[0], octets[1], octets[2], octets[3]) {
1088                        (8, 8, 8, 8) | (8, 8, 4, 4) => "google_dns".to_string(),
1089                        (1, 1, 1, 1) | (1, 0, 0, 1) => "cloudflare_dns".to_string(),
1090                        (208, 67, 222, 222) | (208, 67, 220, 220) => "opendns".to_string(),
1091                        _ => {
1092                            // Real MaxMind GeoIP2 database integration
1093                            self.lookup_maxmind_geolocation(&ipv4).unwrap_or_else(|| {
1094                                // Fallback to basic regional classification
1095                                match octets[0] {
1096                                    1..=23 => "apnic_region".to_string(),    // APNIC (Asia-Pacific)
1097                                    24..=49 => "arin_region".to_string(),    // ARIN (North America)
1098                                    50..=99 => "ripe_region".to_string(), // RIPE (Europe/Middle East)
1099                                    100..=127 => "mixed_region".to_string(), // Various registries
1100                                    128..=191 => "arin_region".to_string(), // ARIN
1101                                    192..=223 => "ripe_apnic_region".to_string(), // RIPE/APNIC
1102                                    _ => format!("public_class_{}", octets[0] / 64),
1103                                }
1104                            })
1105                        }
1106                    }
1107                }
1108                IpAddr::V6(ipv6) => {
1109                    let segments = ipv6.segments();
1110
1111                    // IPv6 loopback
1112                    if ipv6.is_loopback() {
1113                        return "ipv6_loopback".to_string();
1114                    }
1115
1116                    // IPv6 link-local (fe80::/10)
1117                    if segments[0] & 0xffc0 == 0xfe80 {
1118                        return "ipv6_link_local".to_string();
1119                    }
1120
1121                    // IPv6 unique local (fc00::/7)
1122                    if segments[0] & 0xfe00 == 0xfc00 {
1123                        return "ipv6_unique_local".to_string();
1124                    }
1125
1126                    // IPv6 multicast (ff00::/8)
1127                    if segments[0] & 0xff00 == 0xff00 {
1128                        return "ipv6_multicast".to_string();
1129                    }
1130
1131                    // Global unicast
1132                    format!("ipv6_global_{:x}", segments[0] / 0x1000)
1133                }
1134            }
1135        } else {
1136            "invalid_ip".to_string()
1137        }
1138    }
1139
1140    /// Get system language for fingerprinting
1141    fn get_system_language(&self) -> String {
1142        // Would be extracted from Accept-Language header or client info
1143        "en-US".to_string()
1144    }
1145
1146    /// Get timezone offset for fingerprinting
1147    fn get_timezone_offset(&self) -> String {
1148        // Would be provided by client-side JavaScript
1149        "-05:00".to_string() // EST example
1150    }
1151
1152    /// Get hardware concurrency for fingerprinting
1153    fn get_hardware_concurrency(&self) -> String {
1154        // Would be provided by client via navigator.hardwareConcurrency
1155        "4".to_string()
1156    }
1157
1158    /// Get connection information for fingerprinting
1159    fn get_connection_info(&self) -> String {
1160        // Would include connection speed, type, etc.
1161        "wifi".to_string()
1162    }
1163
1164    /// Get client capabilities for fingerprinting
1165    fn get_client_capabilities(&self) -> String {
1166        // Would include supported features, WebGL renderer, etc.
1167        "webgl2_canvas_audio".to_string()
1168    }
1169
1170    /// Lookup IP geolocation using MaxMind GeoIP2 database
1171    fn lookup_maxmind_geolocation(&self, ip: &std::net::Ipv4Addr) -> Option<String> {
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        self.lookup_maxmind_geolocation_at(&db_path, ip)
1176    }
1177
1178    /// [`Self::lookup_maxmind_geolocation`] against an explicit database path.
1179    fn lookup_maxmind_geolocation_at(
1180        &self,
1181        db_path: &str,
1182        ip: &std::net::Ipv4Addr,
1183    ) -> Option<String> {
1184        use std::path::Path;
1185
1186        if !Path::new(&db_path).exists() {
1187            tracing::warn!(
1188                "MaxMind database not found at {}, falling back to basic geolocation",
1189                db_path
1190            );
1191            return None;
1192        }
1193
1194        match maxminddb::Reader::open_readfile(db_path) {
1195            Ok(reader) => {
1196                match reader.lookup((*ip).into()) {
1197                    Ok(result) => match result.decode::<maxminddb::geoip2::City>() {
1198                        Ok(Some(city)) => {
1199                            let mut location_parts = Vec::new();
1200
1201                            // Extract location coordinates from MaxMind data
1202                            let location = &city.location;
1203                            if let (Some(lat), Some(lon)) = (location.latitude, location.longitude)
1204                            {
1205                                location_parts.push(format!("coords:{:.4},{:.4}", lat, lon));
1206                            }
1207
1208                            // Note: Full MaxMind geo-parsing requires accessing complex nested structures
1209                            // For now, we focus on coordinates which are most reliable
1210                            if location_parts.is_empty() {
1211                                None
1212                            } else {
1213                                Some(location_parts.join("|"))
1214                            }
1215                        }
1216                        Ok(None) => {
1217                            tracing::debug!("MaxMind lookup returned no data for {}", ip);
1218                            None
1219                        }
1220                        Err(e) => {
1221                            tracing::debug!("MaxMind decode failed for {}: {}", ip, e);
1222                            None
1223                        }
1224                    },
1225                    Err(e) => {
1226                        tracing::debug!("MaxMind lookup failed for {}: {}", ip, e);
1227                        None
1228                    }
1229                }
1230            }
1231            Err(e) => {
1232                tracing::warn!("Failed to open MaxMind database: {}", e);
1233                None
1234            }
1235        }
1236    }
1237}
1238
1239/// Calculates session risk scores based on device, location, and behavioral factors.
1240///
1241/// Risk scores range from 0 (no risk) to 100 (maximum risk) and are used by
1242/// [`SessionSecurityPolicy`] to trigger automatic session suspension or
1243/// step-up authentication.
1244pub struct RiskCalculator;
1245
1246impl Default for RiskCalculator {
1247    fn default() -> Self {
1248        Self::new()
1249    }
1250}
1251
1252impl RiskCalculator {
1253    pub fn new() -> Self {
1254        Self
1255    }
1256
1257    /// Calculate risk score (0-100) for a session
1258    pub fn calculate_risk(
1259        &self,
1260        device_info: &DeviceInfo,
1261        metadata: &RequestMetadata,
1262        _session_history: &[Session],
1263        threat_intel_manager: Option<&ThreatFeedManager>,
1264    ) -> u8 {
1265        let mut risk_score = 0u8;
1266
1267        // Check for new device
1268        if !device_info.is_trusted {
1269            risk_score += 20;
1270        }
1271
1272        // Check IP reputation (simplified)
1273        if let Some(ip) = &metadata.ip_address
1274            && self.is_suspicious_ip(ip, threat_intel_manager)
1275        {
1276            risk_score += 30;
1277        }
1278
1279        // Check geolocation anomalies
1280        if let Some(location) = &metadata.geolocation {
1281            let mut geo_risk = 0;
1282
1283            // Check country-based risk
1284            if let Some(country) = &location.country {
1285                let country_lower = country.to_lowercase();
1286
1287                // High-risk indicators in country names
1288                let high_risk_countries =
1289                    ["tor", "anonymous", "vpn", "proxy", "hosting", "datacenter"];
1290
1291                for indicator in &high_risk_countries {
1292                    if country_lower.contains(indicator) {
1293                        geo_risk += 30;
1294                        break;
1295                    }
1296                }
1297
1298                // Real threat intelligence integration for geographic risk
1299                geo_risk += self.assess_country_threat_level(&country_lower) as u8;
1300
1301                // Check against known high-risk hosting providers
1302                let elevated_risk_patterns = ["cloud", "aws", "azure", "gcp"];
1303                for pattern in &elevated_risk_patterns {
1304                    if country_lower.contains(pattern) {
1305                        geo_risk += 20;
1306                        break;
1307                    }
1308                }
1309            }
1310
1311            // Check for impossible travel (basic latitude/longitude analysis)
1312            if let (Some(lat), Some(lon)) = (location.latitude, location.longitude) {
1313                // Validate coordinate ranges
1314                if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
1315                    geo_risk += 25; // Invalid coordinates are suspicious
1316                }
1317
1318                // Detect datacenter coordinates (often round numbers)
1319                if (lat * 100.0).fract().abs() < 0.01 && (lon * 100.0).fract().abs() < 0.01 {
1320                    geo_risk += 15; // Suspiciously precise coordinates
1321                }
1322            }
1323
1324            // Region-based analysis
1325            if let Some(region) = &location.region {
1326                let region_lower = region.to_lowercase();
1327                if region_lower.contains("hosting") || region_lower.contains("datacenter") {
1328                    geo_risk += 20;
1329                }
1330            }
1331
1332            // City-based analysis
1333            if let Some(city) = &location.city {
1334                let city_lower = city.to_lowercase();
1335                if city_lower.contains("server") || city_lower.contains("datacenter") {
1336                    geo_risk += 15;
1337                }
1338            }
1339
1340            risk_score += geo_risk;
1341        }
1342
1343        // Check time-based anomalies
1344        // - Unusual login times
1345        // - Rapid geographic movement
1346        // - Multiple simultaneous sessions
1347
1348        risk_score.min(100)
1349    }
1350
1351    /// Check if IP address is suspicious
1352    fn is_suspicious_ip(&self, ip: &str, threat_intel_manager: Option<&ThreatFeedManager>) -> bool {
1353        use std::net::IpAddr;
1354        use std::str::FromStr;
1355
1356        // Parse IP address for analysis
1357        if let Ok(ip_addr) = IpAddr::from_str(ip) {
1358            match ip_addr {
1359                IpAddr::V4(ipv4) => {
1360                    let octets = ipv4.octets();
1361
1362                    // Real threat intelligence feeds integration
1363                    if self.check_malicious_ip_feeds(&ipv4, threat_intel_manager) {
1364                        return true;
1365                    }
1366
1367                    // Suspicious hosting ranges (example patterns)
1368                    let suspicious_ranges = [
1369                        // Known VPN/hosting provider ranges (examples)
1370                        (5, 0, 0, 0, 8),   // Various hosting
1371                        (31, 0, 0, 0, 8),  // Various hosting
1372                        (37, 0, 0, 0, 8),  // Various hosting
1373                        (46, 0, 0, 0, 8),  // Various hosting
1374                        (95, 0, 0, 0, 8),  // Various hosting
1375                        (185, 0, 0, 0, 8), // Various hosting
1376                    ];
1377
1378                    for (net, _, _, _, _) in &suspicious_ranges {
1379                        if octets[0] == *net {
1380                            return true;
1381                        }
1382                    }
1383
1384                    // Check for reserved/special ranges that shouldn't be used
1385                    if octets[0] == 0 ||                              // "This" network
1386                       (octets[0] == 100 && octets[1] >= 64 && octets[1] <= 127) || // Carrier-grade NAT
1387                       (octets[0] == 169 && octets[1] == 254) ||      // Link-local
1388                       (octets[0] >= 224 && octets[0] <= 239) ||      // Multicast
1389                       (octets[0] >= 240)
1390                    {
1391                        // Reserved/experimental
1392                        return true;
1393                    }
1394
1395                    // Detect potential port scans (suspicious patterns in last octet)
1396                    if octets[3] == 0 || octets[3] == 255 {
1397                        return true;
1398                    }
1399
1400                    // Real specialized databases for proxy/VPN detection
1401                    if self.check_proxy_vpn_databases(&ipv4) {
1402                        return true;
1403                    }
1404
1405                    // Fallback proxy port pattern detection
1406                    let proxy_ports_in_ip = [
1407                        80, 443, 8080, 3128, 1080, 8000, 8888, 9050, // Common proxy ports
1408                    ];
1409
1410                    for &port in &proxy_ports_in_ip {
1411                        if octets[2] == (port / 256) as u8 && octets[3] == (port % 256) as u8 {
1412                            return true;
1413                        }
1414                    }
1415
1416                    false
1417                }
1418                IpAddr::V6(ipv6) => {
1419                    let segments = ipv6.segments();
1420
1421                    // Real-time Tor exit node detection
1422                    if self.check_tor_exit_nodes(&ipv6) {
1423                        return true;
1424                    }
1425
1426                    // Fallback static range checks
1427                    if segments[0] == 0x2001 && segments[1] == 0x67c {
1428                        // Example known Tor range (static fallback)
1429                        return true;
1430                    }
1431
1432                    // Suspicious IPv6 patterns (overly sequential or predictable)
1433                    let mut sequential_count = 0;
1434                    for i in 1..segments.len() {
1435                        if segments[i] == segments[i - 1] + 1 {
1436                            sequential_count += 1;
1437                        }
1438                    }
1439                    if sequential_count >= 4 {
1440                        // Too many sequential segments
1441                        return true;
1442                    }
1443
1444                    // Check for tunnel brokers (often used for anonymity)
1445                    if segments[0] == 0x2001 && segments[1] == 0x470 {
1446                        // Hurricane Electric
1447                        return true;
1448                    }
1449
1450                    false
1451                }
1452            }
1453        } else {
1454            true // Invalid IP format is suspicious
1455        }
1456    }
1457
1458    /// Assess threat level for a country using threat intelligence feeds
1459    fn assess_country_threat_level(&self, country: &str) -> u32 {
1460        use std::path::Path;
1461
1462        // Load country threat intelligence (configurable path)
1463        let threat_db_path = std::env::var("COUNTRY_THREAT_DB_PATH")
1464            .unwrap_or_else(|_| "country-threats.csv".to_string());
1465
1466        if Path::new(&threat_db_path).exists() {
1467            // Real implementation: Load from CSV threat feed
1468            if let Ok(contents) = std::fs::read_to_string(&threat_db_path) {
1469                let mut csv_reader = csv::Reader::from_reader(contents.as_bytes());
1470
1471                for result in csv_reader.records() {
1472                    if let Ok(record) = result
1473                        && record.len() >= 2
1474                    {
1475                        let threat_country = record[0].to_lowercase();
1476                        if let Ok(risk_score) = record[1].parse::<u32>()
1477                            && country.contains(&threat_country)
1478                        {
1479                            tracing::debug!(
1480                                "Country threat match: {} -> risk {}",
1481                                country,
1482                                risk_score
1483                            );
1484                            return risk_score;
1485                        }
1486                    }
1487                }
1488            }
1489        }
1490
1491        // No additional risk from country name patterns
1492        0 // No additional risk
1493    }
1494
1495    /// Check IP against malicious IP threat intelligence feeds
1496    fn check_malicious_ip_feeds(
1497        &self,
1498        ip: &std::net::Ipv4Addr,
1499        threat_intel_manager: Option<&ThreatFeedManager>,
1500    ) -> bool {
1501        // Try automated threat intelligence first
1502        if let Some(threat_manager) = threat_intel_manager {
1503            return threat_manager.is_malicious_ip(&std::net::IpAddr::V4(*ip));
1504        }
1505
1506        // Fall back to manual file checking for backward compatibility
1507        use std::path::Path;
1508
1509        // Load malicious IP feeds (multiple sources)
1510        let feed_paths = [
1511            std::env::var("MALICIOUS_IPS_DB_PATH")
1512                .unwrap_or_else(|_| "malicious-ips.txt".to_string()),
1513            std::env::var("BOTNET_IPS_DB_PATH").unwrap_or_else(|_| "botnet-ips.txt".to_string()),
1514            std::env::var("TOR_EXIT_NODES_DB_PATH").unwrap_or_else(|_| "tor-exits.txt".to_string()),
1515        ];
1516
1517        for feed_path in &feed_paths {
1518            if Path::new(feed_path).exists()
1519                && let Ok(contents) = std::fs::read_to_string(feed_path)
1520            {
1521                for line in contents.lines() {
1522                    let line = line.trim();
1523                    if line.is_empty() || line.starts_with('#') {
1524                        continue;
1525                    }
1526
1527                    // Check exact IP match
1528                    if line == ip.to_string() {
1529                        tracing::warn!("Malicious IP detected: {} (source: {})", ip, feed_path);
1530                        return true;
1531                    }
1532
1533                    // Check CIDR network match
1534                    if line.contains('/')
1535                        && let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1536                        && network.contains(*ip)
1537                    {
1538                        tracing::warn!(
1539                            "Malicious network detected: {} in {} (source: {})",
1540                            ip,
1541                            network,
1542                            feed_path
1543                        );
1544                        return true;
1545                    }
1546                }
1547            }
1548        }
1549
1550        false
1551    }
1552
1553    /// Check against specialized proxy/VPN databases
1554    fn check_proxy_vpn_databases(&self, ip: &std::net::Ipv4Addr) -> bool {
1555        use std::path::Path;
1556
1557        // Multiple specialized databases for proxy/VPN detection
1558        let db_sources = [
1559            ("VPN_DATABASE_PATH", "vpn-ranges.txt"),
1560            ("PROXY_DATABASE_PATH", "proxy-ips.txt"),
1561            ("DATACENTER_DATABASE_PATH", "datacenter-ranges.txt"),
1562            ("HOSTING_DATABASE_PATH", "hosting-providers.txt"),
1563        ];
1564
1565        for (env_var, default_file) in &db_sources {
1566            let db_path = std::env::var(env_var).unwrap_or_else(|_| default_file.to_string());
1567
1568            if Path::new(&db_path).exists()
1569                && let Ok(contents) = std::fs::read_to_string(&db_path)
1570            {
1571                for line in contents.lines() {
1572                    let line = line.trim();
1573                    if line.is_empty() || line.starts_with('#') {
1574                        continue;
1575                    }
1576
1577                    // Support multiple formats: IP, CIDR, IP ranges
1578                    if line.contains('/') {
1579                        // CIDR notation
1580                        if let Ok(network) = line.parse::<ipnetwork::Ipv4Network>()
1581                            && network.contains(*ip)
1582                        {
1583                            tracing::info!(
1584                                "Proxy/VPN detected: {} in {} (source: {})",
1585                                ip,
1586                                network,
1587                                db_path
1588                            );
1589                            return true;
1590                        }
1591                    } else if line.contains('-') {
1592                        // IP range format: 1.2.3.4-1.2.3.10
1593                        let parts: Vec<&str> = line.split('-').collect();
1594                        if parts.len() == 2
1595                            && let (Ok(start_ip), Ok(end_ip)) = (
1596                                parts[0].trim().parse::<std::net::Ipv4Addr>(),
1597                                parts[1].trim().parse::<std::net::Ipv4Addr>(),
1598                            )
1599                        {
1600                            let ip_u32 = u32::from(*ip);
1601                            let start_u32 = u32::from(start_ip);
1602                            let end_u32 = u32::from(end_ip);
1603
1604                            if ip_u32 >= start_u32 && ip_u32 <= end_u32 {
1605                                tracing::info!(
1606                                    "Proxy/VPN range detected: {} in {}-{} (source: {})",
1607                                    ip,
1608                                    start_ip,
1609                                    end_ip,
1610                                    db_path
1611                                );
1612                                return true;
1613                            }
1614                        }
1615                    } else if line == ip.to_string() {
1616                        // Exact IP match
1617                        tracing::info!("Proxy/VPN exact match: {} (source: {})", ip, db_path);
1618                        return true;
1619                    }
1620                }
1621            }
1622        }
1623
1624        false
1625    }
1626
1627    /// Check against real-time Tor exit node lists
1628    fn check_tor_exit_nodes(&self, ip: &std::net::Ipv6Addr) -> bool {
1629        use std::path::Path;
1630
1631        // Real-time Tor exit node detection
1632        let tor_db_path = std::env::var("TOR_EXIT_NODES_IPV6_PATH")
1633            .unwrap_or_else(|_| "tor-exits-ipv6.txt".to_string());
1634
1635        if Path::new(&tor_db_path).exists()
1636            && let Ok(contents) = std::fs::read_to_string(&tor_db_path)
1637        {
1638            for line in contents.lines() {
1639                let line = line.trim();
1640                if line.is_empty() || line.starts_with('#') {
1641                    continue;
1642                }
1643
1644                // Check IPv6 exact match
1645                if let Ok(tor_ip) = line.parse::<std::net::Ipv6Addr>()
1646                    && tor_ip == *ip
1647                {
1648                    tracing::warn!("Tor exit node detected: {}", ip);
1649                    return true;
1650                }
1651
1652                // Check IPv6 network match
1653                if line.contains('/')
1654                    && let Ok(network) = line.parse::<ipnetwork::Ipv6Network>()
1655                    && network.contains(*ip)
1656                {
1657                    tracing::warn!("Tor exit network detected: {} in {}", ip, network);
1658                    return true;
1659                }
1660            }
1661        }
1662
1663        // Also check IPv4-mapped IPv6 addresses for Tor
1664        if let Some(ipv4) = ip.to_ipv4() {
1665            let tor_v4_path = std::env::var("TOR_EXIT_NODES_IPV4_PATH")
1666                .unwrap_or_else(|_| "tor-exits-ipv4.txt".to_string());
1667
1668            if Path::new(&tor_v4_path).exists()
1669                && let Ok(contents) = std::fs::read_to_string(&tor_v4_path)
1670            {
1671                for line in contents.lines() {
1672                    let line = line.trim();
1673                    if line == ipv4.to_string() {
1674                        tracing::warn!("Tor exit node detected (IPv4-mapped): {}", ip);
1675                        return true;
1676                    }
1677                }
1678            }
1679        }
1680
1681        false
1682    }
1683}
1684
1685impl Default for SessionConfig {
1686    fn default() -> Self {
1687        Self {
1688            default_duration: Duration::from_secs(3600), // 1 hour
1689            max_duration: Duration::from_secs(86400),    // 24 hours
1690            idle_timeout: Duration::from_secs(1800),     // 30 minutes
1691            rotate_on_privilege_escalation: true,
1692            rotate_periodically: true,
1693            rotation_interval: Duration::from_secs(1800), // 30 minutes
1694            max_concurrent_sessions: Some(5),
1695            track_device_fingerprints: true,
1696            enforce_geographic_restrictions: false,
1697            allowed_countries: vec![],
1698            security_policy: SessionSecurityPolicy::default(),
1699        }
1700    }
1701}
1702
1703impl Default for SessionSecurityPolicy {
1704    fn default() -> Self {
1705        Self {
1706            require_mfa_for_new_devices: true,
1707            require_reauth_for_sensitive_ops: true,
1708            reauth_timeout: Duration::from_secs(300), // 5 minutes
1709            max_risk_score: 70,
1710            auto_suspend_suspicious: true,
1711            verify_location_changes: true,
1712            limit_concurrent_sessions: true,
1713        }
1714    }
1715}
1716
1717#[cfg(test)]
1718mod tests {
1719    use super::*;
1720
1721    #[test]
1722    fn test_device_fingerprint_generation() {
1723        let generator = DeviceFingerprintGenerator::new();
1724        let metadata = RequestMetadata {
1725            user_agent: Some("Mozilla/5.0".to_string()),
1726            ..Default::default()
1727        };
1728
1729        let fp1 = generator.generate_fingerprint(&metadata);
1730        let fp2 = generator.generate_fingerprint(&metadata);
1731
1732        assert_eq!(fp1, fp2);
1733        assert!(fp1.starts_with("fp_"));
1734    }
1735
1736    #[test]
1737    fn test_risk_calculation() {
1738        let calculator = RiskCalculator::new();
1739        let device_info = DeviceInfo {
1740            fingerprint: "test".to_string(),
1741            device_type: "desktop".to_string(),
1742            operating_system: None,
1743            browser: None,
1744            screen_resolution: None,
1745            timezone: None,
1746            language: None,
1747            is_trusted: false,
1748            device_name: None,
1749            is_mobile: false,
1750            ip_address: None,
1751        };
1752
1753        let metadata = RequestMetadata::default();
1754        let history = vec![];
1755
1756        let risk = calculator.calculate_risk(&device_info, &metadata, &history, None);
1757        assert!(risk >= 20); // Should have at least 20 for untrusted device
1758    }
1759
1760    /// Minimal in-memory session storage for tests.
1761    #[derive(Default)]
1762    struct TestSessionStorage {
1763        sessions: std::sync::Mutex<std::collections::HashMap<String, Session>>,
1764    }
1765
1766    #[async_trait::async_trait]
1767    impl SessionStorage for TestSessionStorage {
1768        async fn create_session(&self, session: &Session) -> Result<()> {
1769            self.sessions
1770                .lock()
1771                .unwrap()
1772                .insert(session.id.clone(), session.clone());
1773            Ok(())
1774        }
1775        async fn get_session(&self, id: &str) -> Result<Option<Session>> {
1776            Ok(self.sessions.lock().unwrap().get(id).cloned())
1777        }
1778        async fn update_session(&self, session: &Session) -> Result<()> {
1779            self.create_session(session).await
1780        }
1781        async fn delete_session(&self, id: &str) -> Result<()> {
1782            self.sessions.lock().unwrap().remove(id);
1783            Ok(())
1784        }
1785        async fn get_user_sessions(&self, user_id: &str) -> Result<Vec<Session>> {
1786            Ok(self
1787                .sessions
1788                .lock()
1789                .unwrap()
1790                .values()
1791                .filter(|s| s.user_id == user_id)
1792                .cloned()
1793                .collect())
1794        }
1795        async fn count_active_sessions(&self, _user_id: &str) -> Result<u32> {
1796            Ok(0)
1797        }
1798        async fn cleanup_expired_sessions(&self) -> Result<u32> {
1799            Ok(0)
1800        }
1801        async fn find_sessions_by_device(&self, _fp: &str) -> Result<Vec<Session>> {
1802            Ok(vec![])
1803        }
1804        async fn find_sessions_by_ip(&self, _ip: &str) -> Result<Vec<Session>> {
1805            Ok(vec![])
1806        }
1807    }
1808
1809    #[tokio::test]
1810    async fn revoke_all_user_sessions_ends_every_live_session_whatever_its_state() {
1811        use crate::audit::{AuditLogger, TracingAuditStorage};
1812        let manager = SessionManager::new(
1813            TestSessionStorage::default(),
1814            SessionConfigBuilder::for_web_app().build(),
1815            AuditLogger::new(TracingAuditStorage),
1816        );
1817        let live_states = [
1818            SessionState::Active,
1819            SessionState::Suspended,
1820            SessionState::RequiresMfa,
1821            SessionState::RequiresReauth,
1822            SessionState::RequiresRotation,
1823            SessionState::HighRisk,
1824        ];
1825        let mut ids = Vec::new();
1826        for state in live_states.iter().cloned() {
1827            let mut s = Session::new("victim", Duration::from_secs(3600));
1828            s.state = state;
1829            manager.storage.create_session(&s).await.unwrap();
1830            ids.push(s.id);
1831        }
1832        // a terminal session is left as it is and not counted; another user's session is untouched
1833        let mut expired = Session::new("victim", Duration::from_secs(3600));
1834        expired.state = SessionState::Expired;
1835        manager.storage.create_session(&expired).await.unwrap();
1836        let other = Session::new("someone-else", Duration::from_secs(3600));
1837        manager.storage.create_session(&other).await.unwrap();
1838
1839        let revoked = manager.revoke_all_user_sessions("victim").await.unwrap();
1840        assert_eq!(revoked as usize, live_states.len());
1841        for (id, state) in ids.iter().zip(live_states.iter()) {
1842            let after = manager.storage.get_session(id).await.unwrap().unwrap();
1843            assert_eq!(after.state, SessionState::Revoked, "was {state:?}");
1844        }
1845        let expired_after = manager
1846            .storage
1847            .get_session(&expired.id)
1848            .await
1849            .unwrap()
1850            .unwrap();
1851        assert_eq!(expired_after.state, SessionState::Expired);
1852        let other_after = manager
1853            .storage
1854            .get_session(&other.id)
1855            .await
1856            .unwrap()
1857            .unwrap();
1858        assert_eq!(other_after.state, SessionState::Active);
1859    }
1860
1861    #[test]
1862    fn test_session_config_builder_for_web_app() {
1863        let config = SessionConfigBuilder::for_web_app().build();
1864        assert_eq!(config.default_duration, Duration::from_secs(3600));
1865        assert_eq!(config.max_duration, Duration::from_secs(86400));
1866        assert_eq!(config.max_concurrent_sessions, Some(5));
1867        assert!(config.track_device_fingerprints);
1868    }
1869
1870    #[test]
1871    fn test_session_config_builder_for_api_service() {
1872        let config = SessionConfigBuilder::for_api_service().build();
1873        assert_eq!(config.default_duration, Duration::from_secs(900));
1874        assert!(config.max_concurrent_sessions.is_none());
1875        assert!(!config.track_device_fingerprints);
1876        assert!(!config.rotate_periodically);
1877    }
1878
1879    #[test]
1880    fn test_session_config_builder_for_high_security() {
1881        let config = SessionConfigBuilder::for_high_security()
1882            .allowed_countries(vec!["US".into()])
1883            .build();
1884        assert_eq!(config.default_duration, Duration::from_secs(1800));
1885        assert_eq!(config.max_concurrent_sessions, Some(1));
1886        assert!(config.enforce_geographic_restrictions);
1887        assert_eq!(config.allowed_countries, vec!["US".to_string()]);
1888        assert!(config.security_policy.require_mfa_for_new_devices);
1889    }
1890
1891    // No test here performs a real MaxMind lookup (that needs a third-party
1892    // .mmdb fixture). These cover the open path: a missing or unreadable
1893    // database must yield `None`, never a panic.
1894    #[test]
1895    fn maxmind_geolocation_none_for_missing_or_garbage_database() {
1896        let generator = DeviceFingerprintGenerator::new();
1897        let ip = std::net::Ipv4Addr::new(8, 8, 8, 8);
1898        let dir = tempfile::tempdir().unwrap();
1899
1900        let missing = dir.path().join("missing.mmdb");
1901        assert_eq!(
1902            generator.lookup_maxmind_geolocation_at(missing.to_str().unwrap(), &ip),
1903            None
1904        );
1905
1906        let garbage_inputs: [(&str, &[u8]); 3] = [
1907            ("empty.mmdb", b""),
1908            ("garbage.mmdb", b"this is not a MaxMind database at all"),
1909            ("truncated.mmdb", b"\xAB\xCD\xEFMaxMind.com\x00"),
1910        ];
1911        for (name, bytes) in garbage_inputs {
1912            let path = dir.path().join(name);
1913            std::fs::write(&path, bytes).unwrap();
1914            // Positive control: see the twin test in secure_session_config.rs.
1915            assert!(
1916                maxminddb::Reader::open_readfile(&path).is_err(),
1917                "{name}: maxminddb accepted garbage bytes"
1918            );
1919            assert_eq!(
1920                generator.lookup_maxmind_geolocation_at(path.to_str().unwrap(), &ip),
1921                None,
1922                "{name}"
1923            );
1924        }
1925    }
1926}