auth-framework 0.5.0-rc19

A comprehensive, production-ready authentication and authorization framework for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
// Secure session management with enhanced security measures
use super::secure_utils::{SecureComparison, SecureRandomGen};
use crate::errors::{AuthError, Result};
use crate::session::manager::SessionState;
use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use zeroize::ZeroizeOnDrop;

/// Secure session with enhanced security properties
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecureSession {
    /// Cryptographically secure session ID
    pub id: String,

    /// User ID associated with this session
    pub user_id: String,

    /// Session creation timestamp
    pub created_at: SystemTime,

    /// Last activity timestamp
    pub last_accessed: SystemTime,

    /// Session expiration time
    pub expires_at: SystemTime,

    /// Session state
    pub state: SessionState,

    /// Device fingerprint for security tracking
    pub device_fingerprint: DeviceFingerprint,

    /// IP address where session was created
    pub creation_ip: String,

    /// Current IP address
    pub current_ip: String,

    /// User agent string
    pub user_agent: String,

    /// MFA verification status
    pub mfa_verified: bool,

    /// Security flags
    pub security_flags: SecurityFlags,

    /// Session metadata
    pub metadata: HashMap<String, String>,

    /// Number of concurrent sessions for this user
    pub concurrent_sessions: u32,

    /// Session risk score (0-100)
    pub risk_score: u8,

    /// Session rotation count
    pub rotation_count: u32,
}

/// Device fingerprint for tracking sessions
#[derive(Debug, Clone, Serialize, Deserialize, ZeroizeOnDrop)]
pub struct DeviceFingerprint {
    /// Browser fingerprint hash
    pub browser_hash: String,

    /// Screen resolution
    pub screen_resolution: Option<String>,

    /// Timezone offset
    pub timezone_offset: Option<i32>,

    /// Platform information
    pub platform: Option<String>,

    /// Language preferences
    pub languages: Vec<String>,

    /// Canvas fingerprint
    pub canvas_hash: Option<String>,

    /// WebGL fingerprint
    pub webgl_hash: Option<String>,
}

/// Security flags for session management
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SecurityFlags {
    /// Session created over secure transport (HTTPS)
    pub secure_transport: bool,

    /// Session accessed from suspicious location
    pub suspicious_location: bool,

    /// Multiple failed authentication attempts
    pub multiple_failures: bool,

    /// Session accessed from new device
    pub new_device: bool,

    /// Session accessed outside normal hours
    pub unusual_hours: bool,

    /// High-privilege operations performed
    pub high_privilege_ops: bool,

    /// Session shared across devices (security risk)
    pub cross_device_access: bool,
}

/// Secure session configuration
#[derive(Debug, Clone)]
pub struct SecureSessionConfig {
    /// Maximum session lifetime
    pub max_lifetime: Duration,

    /// Session idle timeout
    pub idle_timeout: Duration,

    /// Maximum concurrent sessions per user
    pub max_concurrent_sessions: u32,

    /// Force session rotation interval
    pub rotation_interval: Duration,

    /// Require secure transport (HTTPS)
    pub require_secure_transport: bool,

    /// Enable device fingerprinting
    pub enable_device_fingerprinting: bool,

    /// Maximum allowed risk score
    pub max_risk_score: u8,

    /// Enable IP address validation
    pub validate_ip_address: bool,

    /// Maximum IP address changes per session
    pub max_ip_changes: u32,

    /// Enable geolocation tracking
    pub enable_geolocation: bool,
}

impl Default for SecureSessionConfig {
    /// Returns a balanced default suitable for most web applications.
    ///
    /// | Field | Value | Rationale |
    /// |---|---|---|
    /// | `max_lifetime` | 8 h | Covers a working day without forcing re-login |
    /// | `idle_timeout` | 30 min | OWASP recommendation for general web apps |
    /// | `max_concurrent_sessions` | 3 | Desktop + phone + tablet |
    /// | `rotation_interval` | 1 h | Limits window for session-fixation |
    /// | `require_secure_transport` | `true` | Always enforce HTTPS |
    /// | `enable_device_fingerprinting` | `true` | Detect session hijacking |
    /// | `max_risk_score` | 70 | Permit moderate anomalies |
    /// | `validate_ip_address` | `true` | Catch session theft across IPs |
    /// | `max_ip_changes` | 3 | Allow mobile network handoffs |
    /// | `enable_geolocation` | `false` | Requires external MaxMind DB |
    fn default() -> Self {
        Self {
            max_lifetime: Duration::from_secs(8 * 3600), // 8 hours
            idle_timeout: Duration::from_secs(30 * 60),  // 30 minutes
            max_concurrent_sessions: 3,
            rotation_interval: Duration::from_secs(3600), // 1 hour
            require_secure_transport: true,
            enable_device_fingerprinting: true,
            max_risk_score: 70,
            validate_ip_address: true,
            max_ip_changes: 3,
            enable_geolocation: false, // Requires external service
        }
    }
}

