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