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 dashmap::DashMap;
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7use std::sync::Arc;
8use std::time::{Duration, SystemTime};
9use zeroize::ZeroizeOnDrop;
10
11/// Secure session with enhanced security properties
12#[derive(Clone, Serialize, Deserialize)]
13pub struct SecureSession {
14    /// Cryptographically secure session ID
15    pub id: String,
16
17    /// User ID associated with this session
18    pub user_id: String,
19
20    /// Session creation timestamp
21    pub created_at: SystemTime,
22
23    /// Last activity timestamp
24    pub last_accessed: SystemTime,
25
26    /// Session expiration time
27    pub expires_at: SystemTime,
28
29    /// Session state
30    pub state: SessionState,
31
32    /// Device fingerprint for security tracking
33    pub device_fingerprint: DeviceFingerprint,
34
35    /// IP address where session was created
36    pub creation_ip: String,
37
38    /// Current IP address
39    pub current_ip: String,
40
41    /// User agent string
42    pub user_agent: String,
43
44    /// MFA verification status
45    pub mfa_verified: bool,
46
47    /// Security flags
48    pub security_flags: SecurityFlags,
49
50    /// Session metadata
51    pub metadata: HashMap<String, String>,
52
53    /// Number of concurrent sessions for this user
54    pub concurrent_sessions: u32,
55
56    /// Session risk score (0-100)
57    pub risk_score: u8,
58
59    /// Session rotation count
60    pub rotation_count: u32,
61}
62
63impl std::fmt::Debug for SecureSession {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        let mut d = f.debug_struct("SecureSession");
66        d.field("id", &crate::utils::redact::redacted(&self.id));
67        d.field("user_id", &self.user_id);
68        d.field("created_at", &self.created_at);
69        d.field("last_accessed", &self.last_accessed);
70        d.field("expires_at", &self.expires_at);
71        d.field("state", &self.state);
72        d.field("device_fingerprint", &self.device_fingerprint);
73        d.field("creation_ip", &self.creation_ip);
74        d.field("current_ip", &self.current_ip);
75        d.field("user_agent", &self.user_agent);
76        d.field("mfa_verified", &self.mfa_verified);
77        d.field("security_flags", &self.security_flags);
78        d.field("metadata", &self.metadata);
79        d.field("concurrent_sessions", &self.concurrent_sessions);
80        d.field("risk_score", &self.risk_score);
81        d.field("rotation_count", &self.rotation_count);
82        d.finish()
83    }
84}
85
86/// Session state with security considerations
87#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
88pub enum SessionState {
89    Active,
90    Expired,
91    Revoked,
92    Suspended,
93    RequiresMfa,
94    RequiresRotation,
95    HighRisk,
96}
97
98/// Device fingerprint for tracking sessions
99#[derive(Debug, Clone, Serialize, Deserialize, ZeroizeOnDrop)]
100pub struct DeviceFingerprint {
101    /// Browser fingerprint hash
102    pub browser_hash: String,
103
104    /// Screen resolution
105    pub screen_resolution: Option<String>,
106
107    /// Timezone offset
108    pub timezone_offset: Option<i32>,
109
110    /// Platform information
111    pub platform: Option<String>,
112
113    /// Language preferences
114    pub languages: Vec<String>,
115
116    /// Canvas fingerprint
117    pub canvas_hash: Option<String>,
118
119    /// WebGL fingerprint
120    pub webgl_hash: Option<String>,
121}
122
123/// Security flags for session management
124#[derive(Debug, Clone, Serialize, Deserialize, Default)]
125pub struct SecurityFlags {
126    /// Session created over secure transport (HTTPS)
127    pub secure_transport: bool,
128
129    /// Session accessed from suspicious location
130    pub suspicious_location: bool,
131
132    /// Multiple failed authentication attempts
133    pub multiple_failures: bool,
134
135    /// Session accessed from new device
136    pub new_device: bool,
137
138    /// Session accessed outside normal hours
139    pub unusual_hours: bool,
140
141    /// High-privilege operations performed
142    pub high_privilege_ops: bool,
143
144    /// Session shared across devices (security risk)
145    pub cross_device_access: bool,
146}
147
148/// Secure session configuration
149#[derive(Debug, Clone)]
150pub struct SecureSessionConfig {
151    /// Maximum session lifetime
152    pub max_lifetime: Duration,
153
154    /// Session idle timeout
155    pub idle_timeout: Duration,
156
157    /// Maximum concurrent sessions per user
158    pub max_concurrent_sessions: u32,
159
160    /// Force session rotation interval
161    pub rotation_interval: Duration,
162
163    /// Require secure transport (HTTPS)
164    pub require_secure_transport: bool,
165
166    /// Enable device fingerprinting
167    pub enable_device_fingerprinting: bool,
168
169    /// Maximum allowed risk score
170    pub max_risk_score: u8,
171
172    /// Enable IP address validation
173    pub validate_ip_address: bool,
174
175    /// Maximum IP address changes per session
176    pub max_ip_changes: u32,
177
178    /// Enable geolocation tracking
179    pub enable_geolocation: bool,
180}
181
182impl Default for SecureSessionConfig {
183    fn default() -> Self {
184        Self {
185            max_lifetime: Duration::from_secs(8 * 3600), // 8 hours
186            idle_timeout: Duration::from_secs(30 * 60),  // 30 minutes
187            max_concurrent_sessions: 3,
188            rotation_interval: Duration::from_secs(3600), // 1 hour
189            require_secure_transport: true,
190            enable_device_fingerprinting: true,
191            max_risk_score: 70,
192            validate_ip_address: true,
193            max_ip_changes: 3,
194            enable_geolocation: false, // Requires external service
195        }
196    }
197}
198
199/// Secure session manager with comprehensive security controls
200pub struct SecureSessionManager {
201    config: SecureSessionConfig,
202    active_sessions: Arc<DashMap<String, SecureSession>>,
203    user_sessions: Arc<DashMap<String, Vec<String>>>, // user_id -> session_ids
204    ip_changes: Arc<DashMap<String, u32>>,            // session_id -> change_count
205}
206
207impl SecureSessionManager {
208    /// Create a new secure session manager
209    pub fn new(config: SecureSessionConfig) -> Self {
210        Self {
211            config,
212            active_sessions: Arc::new(DashMap::new()),
213            user_sessions: Arc::new(DashMap::new()),
214            ip_changes: Arc::new(DashMap::new()),
215        }
216    }
217
218    /// Create a new secure session
219    pub fn create_session(
220        &self,
221        user_id: &str,
222        ip_address: &str,
223        user_agent: &str,
224        device_fingerprint: Option<DeviceFingerprint>,
225        secure_transport: bool,
226    ) -> Result<SecureSession> {
227        // Validate security requirements
228        if self.config.require_secure_transport && !secure_transport {
229            return Err(AuthError::validation(
230                "Session must be created over secure transport (HTTPS)".to_string(),
231            ));
232        }
233
234        // Check concurrent session limits
235        self.enforce_concurrent_session_limit(user_id)?;
236
237        // Generate secure session ID
238        let session_id = SecureRandomGen::generate_session_id()?;
239
240        let now = SystemTime::now();
241        let expires_at = now + self.config.max_lifetime;
242
243        // Calculate initial risk score
244        let risk_score = self.calculate_risk_score(
245            ip_address,
246            user_agent,
247            &device_fingerprint,
248            secure_transport,
249        );
250
251        // Get concurrent session count
252        let concurrent_sessions = self.get_user_session_count(user_id);
253
254        let session = SecureSession {
255            id: session_id.clone(),
256            user_id: user_id.to_string(),
257            created_at: now,
258            last_accessed: now,
259            expires_at,
260            state: if risk_score > self.config.max_risk_score {
261                SessionState::HighRisk
262            } else {
263                SessionState::Active
264            },
265            device_fingerprint: device_fingerprint.unwrap_or_else(|| DeviceFingerprint {
266                browser_hash: "unknown".to_string(),
267                screen_resolution: None,
268                timezone_offset: None,
269                platform: None,
270                languages: vec![],
271                canvas_hash: None,
272                webgl_hash: None,
273            }),
274            creation_ip: ip_address.to_string(),
275            current_ip: ip_address.to_string(),
276            user_agent: user_agent.to_string(),
277            mfa_verified: false,
278            security_flags: SecurityFlags {
279                secure_transport,
280                ..SecurityFlags::default()
281            },
282            metadata: HashMap::new(),
283            concurrent_sessions,
284            risk_score,
285            rotation_count: 0,
286        };
287
288        // Store session
289        self.store_session(session.clone())?;
290
291        tracing::info!(
292            "Created secure session {} for user {} (risk score: {})",
293            crate::utils::redact::fingerprint(&session_id),
294            user_id,
295            risk_score
296        );
297
298        Ok(session)
299    }
300
301    /// Validate and retrieve session
302    pub fn get_session(&self, session_id: &str) -> Result<Option<SecureSession>> {
303        if let Some(session_ref) = self.active_sessions.get(session_id) {
304            let session = session_ref.value().clone();
305
306            // Check if session is expired
307            if session.expires_at < SystemTime::now() {
308                drop(session_ref);
309                self.revoke_session(session_id)?;
310                return Ok(None);
311            }
312
313            // Check session state
314            match session.state {
315                SessionState::Active => Ok(Some(session)),
316                SessionState::RequiresMfa => Ok(Some(session)),
317                SessionState::RequiresRotation => Ok(Some(session)),
318                _ => Ok(None), // Expired, revoked, suspended, high risk
319            }
320        } else {
321            Ok(None)
322        }
323    }
324
325    /// Update session activity and validate security
326    pub fn update_session_activity(
327        &self,
328        session_id: &str,
329        ip_address: &str,
330        user_agent: &str,
331    ) -> Result<()> {
332        if let Some(mut session_entry) = self.active_sessions.get_mut(session_id) {
333            let session = session_entry.value_mut();
334            let now = SystemTime::now();
335
336            // Check idle timeout
337            if now
338                .duration_since(session.last_accessed)
339                .unwrap_or_default()
340                > self.config.idle_timeout
341            {
342                session.state = SessionState::Expired;
343                return Err(AuthError::validation(
344                    "Session expired due to inactivity".to_string(),
345                ));
346            }
347
348            // Validate IP address change
349            if self.config.validate_ip_address && session.current_ip != ip_address {
350                self.handle_ip_change(session, ip_address)?;
351            }
352
353            // Validate user agent consistency
354            if !SecureComparison::constant_time_eq(&session.user_agent, user_agent) {
355                session.security_flags.cross_device_access = true;
356                tracing::warn!(
357                    "User agent change detected for session {}: {} -> {}",
358                    crate::utils::redact::fingerprint(session_id),
359                    session.user_agent,
360                    user_agent
361                );
362            }
363
364            // Update activity
365            session.last_accessed = now;
366            session.current_ip = ip_address.to_string();
367
368            // Check if rotation is needed
369            if now.duration_since(session.created_at).unwrap_or_default()
370                > self.config.rotation_interval
371            {
372                session.state = SessionState::RequiresRotation;
373            }
374
375            // Recalculate risk score
376            let new_risk_score = self.calculate_risk_score_update(session);
377            session.risk_score = new_risk_score;
378
379            if new_risk_score > self.config.max_risk_score {
380                session.state = SessionState::HighRisk;
381                tracing::warn!(
382                    "Session {} marked as high risk (score: {})",
383                    crate::utils::redact::fingerprint(session_id),
384                    new_risk_score
385                );
386            }
387
388            Ok(())
389        } else {
390            Err(AuthError::validation("Session not found".to_string()))
391        }
392    }
393
394    /// Rotate session ID for security
395    pub fn rotate_session(&self, session_id: &str) -> Result<String> {
396        if let Some((_, mut session)) = self.active_sessions.remove(session_id) {
397            // Generate new session ID
398            let new_session_id = SecureRandomGen::generate_session_id()?;
399
400            // Update session
401            session.id = new_session_id.clone();
402            session.rotation_count += 1;
403            session.state = SessionState::Active;
404            session.last_accessed = SystemTime::now();
405
406            // Store with new ID
407            self.active_sessions
408                .insert(new_session_id.clone(), session.clone());
409
410            // Update user session tracking with atomic operations
411            if let Some(mut user_session_list) = self.user_sessions.get_mut(&session.user_id)
412                && let Some(pos) = user_session_list.iter().position(|id| id == session_id)
413            {
414                user_session_list[pos] = new_session_id.clone();
415            }
416
417            tracing::info!(
418                "Session rotated: {} -> {} (rotation count: {})",
419                crate::utils::redact::fingerprint(session_id),
420                crate::utils::redact::fingerprint(&new_session_id),
421                session.rotation_count
422            );
423
424            Ok(new_session_id)
425        } else {
426            Err(AuthError::validation(
427                "Session not found for rotation".to_string(),
428            ))
429        }
430    }
431
432    /// Revoke a session
433    pub fn revoke_session(&self, session_id: &str) -> Result<()> {
434        if let Some((_, session)) = self.active_sessions.remove(session_id) {
435            // Remove from user session tracking using atomic operations
436            if let Some(mut user_session_list) = self.user_sessions.get_mut(&session.user_id) {
437                user_session_list.retain(|id| id != session_id);
438                if user_session_list.is_empty() {
439                    drop(user_session_list);
440                    self.user_sessions.remove(&session.user_id);
441                }
442            }
443
444            // Clean up IP change tracking
445            self.ip_changes.remove(session_id);
446
447            tracing::info!(
448                "Session {} revoked for user {}",
449                crate::utils::redact::fingerprint(session_id),
450                session.user_id
451            );
452
453            Ok(())
454        } else {
455            Err(AuthError::validation(
456                "Session not found for revocation".to_string(),
457            ))
458        }
459    }
460
461    /// Revoke all sessions for a user
462    pub fn revoke_user_sessions(&self, user_id: &str) -> Result<u32> {
463        if let Some((_, session_ids)) = self.user_sessions.remove(user_id) {
464            let count = session_ids.len() as u32;
465
466            for session_id in &session_ids {
467                self.active_sessions.remove(session_id);
468            }
469
470            // Clean up IP change tracking
471            for session_id in &session_ids {
472                self.ip_changes.remove(session_id);
473            }
474
475            tracing::info!("Revoked {} sessions for user {}", count, user_id);
476
477            Ok(count)
478        } else {
479            Ok(0)
480        }
481    }
482
483    /// Clean up expired sessions
484    pub fn cleanup_expired_sessions(&self) -> Result<u32> {
485        let now = SystemTime::now();
486        let mut expired_sessions = Vec::new();
487
488        // Find expired sessions using DashMap iterator
489        for session_ref in self.active_sessions.iter() {
490            if session_ref.value().expires_at < now {
491                expired_sessions.push(session_ref.key().clone());
492            }
493        }
494
495        // Remove expired sessions
496        let count = expired_sessions.len() as u32;
497        for session_id in expired_sessions {
498            let _ = self.revoke_session(&session_id);
499        }
500
501        if count > 0 {
502            tracing::info!("Cleaned up {} expired sessions", count);
503        }
504
505        Ok(count)
506    }
507
508    /// Store session in memory (in production, use persistent storage)
509    fn store_session(&self, session: SecureSession) -> Result<()> {
510        self.active_sessions
511            .insert(session.id.clone(), session.clone());
512
513        self.user_sessions
514            .entry(session.user_id.clone())
515            .or_default()
516            .push(session.id.clone());
517
518        Ok(())
519    }
520
521    /// Enforce concurrent session limits
522    fn enforce_concurrent_session_limit(&self, user_id: &str) -> Result<()> {
523        let current_count = self.get_user_session_count(user_id);
524
525        if current_count >= self.config.max_concurrent_sessions {
526            // Revoke oldest session
527            self.revoke_oldest_user_session(user_id)?;
528        }
529
530        Ok(())
531    }
532
533    /// Get number of active sessions for a user
534    fn get_user_session_count(&self, user_id: &str) -> u32 {
535        self.user_sessions
536            .get(user_id)
537            .map(|sessions| sessions.len() as u32)
538            .unwrap_or(0)
539    }
540
541    /// Revoke the oldest session for a user
542    fn revoke_oldest_user_session(&self, user_id: &str) -> Result<()> {
543        let oldest_session_id = if let Some(session_ids_ref) = self.user_sessions.get(user_id) {
544            let session_ids = session_ids_ref.value();
545            session_ids
546                .iter()
547                .filter_map(|id| self.active_sessions.get(id))
548                .min_by_key(|session_ref| session_ref.value().created_at)
549                .map(|session_ref| session_ref.key().clone())
550        } else {
551            None
552        };
553
554        if let Some(session_id) = oldest_session_id {
555            self.revoke_session(&session_id)?;
556            tracing::info!(
557                "Revoked oldest session {} for user {} due to concurrent limit",
558                crate::utils::redact::fingerprint(&session_id),
559                user_id
560            );
561        }
562
563        Ok(())
564    }
565
566    /// Handle IP address change
567    fn handle_ip_change(&self, session: &mut SecureSession, new_ip: &str) -> Result<()> {
568        let mut change_count = self.ip_changes.entry(session.id.clone()).or_insert(0);
569        *change_count += 1;
570
571        if *change_count > self.config.max_ip_changes {
572            session.state = SessionState::HighRisk;
573            session.security_flags.suspicious_location = true;
574            return Err(AuthError::validation(
575                "Too many IP address changes - session marked as high risk".to_string(),
576            ));
577        }
578
579        session.security_flags.suspicious_location = true;
580        tracing::warn!(
581            "IP address change #{} for session {}: {} -> {}",
582            *change_count,
583            crate::utils::redact::fingerprint(&session.id),
584            session.current_ip,
585            new_ip
586        );
587
588        Ok(())
589    }
590
591    /// Calculate initial risk score
592    fn calculate_risk_score(
593        &self,
594        ip_address: &str,
595        user_agent: &str,
596        device_fingerprint: &Option<DeviceFingerprint>,
597        secure_transport: bool,
598    ) -> u8 {
599        let mut score = 0u8;
600
601        // Non-secure transport
602        if !secure_transport {
603            score += 30;
604        }
605
606        // Unknown or suspicious user agent
607        if user_agent.is_empty() || user_agent.len() < 10 {
608            score += 20;
609        }
610
611        // Missing device fingerprint
612        if device_fingerprint.is_none() {
613            score += 15;
614        }
615
616        // Private/local IP addresses (higher risk)
617        if self.is_private_ip(ip_address) {
618            score += 10;
619        }
620
621        score.min(100)
622    }
623
624    /// Update risk score based on session activity
625    fn calculate_risk_score_update(&self, session: &SecureSession) -> u8 {
626        let mut score = session.risk_score;
627
628        // Security flag penalties
629        if session.security_flags.suspicious_location {
630            score = score.saturating_add(20);
631        }
632        if session.security_flags.multiple_failures {
633            score = score.saturating_add(25);
634        }
635        if session.security_flags.new_device {
636            score = score.saturating_add(15);
637        }
638        if session.security_flags.unusual_hours {
639            score = score.saturating_add(10);
640        }
641        if session.security_flags.cross_device_access {
642            score = score.saturating_add(20);
643        }
644
645        // High concurrent sessions
646        if session.concurrent_sessions > 5 {
647            score = score.saturating_add(15);
648        }
649
650        // Multiple rotations (could indicate compromise)
651        if session.rotation_count > 3 {
652            score = score.saturating_add(10);
653        }
654
655        score.min(100)
656    }
657
658    /// Check if IP address is private/internal
659    fn is_private_ip(&self, ip: &str) -> bool {
660        ip.starts_with("192.168.")
661            || ip.starts_with("10.")
662            || ip.starts_with("172.")
663            || ip == "127.0.0.1"
664            || ip == "::1"
665    }
666}
667
668#[cfg(test)]
669mod tests {
670    use super::*;
671
672    #[test]
673    fn test_secure_session_creation() {
674        let config = SecureSessionConfig::default();
675        let manager = SecureSessionManager::new(config);
676
677        let session = manager
678            .create_session(
679                "user123",
680                "192.168.1.100",
681                "Mozilla/5.0 Test Browser",
682                None,
683                true,
684            )
685            .unwrap();
686
687        assert_eq!(session.user_id, "user123");
688        assert_eq!(session.creation_ip, "192.168.1.100");
689        assert!(session.security_flags.secure_transport);
690        assert_eq!(session.state, SessionState::Active);
691    }
692
693    #[test]
694    fn test_session_rotation() {
695        let config = SecureSessionConfig::default();
696        let manager = SecureSessionManager::new(config);
697
698        let session = manager
699            .create_session(
700                "user123",
701                "192.168.1.100",
702                "Mozilla/5.0 Test Browser",
703                None,
704                true,
705            )
706            .unwrap();
707
708        let old_id = session.id.clone();
709        let new_id = manager.rotate_session(&old_id).unwrap();
710
711        assert_ne!(old_id, new_id);
712        assert!(manager.get_session(&old_id).unwrap().is_none());
713        assert!(manager.get_session(&new_id).unwrap().is_some());
714    }
715
716    #[test]
717    fn test_concurrent_session_limit() {
718        let config = SecureSessionConfig {
719            max_concurrent_sessions: 2,
720            ..Default::default()
721        };
722        let manager = SecureSessionManager::new(config);
723
724        // Create first session
725        let session1 = manager
726            .create_session(
727                "user123",
728                "192.168.1.100",
729                "Mozilla/5.0 Test Browser",
730                None,
731                true,
732            )
733            .unwrap();
734
735        // Create second session
736        let session2 = manager
737            .create_session(
738                "user123",
739                "192.168.1.101",
740                "Mozilla/5.0 Test Browser",
741                None,
742                true,
743            )
744            .unwrap();
745
746        // Third session should revoke the first
747        let session3 = manager
748            .create_session(
749                "user123",
750                "192.168.1.102",
751                "Mozilla/5.0 Test Browser",
752                None,
753                true,
754            )
755            .unwrap();
756
757        // First session should be revoked
758        assert!(manager.get_session(&session1.id).unwrap().is_none());
759        assert!(manager.get_session(&session2.id).unwrap().is_some());
760        assert!(manager.get_session(&session3.id).unwrap().is_some());
761    }
762
763    #[test]
764    fn test_risk_score_calculation() {
765        let config = SecureSessionConfig::default();
766        let manager = SecureSessionManager::new(config);
767
768        // High risk: non-secure transport, private IP, no device fingerprint
769        let risk_score = manager.calculate_risk_score("192.168.1.1", "", &None, false);
770
771        assert!(risk_score > 50, "Risk score should be high: {}", risk_score);
772    }
773
774    #[test]
775    fn test_session_cleanup() {
776        let config = SecureSessionConfig {
777            max_lifetime: Duration::from_millis(1), // Very short for testing
778            ..Default::default()
779        };
780        let manager = SecureSessionManager::new(config);
781
782        let session = manager
783            .create_session(
784                "user123",
785                "192.168.1.100",
786                "Mozilla/5.0 Test Browser",
787                None,
788                true,
789            )
790            .unwrap();
791
792        // Wait for expiration
793        std::thread::sleep(Duration::from_millis(10));
794
795        let cleaned = manager.cleanup_expired_sessions().unwrap();
796        assert_eq!(cleaned, 1);
797        assert!(manager.get_session(&session.id).unwrap().is_none());
798    }
799}