Skip to main content

auth_framework/security/
secure_session.rs

1// Secure session management with enhanced security measures
2use super::secure_utils::{SecureComparison, SecureRandomGen};
3use crate::errors::{AuthError, Result};
4use crate::session::manager::SessionState;
5use dashmap::DashMap;
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use std::sync::Arc;
9use std::time::{Duration, SystemTime};
10use zeroize::ZeroizeOnDrop;
11
12/// Secure session with enhanced security properties
13#[derive(Clone, Serialize, Deserialize)]
14pub struct SecureSession {
15    /// Cryptographically secure session ID
16    pub id: String,
17
18    /// User ID associated with this session
19    pub user_id: String,
20
21    /// Session creation timestamp
22    pub created_at: SystemTime,
23
24    /// Last activity timestamp
25    pub last_accessed: SystemTime,
26
27    /// Session expiration time
28    pub expires_at: SystemTime,
29
30    /// Session state
31    pub state: SessionState,
32
33    /// Device fingerprint for security tracking
34    pub device_fingerprint: DeviceFingerprint,
35
36    /// IP address where session was created
37    pub creation_ip: String,
38
39    /// Current IP address
40    pub current_ip: String,
41
42    /// User agent string
43    pub user_agent: String,
44
45    /// MFA verification status
46    pub mfa_verified: bool,
47
48    /// Security flags
49    pub security_flags: SecurityFlags,
50
51    /// Session metadata
52    pub metadata: HashMap<String, String>,
53
54    /// Number of concurrent sessions for this user
55    pub concurrent_sessions: u32,
56
57    /// Session risk score (0-100)
58    pub risk_score: u8,
59
60    /// Session rotation count
61    pub rotation_count: u32,
62}
63
64impl std::fmt::Debug for SecureSession {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        let mut d = f.debug_struct("SecureSession");
67        d.field("id", &crate::utils::redact::redacted(&self.id));
68        d.field("user_id", &self.user_id);
69        d.field("created_at", &self.created_at);
70        d.field("last_accessed", &self.last_accessed);
71        d.field("expires_at", &self.expires_at);
72        d.field("state", &self.state);
73        d.field("device_fingerprint", &self.device_fingerprint);
74        d.field("creation_ip", &self.creation_ip);
75        d.field("current_ip", &self.current_ip);
76        d.field("user_agent", &self.user_agent);
77        d.field("mfa_verified", &self.mfa_verified);
78        d.field("security_flags", &self.security_flags);
79        d.field("metadata", &self.metadata);
80        d.field("concurrent_sessions", &self.concurrent_sessions);
81        d.field("risk_score", &self.risk_score);
82        d.field("rotation_count", &self.rotation_count);
83        d.finish()
84    }
85}
86
87/// Device fingerprint for tracking sessions
88#[derive(Debug, Clone, Serialize, Deserialize, ZeroizeOnDrop)]
89pub struct DeviceFingerprint {
90    /// Browser fingerprint hash
91    pub browser_hash: String,
92
93    /// Screen resolution
94    pub screen_resolution: Option<String>,
95
96    /// Timezone offset
97    pub timezone_offset: Option<i32>,
98
99    /// Platform information
100    pub platform: Option<String>,
101
102    /// Language preferences
103    pub languages: Vec<String>,
104
105    /// Canvas fingerprint
106    pub canvas_hash: Option<String>,
107
108    /// WebGL fingerprint
109    pub webgl_hash: Option<String>,
110}
111
112/// Security flags for session management
113#[derive(Debug, Clone, Serialize, Deserialize, Default)]
114pub struct SecurityFlags {
115    /// Session created over secure transport (HTTPS)
116    pub secure_transport: bool,
117
118    /// Session accessed from suspicious location
119    pub suspicious_location: bool,
120
121    /// Multiple failed authentication attempts
122    pub multiple_failures: bool,
123
124    /// Session accessed from new device
125    pub new_device: bool,
126
127    /// Session accessed outside normal hours
128    pub unusual_hours: bool,
129
130    /// High-privilege operations performed
131    pub high_privilege_ops: bool,
132
133    /// Session shared across devices (security risk)
134    pub cross_device_access: bool,
135}
136
137/// Secure session configuration
138#[derive(Debug, Clone)]
139pub struct SecureSessionConfig {
140    /// Maximum session lifetime
141    pub max_lifetime: Duration,
142
143    /// Session idle timeout
144    pub idle_timeout: Duration,
145
146    /// Maximum concurrent sessions per user
147    pub max_concurrent_sessions: u32,
148
149    /// Force session rotation interval
150    pub rotation_interval: Duration,
151
152    /// Require secure transport (HTTPS)
153    pub require_secure_transport: bool,
154
155    /// Enable device fingerprinting
156    pub enable_device_fingerprinting: bool,
157
158    /// Maximum allowed risk score
159    pub max_risk_score: u8,
160
161    /// Enable IP address validation
162    pub validate_ip_address: bool,
163
164    /// Maximum IP address changes per session
165    pub max_ip_changes: u32,
166
167    /// Enable geolocation tracking
168    pub enable_geolocation: bool,
169}
170
171impl Default for SecureSessionConfig {
172    /// Returns a balanced default suitable for most web applications.
173    ///
174    /// | Field | Value | Rationale |
175    /// |---|---|---|
176    /// | `max_lifetime` | 8 h | Covers a working day without forcing re-login |
177    /// | `idle_timeout` | 30 min | OWASP recommendation for general web apps |
178    /// | `max_concurrent_sessions` | 3 | Desktop + phone + tablet |
179    /// | `rotation_interval` | 1 h | Limits window for session-fixation |
180    /// | `require_secure_transport` | `true` | Always enforce HTTPS |
181    /// | `enable_device_fingerprinting` | `true` | Detect session hijacking |
182    /// | `max_risk_score` | 70 | Permit moderate anomalies |
183    /// | `validate_ip_address` | `true` | Catch session theft across IPs |
184    /// | `max_ip_changes` | 3 | Allow mobile network handoffs |
185    /// | `enable_geolocation` | `false` | Requires external MaxMind DB |
186    fn default() -> Self {
187        Self {
188            max_lifetime: Duration::from_secs(8 * 3600), // 8 hours
189            idle_timeout: Duration::from_secs(30 * 60),  // 30 minutes
190            max_concurrent_sessions: 3,
191            rotation_interval: Duration::from_secs(3600), // 1 hour
192            require_secure_transport: true,
193            enable_device_fingerprinting: true,
194            max_risk_score: 70,
195            validate_ip_address: true,
196            max_ip_changes: 3,
197            enable_geolocation: false, // Requires external service
198        }
199    }
200}
201
202impl SecureSessionConfig {
203    /// Preset for high-security environments (finance, healthcare, government).
204    ///
205    /// Tighter timeouts, single-device enforcement, aggressive anomaly detection.
206    ///
207    /// # Example
208    /// ```rust,ignore
209    /// let manager = SecureSessionManager::new(SecureSessionConfig::for_high_security());
210    /// ```
211    pub fn for_high_security() -> Self {
212        Self {
213            max_lifetime: Duration::from_secs(2 * 3600), // 2 hours
214            idle_timeout: Duration::from_secs(10 * 60),  // 10 minutes
215            max_concurrent_sessions: 1,
216            rotation_interval: Duration::from_secs(15 * 60), // 15 minutes
217            require_secure_transport: true,
218            enable_device_fingerprinting: true,
219            max_risk_score: 40,
220            validate_ip_address: true,
221            max_ip_changes: 1,
222            enable_geolocation: true,
223        }
224    }
225
226    /// Preset for mobile / native-app sessions.
227    ///
228    /// Longer lifetimes and more lenient IP-change limits to cope with
229    /// cellular hand-offs, while still requiring secure transport.
230    ///
231    /// # Example
232    /// ```rust,ignore
233    /// let manager = SecureSessionManager::new(SecureSessionConfig::for_mobile());
234    /// ```
235    pub fn for_mobile() -> Self {
236        Self {
237            max_lifetime: Duration::from_secs(30 * 24 * 3600), // 30 days
238            idle_timeout: Duration::from_secs(7 * 24 * 3600),  // 7 days
239            max_concurrent_sessions: 5,
240            rotation_interval: Duration::from_secs(24 * 3600), // 24 hours
241            require_secure_transport: true,
242            enable_device_fingerprinting: true,
243            max_risk_score: 80,
244            validate_ip_address: false,
245            max_ip_changes: 50,
246            enable_geolocation: false,
247        }
248    }
249}
250
251/// Secure session manager with comprehensive security controls
252pub struct SecureSessionManager {
253    config: SecureSessionConfig,
254    active_sessions: Arc<DashMap<String, SecureSession>>,
255    user_sessions: Arc<DashMap<String, Vec<String>>>, // user_id -> session_ids
256    ip_changes: Arc<DashMap<String, u32>>,            // session_id -> change_count
257}
258
259impl SecureSessionManager {
260    /// Create a new secure session manager
261    pub fn new(config: SecureSessionConfig) -> Self {
262        Self {
263            config,
264            active_sessions: Arc::new(DashMap::new()),
265            user_sessions: Arc::new(DashMap::new()),
266            ip_changes: Arc::new(DashMap::new()),
267        }
268    }
269
270    /// Create a new secure session
271    pub fn create_session(
272        &self,
273        user_id: &str,
274        ip_address: &str,
275        user_agent: &str,
276        device_fingerprint: Option<DeviceFingerprint>,
277        secure_transport: bool,
278    ) -> Result<SecureSession> {
279        // Validate security requirements
280        if self.config.require_secure_transport && !secure_transport {
281            return Err(AuthError::validation(
282                "Session must be created over secure transport (HTTPS)".to_string(),
283            ));
284        }
285
286        // Check concurrent session limits
287        self.enforce_concurrent_session_limit(user_id)?;
288
289        // Generate secure session ID
290        let session_id = SecureRandomGen::generate_session_id()?;
291
292        let now = SystemTime::now();
293        let expires_at = now + self.config.max_lifetime;
294
295        // Calculate initial risk score
296        let risk_score = self.calculate_risk_score(
297            ip_address,
298            user_agent,
299            &device_fingerprint,
300            secure_transport,
301        );
302
303        // Get concurrent session count
304        let concurrent_sessions = self.get_user_session_count(user_id);
305
306        let session = SecureSession {
307            id: session_id.clone(),
308            user_id: user_id.to_string(),
309            created_at: now,
310            last_accessed: now,
311            expires_at,
312            state: if risk_score > self.config.max_risk_score {
313                SessionState::HighRisk
314            } else {
315                SessionState::Active
316            },
317            device_fingerprint: device_fingerprint.unwrap_or_else(|| DeviceFingerprint {
318                browser_hash: "unknown".to_string(),
319                screen_resolution: None,
320                timezone_offset: None,
321                platform: None,
322                languages: vec![],
323                canvas_hash: None,
324                webgl_hash: None,
325            }),
326            creation_ip: ip_address.to_string(),
327            current_ip: ip_address.to_string(),
328            user_agent: user_agent.to_string(),
329            mfa_verified: false,
330            security_flags: SecurityFlags {
331                secure_transport,
332                ..SecurityFlags::default()
333            },
334            metadata: HashMap::new(),
335            concurrent_sessions,
336            risk_score,
337            rotation_count: 0,
338        };
339
340        // Store session
341        self.store_session(session.clone())?;
342
343        tracing::info!(
344            "Created secure session {} for user {} (risk score: {})",
345            crate::utils::redact::fingerprint(&session_id),
346            user_id,
347            risk_score
348        );
349
350        Ok(session)
351    }
352
353    /// Validate and retrieve session
354    pub fn get_session(&self, session_id: &str) -> Result<Option<SecureSession>> {
355        if let Some(session_ref) = self.active_sessions.get(session_id) {
356            let session = session_ref.value().clone();
357
358            // Check if session is expired
359            if session.expires_at < SystemTime::now() {
360                drop(session_ref);
361                self.revoke_session(session_id)?;
362                return Ok(None);
363            }
364
365            // Check session state
366            match session.state {
367                SessionState::Active => Ok(Some(session)),
368                SessionState::RequiresMfa => Ok(Some(session)),
369                SessionState::RequiresRotation => Ok(Some(session)),
370                _ => Ok(None), // Expired, revoked, suspended, high risk
371            }
372        } else {
373            Ok(None)
374        }
375    }
376
377    /// Update session activity and validate security.
378    ///
379    /// NOTE: DashMap's `get_mut` provides per-shard locking, serializing concurrent
380    /// access to the same session. This prevents TOCTOU race conditions on session
381    /// state checks and updates.
382    pub fn update_session_activity(
383        &self,
384        session_id: &str,
385        ip_address: &str,
386        user_agent: &str,
387    ) -> Result<()> {
388        if let Some(mut session_entry) = self.active_sessions.get_mut(session_id) {
389            let session = session_entry.value_mut();
390            let now = SystemTime::now();
391
392            // Reject updates on terminal session states
393            match session.state {
394                SessionState::Active | SessionState::RequiresRotation => {}
395                SessionState::RequiresMfa => {
396                    return Err(AuthError::validation(
397                        "Session requires MFA verification before activity is allowed".to_string(),
398                    ));
399                }
400                _ => {
401                    return Err(AuthError::validation(
402                        "Session is no longer active".to_string(),
403                    ));
404                }
405            }
406
407            // Check idle timeout
408            if now
409                .duration_since(session.last_accessed)
410                .unwrap_or_default()
411                > self.config.idle_timeout
412            {
413                session.state = SessionState::Expired;
414                return Err(AuthError::validation(
415                    "Session expired due to inactivity".to_string(),
416                ));
417            }
418
419            // Validate IP address change
420            if self.config.validate_ip_address && session.current_ip != ip_address {
421                self.handle_ip_change(session, ip_address)?;
422            }
423
424            // Validate user agent consistency
425            if !SecureComparison::constant_time_eq(&session.user_agent, user_agent) {
426                session.security_flags.cross_device_access = true;
427                tracing::warn!(
428                    "User agent change detected for session {}: {} -> {}",
429                    crate::utils::redact::fingerprint(session_id),
430                    session.user_agent,
431                    user_agent
432                );
433            }
434
435            // Update activity
436            session.last_accessed = now;
437            session.current_ip = ip_address.to_string();
438
439            // Check if rotation is needed
440            if now.duration_since(session.created_at).unwrap_or_default()
441                > self.config.rotation_interval
442            {
443                session.state = SessionState::RequiresRotation;
444            }
445
446            // Recalculate risk score
447            let new_risk_score = self.calculate_risk_score_update(session);
448            session.risk_score = new_risk_score;
449
450            if new_risk_score > self.config.max_risk_score {
451                session.state = SessionState::HighRisk;
452                tracing::warn!(
453                    "Session {} marked as high risk (score: {})",
454                    crate::utils::redact::fingerprint(session_id),
455                    new_risk_score
456                );
457            }
458
459            Ok(())
460        } else {
461            Err(AuthError::validation("Session not found".to_string()))
462        }
463    }
464
465    /// Rotate session ID for security
466    pub fn rotate_session(&self, session_id: &str) -> Result<String> {
467        if let Some((_, mut session)) = self.active_sessions.remove(session_id) {
468            // Generate new session ID
469            let new_session_id = SecureRandomGen::generate_session_id()?;
470
471            // Update session
472            session.id = new_session_id.clone();
473            session.rotation_count += 1;
474            session.state = SessionState::Active;
475            session.last_accessed = SystemTime::now();
476
477            // Store with new ID
478            self.active_sessions
479                .insert(new_session_id.clone(), session.clone());
480
481            // Update user session tracking with atomic operations
482            if let Some(mut user_session_list) = self.user_sessions.get_mut(&session.user_id)
483                && let Some(pos) = user_session_list.iter().position(|id| id == session_id)
484            {
485                user_session_list[pos] = new_session_id.clone();
486            }
487
488            tracing::info!(
489                "Session rotated: {} -> {} (rotation count: {})",
490                crate::utils::redact::fingerprint(session_id),
491                crate::utils::redact::fingerprint(&new_session_id),
492                session.rotation_count
493            );
494
495            Ok(new_session_id)
496        } else {
497            Err(AuthError::validation(
498                "Session not found for rotation".to_string(),
499            ))
500        }
501    }
502
503    /// Revoke a session
504    pub fn revoke_session(&self, session_id: &str) -> Result<()> {
505        if let Some((_, session)) = self.active_sessions.remove(session_id) {
506            // Remove from user session tracking using atomic operations
507            if let Some(mut user_session_list) = self.user_sessions.get_mut(&session.user_id) {
508                user_session_list.retain(|id| id != session_id);
509                if user_session_list.is_empty() {
510                    drop(user_session_list);
511                    self.user_sessions.remove(&session.user_id);
512                }
513            }
514
515            // Clean up IP change tracking
516            self.ip_changes.remove(session_id);
517
518            tracing::info!(
519                "Session {} revoked for user {}",
520                crate::utils::redact::fingerprint(session_id),
521                session.user_id
522            );
523
524            Ok(())
525        } else {
526            Err(AuthError::validation(
527                "Session not found for revocation".to_string(),
528            ))
529        }
530    }
531
532    /// Revoke all sessions for a user
533    pub fn revoke_user_sessions(&self, user_id: &str) -> Result<u32> {
534        if let Some((_, session_ids)) = self.user_sessions.remove(user_id) {
535            let count = session_ids.len() as u32;
536
537            for session_id in &session_ids {
538                self.active_sessions.remove(session_id);
539            }
540
541            // Clean up IP change tracking
542            for session_id in &session_ids {
543                self.ip_changes.remove(session_id);
544            }
545
546            tracing::info!("Revoked {} sessions for user {}", count, user_id);
547
548            Ok(count)
549        } else {
550            Ok(0)
551        }
552    }
553
554    /// Clean up expired sessions
555    pub fn cleanup_expired_sessions(&self) -> Result<u32> {
556        let now = SystemTime::now();
557        let mut expired_sessions = Vec::new();
558
559        // Find expired sessions using DashMap iterator
560        for session_ref in self.active_sessions.iter() {
561            if session_ref.value().expires_at < now {
562                expired_sessions.push(session_ref.key().clone());
563            }
564        }
565
566        // Remove expired sessions
567        let count = expired_sessions.len() as u32;
568        for session_id in expired_sessions {
569            let _ = self.revoke_session(&session_id);
570        }
571
572        if count > 0 {
573            tracing::info!("Cleaned up {} expired sessions", count);
574        }
575
576        Ok(count)
577    }
578
579    /// Store session in memory (in production, use persistent storage)
580    fn store_session(&self, session: SecureSession) -> Result<()> {
581        self.active_sessions
582            .insert(session.id.clone(), session.clone());
583
584        self.user_sessions
585            .entry(session.user_id.clone())
586            .or_default()
587            .push(session.id.clone());
588
589        Ok(())
590    }
591
592    /// Enforce concurrent session limits
593    fn enforce_concurrent_session_limit(&self, user_id: &str) -> Result<()> {
594        let current_count = self.get_user_session_count(user_id);
595
596        if current_count >= self.config.max_concurrent_sessions {
597            // Revoke oldest session
598            self.revoke_oldest_user_session(user_id)?;
599        }
600
601        Ok(())
602    }
603
604    /// Get number of active sessions for a user
605    fn get_user_session_count(&self, user_id: &str) -> u32 {
606        self.user_sessions
607            .get(user_id)
608            .map(|sessions| sessions.len() as u32)
609            .unwrap_or(0)
610    }
611
612    /// Revoke the oldest session for a user
613    fn revoke_oldest_user_session(&self, user_id: &str) -> Result<()> {
614        let oldest_session_id = if let Some(session_ids_ref) = self.user_sessions.get(user_id) {
615            let session_ids = session_ids_ref.value();
616            session_ids
617                .iter()
618                .filter_map(|id| self.active_sessions.get(id))
619                .min_by_key(|session_ref| session_ref.value().created_at)
620                .map(|session_ref| session_ref.key().clone())
621        } else {
622            None
623        };
624
625        if let Some(session_id) = oldest_session_id {
626            self.revoke_session(&session_id)?;
627            tracing::info!(
628                "Revoked oldest session {} for user {} due to concurrent limit",
629                crate::utils::redact::fingerprint(&session_id),
630                user_id
631            );
632        }
633
634        Ok(())
635    }
636
637    /// Handle IP address change
638    fn handle_ip_change(&self, session: &mut SecureSession, new_ip: &str) -> Result<()> {
639        let mut change_count = self.ip_changes.entry(session.id.clone()).or_insert(0);
640        *change_count += 1;
641
642        if *change_count > self.config.max_ip_changes {
643            session.state = SessionState::HighRisk;
644            session.security_flags.suspicious_location = true;
645            return Err(AuthError::validation(
646                "Too many IP address changes - session marked as high risk".to_string(),
647            ));
648        }
649
650        session.security_flags.suspicious_location = true;
651        tracing::warn!(
652            "IP address change #{} for session {}: {} -> {}",
653            *change_count,
654            session.id,
655            session.current_ip,
656            new_ip
657        );
658
659        Ok(())
660    }
661
662    /// Calculate initial risk score
663    fn calculate_risk_score(
664        &self,
665        ip_address: &str,
666        user_agent: &str,
667        device_fingerprint: &Option<DeviceFingerprint>,
668        secure_transport: bool,
669    ) -> u8 {
670        let mut score = 0u8;
671
672        // Non-secure transport
673        if !secure_transport {
674            score += 30;
675        }
676
677        // Unknown or suspicious user agent
678        if user_agent.is_empty() || user_agent.len() < 10 {
679            score += 20;
680        }
681
682        // Missing device fingerprint
683        if device_fingerprint.is_none() {
684            score += 15;
685        }
686
687        // Private/local IP addresses (higher risk)
688        if self.is_private_ip(ip_address) {
689            score += 10;
690        }
691
692        score.min(100)
693    }
694
695    /// Update risk score based on session activity with decay for cleared conditions
696    fn calculate_risk_score_update(&self, session: &SecureSession) -> u8 {
697        // Start from a base score rather than the accumulated score to avoid
698        // monotonic increase. Recalculate from current flags each time.
699        let mut score: u8 = 0;
700
701        // Security flag penalties (only applied when the flag is currently set)
702        if session.security_flags.suspicious_location {
703            score = score.saturating_add(20);
704        }
705        if session.security_flags.multiple_failures {
706            score = score.saturating_add(25);
707        }
708        if session.security_flags.new_device {
709            // Apply time-based decay: new_device risk decreases over session lifetime.
710            // After 30 minutes of consistent activity, halve the penalty.
711            let age_secs = session
712                .last_accessed
713                .duration_since(session.created_at)
714                .unwrap_or_default()
715                .as_secs();
716            let penalty = if age_secs > 1800 { 7 } else { 15 };
717            score = score.saturating_add(penalty);
718        }
719        if session.security_flags.unusual_hours {
720            score = score.saturating_add(10);
721        }
722        if session.security_flags.cross_device_access {
723            score = score.saturating_add(20);
724        }
725
726        // High concurrent sessions
727        if session.concurrent_sessions > 5 {
728            score = score.saturating_add(15);
729        }
730
731        // Multiple rotations (could indicate compromise)
732        if session.rotation_count > 3 {
733            score = score.saturating_add(10);
734        }
735
736        // Velocity check: rapid rotations suggest token theft.
737        // If session has been rotated multiple times within a short window,
738        // increase risk proportionally.
739        if session.rotation_count > 1 {
740            let age_secs = session
741                .last_accessed
742                .duration_since(session.created_at)
743                .unwrap_or_default()
744                .as_secs()
745                .max(1); // avoid division by zero
746            let rotations_per_minute =
747                (session.rotation_count as u64).saturating_mul(60) / age_secs;
748            if rotations_per_minute > 5 {
749                score = score.saturating_add(20);
750            } else if rotations_per_minute > 2 {
751                score = score.saturating_add(10);
752            }
753        }
754
755        score.min(100)
756    }
757
758    /// Check if IP address is private/internal (RFC 1918 + loopback)
759    fn is_private_ip(&self, ip: &str) -> bool {
760        if ip == "127.0.0.1" || ip == "::1" {
761            return true;
762        }
763        if ip.starts_with("192.168.") || ip.starts_with("10.") {
764            return true;
765        }
766        // RFC 1918: 172.16.0.0 – 172.31.255.255
767        if let Some(rest) = ip.strip_prefix("172.")
768            && let Some(second_octet_str) = rest.split('.').next()
769            && let Ok(second_octet) = second_octet_str.parse::<u8>()
770        {
771            return (16..=31).contains(&second_octet);
772        }
773        false
774    }
775}
776
777#[cfg(test)]
778mod tests {
779    use super::*;
780
781    #[test]
782    fn test_secure_session_creation() {
783        let config = SecureSessionConfig::default();
784        let manager = SecureSessionManager::new(config);
785
786        let session = manager
787            .create_session(
788                "user123",
789                "192.168.1.100",
790                "Mozilla/5.0 Test Browser",
791                None,
792                true,
793            )
794            .unwrap();
795
796        assert_eq!(session.user_id, "user123");
797        assert_eq!(session.creation_ip, "192.168.1.100");
798        assert!(session.security_flags.secure_transport);
799        assert_eq!(session.state, SessionState::Active);
800    }
801
802    #[test]
803    fn test_session_rotation() {
804        let config = SecureSessionConfig::default();
805        let manager = SecureSessionManager::new(config);
806
807        let session = manager
808            .create_session(
809                "user123",
810                "192.168.1.100",
811                "Mozilla/5.0 Test Browser",
812                None,
813                true,
814            )
815            .unwrap();
816
817        let old_id = session.id.clone();
818        let new_id = manager.rotate_session(&old_id).unwrap();
819
820        assert_ne!(old_id, new_id);
821        assert!(manager.get_session(&old_id).unwrap().is_none());
822        assert!(manager.get_session(&new_id).unwrap().is_some());
823    }
824
825    #[test]
826    fn test_concurrent_session_limit() {
827        let config = SecureSessionConfig {
828            max_concurrent_sessions: 2,
829            ..Default::default()
830        };
831        let manager = SecureSessionManager::new(config);
832
833        // Create first session
834        let session1 = manager
835            .create_session(
836                "user123",
837                "192.168.1.100",
838                "Mozilla/5.0 Test Browser",
839                None,
840                true,
841            )
842            .unwrap();
843
844        // Create second session
845        let session2 = manager
846            .create_session(
847                "user123",
848                "192.168.1.101",
849                "Mozilla/5.0 Test Browser",
850                None,
851                true,
852            )
853            .unwrap();
854
855        // Third session should revoke the first
856        let session3 = manager
857            .create_session(
858                "user123",
859                "192.168.1.102",
860                "Mozilla/5.0 Test Browser",
861                None,
862                true,
863            )
864            .unwrap();
865
866        // First session should be revoked
867        assert!(manager.get_session(&session1.id).unwrap().is_none());
868        assert!(manager.get_session(&session2.id).unwrap().is_some());
869        assert!(manager.get_session(&session3.id).unwrap().is_some());
870    }
871
872    #[test]
873    fn test_risk_score_calculation() {
874        let config = SecureSessionConfig::default();
875        let manager = SecureSessionManager::new(config);
876
877        // High risk: non-secure transport, private IP, no device fingerprint
878        let risk_score = manager.calculate_risk_score("192.168.1.1", "", &None, false);
879
880        assert!(risk_score > 50, "Risk score should be high: {}", risk_score);
881    }
882
883    #[test]
884    fn test_session_cleanup() {
885        let config = SecureSessionConfig {
886            max_lifetime: Duration::from_millis(1), // Very short for testing
887            ..Default::default()
888        };
889        let manager = SecureSessionManager::new(config);
890
891        let session = manager
892            .create_session(
893                "user123",
894                "192.168.1.100",
895                "Mozilla/5.0 Test Browser",
896                None,
897                true,
898            )
899            .unwrap();
900
901        // Wait for expiration
902        std::thread::sleep(Duration::from_millis(10));
903
904        let cleaned = manager.cleanup_expired_sessions().unwrap();
905        assert_eq!(cleaned, 1);
906        assert!(manager.get_session(&session.id).unwrap().is_none());
907    }
908
909    #[test]
910    fn test_for_high_security_preset() {
911        let config = SecureSessionConfig::for_high_security();
912        assert_eq!(config.max_lifetime, Duration::from_secs(2 * 3600));
913        assert_eq!(config.idle_timeout, Duration::from_secs(10 * 60));
914        assert_eq!(config.max_concurrent_sessions, 1);
915        assert_eq!(config.max_risk_score, 40);
916        assert!(config.enable_geolocation);
917        // Should still create a working manager
918        let manager = SecureSessionManager::new(config);
919        let session = manager
920            .create_session("u1", "10.0.0.1", "UA", None, true)
921            .unwrap();
922        assert_eq!(session.user_id, "u1");
923    }
924
925    #[test]
926    fn test_for_mobile_preset() {
927        let config = SecureSessionConfig::for_mobile();
928        assert_eq!(config.max_lifetime, Duration::from_secs(30 * 24 * 3600));
929        assert_eq!(config.max_concurrent_sessions, 5);
930        assert!(!config.validate_ip_address);
931        let manager = SecureSessionManager::new(config);
932        let session = manager
933            .create_session("u2", "10.0.0.2", "iOS", None, true)
934            .unwrap();
935        assert_eq!(session.user_id, "u2");
936    }
937}