impl SecureSessionConfig {
    /// Preset for high-security environments (finance, healthcare, government).
    ///
    /// Tighter timeouts, single-device enforcement, aggressive anomaly detection.
    ///
    /// # Example
    /// ```rust,ignore
    /// let manager = SecureSessionManager::new(SecureSessionConfig::for_high_security());
    /// ```
    pub fn for_high_security() -> Self {
        Self {
            max_lifetime: Duration::from_secs(2 * 3600), // 2 hours
            idle_timeout: Duration::from_secs(10 * 60),  // 10 minutes
            max_concurrent_sessions: 1,
            rotation_interval: Duration::from_secs(15 * 60), // 15 minutes
            require_secure_transport: true,
            enable_device_fingerprinting: true,
            max_risk_score: 40,
            validate_ip_address: true,
            max_ip_changes: 1,
            enable_geolocation: true,
        }
    }

    /// Preset for mobile / native-app sessions.
    ///
    /// Longer lifetimes and more lenient IP-change limits to cope with
    /// cellular hand-offs, while still requiring secure transport.
    ///
    /// # Example
    /// ```rust,ignore
    /// let manager = SecureSessionManager::new(SecureSessionConfig::for_mobile());
    /// ```
    pub fn for_mobile() -> Self {
        Self {
            max_lifetime: Duration::from_secs(30 * 24 * 3600), // 30 days
            idle_timeout: Duration::from_secs(7 * 24 * 3600),  // 7 days
            max_concurrent_sessions: 5,
            rotation_interval: Duration::from_secs(24 * 3600), // 24 hours
            require_secure_transport: true,
            enable_device_fingerprinting: true,
            max_risk_score: 80,
            validate_ip_address: false,
            max_ip_changes: 50,
            enable_geolocation: false,
        }
    }
}

/// Secure session manager with comprehensive security controls
pub struct SecureSessionManager {
    config: SecureSessionConfig,
    active_sessions: Arc<DashMap<String, SecureSession>>,
    user_sessions: Arc<DashMap<String, Vec<String>>>, // user_id -> session_ids
    ip_changes: Arc<DashMap<String, u32>>,            // session_id -> change_count
}

impl SecureSessionManager {
    /// Create a new secure session manager
    pub fn new(config: SecureSessionConfig) -> Self {
        Self {
            config,
            active_sessions: Arc::new(DashMap::new()),
            user_sessions: Arc::new(DashMap::new()),
            ip_changes: Arc::new(DashMap::new()),
        }
    }

    /// Create a new secure session
    pub fn create_session(
        &self,
        user_id: &str,
        ip_address: &str,
        user_agent: &str,
        device_fingerprint: Option<DeviceFingerprint>,
        secure_transport: bool,
    ) -> Result<SecureSession> {
        // Validate security requirements
        if self.config.require_secure_transport && !secure_transport {
            return Err(AuthError::validation(
                "Session must be created over secure transport (HTTPS)".to_string(),
            ));
        }

        // Check concurrent session limits
        self.enforce_concurrent_session_limit(user_id)?;

        // Generate secure session ID
        let session_id = SecureRandomGen::generate_session_id()?;

        let now = SystemTime::now();
        let expires_at = now + self.config.max_lifetime;

        // Calculate initial risk score
        let risk_score = self.calculate_risk_score(
            ip_address,
            user_agent,
            &device_fingerprint,
            secure_transport,
        );

        // Get concurrent session count
        let concurrent_sessions = self.get_user_session_count(user_id);

        let session = SecureSession {
            id: session_id.clone(),
            user_id: user_id.to_string(),
            created_at: now,
            last_accessed: now,
            expires_at,
            state: if risk_score > self.config.max_risk_score {
                SessionState::HighRisk
            } else {
                SessionState::Active
            },
            device_fingerprint: device_fingerprint.unwrap_or_else(|| DeviceFingerprint {
                browser_hash: "unknown".to_string(),
                screen_resolution: None,
                timezone_offset: None,
                platform: None,
                languages: vec![],
                canvas_hash: None,
                webgl_hash: None,
            }),
            creation_ip: ip_address.to_string(),
            current_ip: ip_address.to_string(),
            user_agent: user_agent.to_string(),
            mfa_verified: false,
            security_flags: SecurityFlags {
                secure_transport,
                ..SecurityFlags::default()
            },
            metadata: HashMap::new(),
            concurrent_sessions,
            risk_score,
            rotation_count: 0,
        };

        // Store session
        self.store_session(session.clone())?;

        tracing::info!(
            "Created secure session {} for user {} (risk score: {})",
            session_id,
            user_id,
            risk_score
        );

        Ok(session)
    }

