1use 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#[derive(Clone, Serialize, Deserialize)]
13pub struct SecureSession {
14 pub id: String,
16
17 pub user_id: String,
19
20 pub created_at: SystemTime,
22
23 pub last_accessed: SystemTime,
25
26 pub expires_at: SystemTime,
28
29 pub state: SessionState,
31
32 pub device_fingerprint: DeviceFingerprint,
34
35 pub creation_ip: String,
37
38 pub current_ip: String,
40
41 pub user_agent: String,
43
44 pub mfa_verified: bool,
46
47 pub security_flags: SecurityFlags,
49
50 pub metadata: HashMap<String, String>,
52
53 pub concurrent_sessions: u32,
55
56 pub risk_score: u8,
58
59 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#[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#[derive(Debug, Clone, Serialize, Deserialize, ZeroizeOnDrop)]
100pub struct DeviceFingerprint {
101 pub browser_hash: String,
103
104 pub screen_resolution: Option<String>,
106
107 pub timezone_offset: Option<i32>,
109
110 pub platform: Option<String>,
112
113 pub languages: Vec<String>,
115
116 pub canvas_hash: Option<String>,
118
119 pub webgl_hash: Option<String>,
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize, Default)]
125pub struct SecurityFlags {
126 pub secure_transport: bool,
128
129 pub suspicious_location: bool,
131
132 pub multiple_failures: bool,
134
135 pub new_device: bool,
137
138 pub unusual_hours: bool,
140
141 pub high_privilege_ops: bool,
143
144 pub cross_device_access: bool,
146}
147
148#[derive(Debug, Clone)]
150pub struct SecureSessionConfig {
151 pub max_lifetime: Duration,
153
154 pub idle_timeout: Duration,
156
157 pub max_concurrent_sessions: u32,
159
160 pub rotation_interval: Duration,
162
163 pub require_secure_transport: bool,
165
166 pub enable_device_fingerprinting: bool,
168
169 pub max_risk_score: u8,
171
172 pub validate_ip_address: bool,
174
175 pub max_ip_changes: u32,
177
178 pub enable_geolocation: bool,
180}
181
182impl Default for SecureSessionConfig {
183 fn default() -> Self {
184 Self {
185 max_lifetime: Duration::from_secs(8 * 3600), idle_timeout: Duration::from_secs(30 * 60), max_concurrent_sessions: 3,
188 rotation_interval: Duration::from_secs(3600), 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, }
196 }
197}
198
199pub struct SecureSessionManager {
201 config: SecureSessionConfig,
202 active_sessions: Arc<DashMap<String, SecureSession>>,
203 user_sessions: Arc<DashMap<String, Vec<String>>>, ip_changes: Arc<DashMap<String, u32>>, }
206
207impl SecureSessionManager {
208 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 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 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 self.enforce_concurrent_session_limit(user_id)?;
236
237 let session_id = SecureRandomGen::generate_session_id()?;
239
240 let now = SystemTime::now();
241 let expires_at = now + self.config.max_lifetime;
242
243 let risk_score = self.calculate_risk_score(
245 ip_address,
246 user_agent,
247 &device_fingerprint,
248 secure_transport,
249 );
250
251 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 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 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 if session.expires_at < SystemTime::now() {
308 drop(session_ref);
309 self.revoke_session(session_id)?;
310 return Ok(None);
311 }
312
313 match session.state {
315 SessionState::Active => Ok(Some(session)),
316 SessionState::RequiresMfa => Ok(Some(session)),
317 SessionState::RequiresRotation => Ok(Some(session)),
318 _ => Ok(None), }
320 } else {
321 Ok(None)
322 }
323 }
324
325 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 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 if self.config.validate_ip_address && session.current_ip != ip_address {
350 self.handle_ip_change(session, ip_address)?;
351 }
352
353 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 session.last_accessed = now;
366 session.current_ip = ip_address.to_string();
367
368 if now.duration_since(session.created_at).unwrap_or_default()
370 > self.config.rotation_interval
371 {
372 session.state = SessionState::RequiresRotation;
373 }
374
375 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 pub fn rotate_session(&self, session_id: &str) -> Result<String> {
396 if let Some((_, mut session)) = self.active_sessions.remove(session_id) {
397 let new_session_id = SecureRandomGen::generate_session_id()?;
399
400 session.id = new_session_id.clone();
402 session.rotation_count += 1;
403 session.state = SessionState::Active;
404 session.last_accessed = SystemTime::now();
405
406 self.active_sessions
408 .insert(new_session_id.clone(), session.clone());
409
410 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 pub fn revoke_session(&self, session_id: &str) -> Result<()> {
434 if let Some((_, session)) = self.active_sessions.remove(session_id) {
435 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 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 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 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 pub fn cleanup_expired_sessions(&self) -> Result<u32> {
485 let now = SystemTime::now();
486 let mut expired_sessions = Vec::new();
487
488 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 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 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 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 self.revoke_oldest_user_session(user_id)?;
528 }
529
530 Ok(())
531 }
532
533 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 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 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 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 if !secure_transport {
603 score += 30;
604 }
605
606 if user_agent.is_empty() || user_agent.len() < 10 {
608 score += 20;
609 }
610
611 if device_fingerprint.is_none() {
613 score += 15;
614 }
615
616 if self.is_private_ip(ip_address) {
618 score += 10;
619 }
620
621 score.min(100)
622 }
623
624 fn calculate_risk_score_update(&self, session: &SecureSession) -> u8 {
626 let mut score = session.risk_score;
627
628 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 if session.concurrent_sessions > 5 {
647 score = score.saturating_add(15);
648 }
649
650 if session.rotation_count > 3 {
652 score = score.saturating_add(10);
653 }
654
655 score.min(100)
656 }
657
658 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 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 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 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 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 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), ..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 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}