    /// Validate and retrieve session
    pub fn get_session(&self, session_id: &str) -> Result<Option<SecureSession>> {
        if let Some(session_ref) = self.active_sessions.get(session_id) {
            let session = session_ref.value().clone();

            // Check if session is expired
            if session.expires_at < SystemTime::now() {
                drop(session_ref);
                self.revoke_session(session_id)?;
                return Ok(None);
            }

            // Check session state
            match session.state {
                SessionState::Active => Ok(Some(session)),
                SessionState::RequiresMfa => Ok(Some(session)),
                SessionState::RequiresRotation => Ok(Some(session)),
                _ => Ok(None), // Expired, revoked, suspended, high risk
            }
        } else {
            Ok(None)
        }
    }

    /// Update session activity and validate security.
    ///
    /// NOTE: DashMap's `get_mut` provides per-shard locking, serializing concurrent
    /// access to the same session. This prevents TOCTOU race conditions on session
    /// state checks and updates.
    pub fn update_session_activity(
        &self,
        session_id: &str,
        ip_address: &str,
        user_agent: &str,
    ) -> Result<()> {
        if let Some(mut session_entry) = self.active_sessions.get_mut(session_id) {
            let session = session_entry.value_mut();
            let now = SystemTime::now();

            // Reject updates on terminal session states
            match session.state {
                SessionState::Active | SessionState::RequiresRotation => {}
                SessionState::RequiresMfa => {
                    return Err(AuthError::validation(
                        "Session requires MFA verification before activity is allowed".to_string(),
                    ));
                }
                _ => {
                    return Err(AuthError::validation(
                        "Session is no longer active".to_string(),
                    ));
                }
            }

            // Check idle timeout
            if now
                .duration_since(session.last_accessed)
                .unwrap_or_default()
                > self.config.idle_timeout
            {
                session.state = SessionState::Expired;
                return Err(AuthError::validation(
                    "Session expired due to inactivity".to_string(),
                ));
            }

            // Validate IP address change
            if self.config.validate_ip_address && session.current_ip != ip_address {
                self.handle_ip_change(session, ip_address)?;
            }

            // Validate user agent consistency
            if !SecureComparison::constant_time_eq(&session.user_agent, user_agent) {
                session.security_flags.cross_device_access = true;
                tracing::warn!(
                    "User agent change detected for session {}: {} -> {}",
                    session_id,
                    session.user_agent,
                    user_agent
                );
            }

            // Update activity
            session.last_accessed = now;
            session.current_ip = ip_address.to_string();

            // Check if rotation is needed
            if now.duration_since(session.created_at).unwrap_or_default()
                > self.config.rotation_interval
            {
                session.state = SessionState::RequiresRotation;
            }

            // Recalculate risk score
            let new_risk_score = self.calculate_risk_score_update(session);
            session.risk_score = new_risk_score;

            if new_risk_score > self.config.max_risk_score {
                session.state = SessionState::HighRisk;
                tracing::warn!(
                    "Session {} marked as high risk (score: {})",
                    session_id,
                    new_risk_score
                );
            }

            Ok(())
        } else {
            Err(AuthError::validation("Session not found".to_string()))
        }
    }

    /// Rotate session ID for security
    pub fn rotate_session(&self, session_id: &str) -> Result<String> {
        if let Some((_, mut session)) = self.active_sessions.remove(session_id) {
            // Generate new session ID
            let new_session_id = SecureRandomGen::generate_session_id()?;

            // Update session
            session.id = new_session_id.clone();
            session.rotation_count += 1;
            session.state = SessionState::Active;
            session.last_accessed = SystemTime::now();

            // Store with new ID
            self.active_sessions
                .insert(new_session_id.clone(), session.clone());

            // Update user session tracking with atomic operations
            if let Some(mut user_session_list) = self.user_sessions.get_mut(&session.user_id)
                && let Some(pos) = user_session_list.iter().position(|id| id == session_id)
            {
                user_session_list[pos] = new_session_id.clone();
            }

            tracing::info!(
                "Session rotated: {} -> {} (rotation count: {})",
                session_id,
                new_session_id,
                session.rotation_count
            );

            Ok(new_session_id)
        } else {
            Err(AuthError::validation(
                "Session not found for rotation".to_string(),
            ))
        }
    }

    /// Revoke a session
    pub fn revoke_session(&self, session_id: &str) -> Result<()> {
        if let Some((_, session)) = self.active_sessions.remove(session_id) {
            // Remove from user session tracking using atomic operations
            if let Some(mut user_session_list) = self.user_sessions.get_mut(&session.user_id) {
                user_session_list.retain(|id| id != session_id);
                if user_session_list.is_empty() {
                    drop(user_session_list);
                    self.user_sessions.remove(&session.user_id);
                }
            }

            // Clean up IP change tracking
            self.ip_changes.remove(session_id);

            tracing::info!(
                "Session {} revoked for user {}",
                session_id,
                session.user_id
            );

            Ok(())
        } else {
            Err(AuthError::validation(
                "Session not found for revocation".to_string(),
            ))
        }
    }

    /// Revoke all sessions for a user
    pub fn revoke_user_sessions(&self, user_id: &str) -> Result<u32> {
        if let Some((_, session_ids)) = self.user_sessions.remove(user_id) {
            let count = session_ids.len() as u32;

            for session_id in &session_ids {
                self.active_sessions.remove(session_id);
            }

            // Clean up IP change tracking
            for session_id in &session_ids {
                self.ip_changes.remove(session_id);
            }

            tracing::info!("Revoked {} sessions for user {}", count, user_id);

            Ok(count)
        } else {
            Ok(0)
        }
    }

    /// Clean up expired sessions
    pub fn cleanup_expired_sessions(&self) -> Result<u32> {
        let now = SystemTime::now();
        let mut expired_sessions = Vec::new();

        // Find expired sessions using DashMap iterator
        for session_ref in self.active_sessions.iter() {
            if session_ref.value().expires_at < now {
                expired_sessions.push(session_ref.key().clone());
            }
        }

        // Remove expired sessions
        let count = expired_sessions.len() as u32;
        for session_id in expired_sessions {
            let _ = self.revoke_session(&session_id);
        }

        if count > 0 {
            tracing::info!("Cleaned up {} expired sessions", count);
        }

        Ok(count)
    }

    /// Store session in memory (in production, use persistent storage)
    fn store_session(&self, session: SecureSession) -> Result<()> {
        self.active_sessions
            .insert(session.id.clone(), session.clone());

        self.user_sessions
            .entry(session.user_id.clone())
            .or_default()
            .push(session.id.clone());

        Ok(())
    }

    /// Enforce concurrent session limits
    fn enforce_concurrent_session_limit(&self, user_id: &str) -> Result<()> {
        let current_count = self.get_user_session_count(user_id);

        if current_count >= self.config.max_concurrent_sessions {
            // Revoke oldest session
            self.revoke_oldest_user_session(user_id)?;
        }

        Ok(())
    }

    /// Get number of active sessions for a user
    fn get_user_session_count(&self, user_id: &str) -> u32 {
        self.user_sessions
            .get(user_id)
            .map(|sessions| sessions.len() as u32)
            .unwrap_or(0)
    }

    /// Revoke the oldest session for a user
    fn revoke_oldest_user_session(&self, user_id: &str) -> Result<()> {
        let oldest_session_id = if let Some(session_ids_ref) = self.user_sessions.get(user_id) {
            let session_ids = session_ids_ref.value();
            session_ids
                .iter()
                .filter_map(|id| self.active_sessions.get(id))
                .min_by_key(|session_ref| session_ref.value().created_at)
                .map(|session_ref| session_ref.key().clone())
        } else {
            None
        };

        if let Some(session_id) = oldest_session_id {
            self.revoke_session(&session_id)?;
            tracing::info!(
                "Revoked oldest session {} for user {} due to concurrent limit",
                session_id,
                user_id
            );
        }

        Ok(())
    }

    /// Handle IP address change
    fn handle_ip_change(&self, session: &mut SecureSession, new_ip: &str) -> Result<()> {
        let mut change_count = self.ip_changes.entry(session.id.clone()).or_insert(0);
        *change_count += 1;

        if *change_count > self.config.max_ip_changes {
            session.state = SessionState::HighRisk;
            session.security_flags.suspicious_location = true;
            return Err(AuthError::validation(
                "Too many IP address changes - session marked as high risk".to_string(),
            ));
        }

        session.security_flags.suspicious_location = true;
        tracing::warn!(
            "IP address change #{} for session {}: {} -> {}",
            *change_count,
            session.id,
            session.current_ip,
            new_ip
        );

        Ok(())
    }

    /// Calculate initial risk score
    fn calculate_risk_score(
        &self,
        ip_address: &str,
        user_agent: &str,
        device_fingerprint: &Option<DeviceFingerprint>,
        secure_transport: bool,
    ) -> u8 {
        let mut score = 0u8;

        // Non-secure transport
        if !secure_transport {
            score += 30;
        }

        // Unknown or suspicious user agent
        if user_agent.is_empty() || user_agent.len() < 10 {
            score += 20;
        }

        // Missing device fingerprint
        if device_fingerprint.is_none() {
            score += 15;
        }

        // Private/local IP addresses (higher risk)
        if self.is_private_ip(ip_address) {
            score += 10;
        }

        score.min(100)
    }

    /// Update risk score based on session activity with decay for cleared conditions
    fn calculate_risk_score_update(&self, session: &SecureSession) -> u8 {
        // Start from a base score rather than the accumulated score to avoid
        // monotonic increase. Recalculate from current flags each time.
        let mut score: u8 = 0;

        // Security flag penalties (only applied when the flag is currently set)
        if session.security_flags.suspicious_location {
            score = score.saturating_add(20);
        }
        if session.security_flags.multiple_failures {
            score = score.saturating_add(25);
        }
        if session.security_flags.new_device {
            // Apply time-based decay: new_device risk decreases over session lifetime.
            // After 30 minutes of consistent activity, halve the penalty.
            let age_secs = session
                .last_accessed
                .duration_since(session.created_at)
                .unwrap_or_default()
                .as_secs();
            let penalty = if age_secs > 1800 { 7 } else { 15 };
            score = score.saturating_add(penalty);
        }
        if session.security_flags.unusual_hours {
            score = score.saturating_add(10);
        }
        if session.security_flags.cross_device_access {
            score = score.saturating_add(20);
        }

        // High concurrent sessions
        if session.concurrent_sessions > 5 {
            score = score.saturating_add(15);
        }

        // Multiple rotations (could indicate compromise)
        if session.rotation_count > 3 {
            score = score.saturating_add(10);
        }

        // Velocity check: rapid rotations suggest token theft.
        // If session has been rotated multiple times within a short window,
        // increase risk proportionally.
        if session.rotation_count > 1 {
            let age_secs = session
                .last_accessed
                .duration_since(session.created_at)
                .unwrap_or_default()
                .as_secs()
                .max(1); // avoid division by zero
            let rotations_per_minute =
                (session.rotation_count as u64).saturating_mul(60) / age_secs;
            if rotations_per_minute > 5 {
                score = score.saturating_add(20);
            } else if rotations_per_minute > 2 {
                score = score.saturating_add(10);
            }
        }

        score.min(100)
    }

    /// Check if IP address is private/internal (RFC 1918 + loopback)
    fn is_private_ip(&self, ip: &str) -> bool {
        if ip == "127.0.0.1" || ip == "::1" {
            return true;
        }
        if ip.starts_with("192.168.") || ip.starts_with("10.") {
            return true;
        }
        // RFC 1918: 172.16.0.0 – 172.31.255.255
        if let Some(rest) = ip.strip_prefix("172.") {
            if let Some(second_octet_str) = rest.split('.').next() {
                if let Ok(second_octet) = second_octet_str.parse::<u8>() {
                    return (16..=31).contains(&second_octet);
                }
            }
        }
        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_secure_session_creation() {
        let config = SecureSessionConfig::default();
        let manager = SecureSessionManager::new(config);

        let session = manager
            .create_session(
                "user123",
                "192.168.1.100",
                "Mozilla/5.0 Test Browser",
                None,
                true,
            )
            .unwrap();

        assert_eq!(session.user_id, "user123");
        assert_eq!(session.creation_ip, "192.168.1.100");
        assert!(session.security_flags.secure_transport);
        assert_eq!(session.state, SessionState::Active);
    }

    #[test]
    fn test_session_rotation() {
        let config = SecureSessionConfig::default();
        let manager = SecureSessionManager::new(config);

        let session = manager
            .create_session(
                "user123",
                "192.168.1.100",
                "Mozilla/5.0 Test Browser",
                None,
                true,
            )
            .unwrap();

        let old_id = session.id.clone();
        let new_id = manager.rotate_session(&old_id).unwrap();

        assert_ne!(old_id, new_id);
        assert!(manager.get_session(&old_id).unwrap().is_none());
        assert!(manager.get_session(&new_id).unwrap().is_some());
    }

    #[test]
    fn test_concurrent_session_limit() {
        let config = SecureSessionConfig {
            max_concurrent_sessions: 2,
            ..Default::default()
        };
        let manager = SecureSessionManager::new(config);

        // Create first session
        let session1 = manager
            .create_session(
                "user123",
                "192.168.1.100",
                "Mozilla/5.0 Test Browser",
                None,
                true,
            )
            .unwrap();

        // Create second session
        let session2 = manager
            .create_session(
                "user123",
                "192.168.1.101",
                "Mozilla/5.0 Test Browser",
                None,
                true,
            )
            .unwrap();

        // Third session should revoke the first
        let session3 = manager
            .create_session(
                "user123",
                "192.168.1.102",
                "Mozilla/5.0 Test Browser",
                None,
                true,
            )
            .unwrap();

        // First session should be revoked
        assert!(manager.get_session(&session1.id).unwrap().is_none());
        assert!(manager.get_session(&session2.id).unwrap().is_some());
        assert!(manager.get_session(&session3.id).unwrap().is_some());
    }

    #[test]
    fn test_risk_score_calculation() {
        let config = SecureSessionConfig::default();
        let manager = SecureSessionManager::new(config);

        // High risk: non-secure transport, private IP, no device fingerprint
        let risk_score = manager.calculate_risk_score("192.168.1.1", "", &None, false);

        assert!(risk_score > 50, "Risk score should be high: {}", risk_score);
    }

    #[test]
    fn test_session_cleanup() {
        let config = SecureSessionConfig {
            max_lifetime: Duration::from_millis(1), // Very short for testing
            ..Default::default()
        };
        let manager = SecureSessionManager::new(config);

        let session = manager
            .create_session(
                "user123",
                "192.168.1.100",
                "Mozilla/5.0 Test Browser",
                None,
                true,
            )
            .unwrap();

        // Wait for expiration
        std::thread::sleep(Duration::from_millis(10));

        let cleaned = manager.cleanup_expired_sessions().unwrap();
        assert_eq!(cleaned, 1);
        assert!(manager.get_session(&session.id).unwrap().is_none());
    }

    #[test]
    fn test_for_high_security_preset() {
        let config = SecureSessionConfig::for_high_security();
        assert_eq!(config.max_lifetime, Duration::from_secs(2 * 3600));
        assert_eq!(config.idle_timeout, Duration::from_secs(10 * 60));
        assert_eq!(config.max_concurrent_sessions, 1);
        assert_eq!(config.max_risk_score, 40);
        assert!(config.enable_geolocation);
        // Should still create a working manager
        let manager = SecureSessionManager::new(config);
        let session = manager.create_session("u1", "10.0.0.1", "UA", None, true).unwrap();
        assert_eq!(session.user_id, "u1");
    }

    #[test]
    fn test_for_mobile_preset() {
        let config = SecureSessionConfig::for_mobile();
        assert_eq!(config.max_lifetime, Duration::from_secs(30 * 24 * 3600));
        assert_eq!(config.max_concurrent_sessions, 5);
        assert!(!config.validate_ip_address);
        let manager = SecureSessionManager::new(config);
        let session = manager.create_session("u2", "10.0.0.2", "iOS", None, true).unwrap();
        assert_eq!(session.user_id, "u2");
    }
}