synapse-waf 0.9.0

High-performance WAF and reverse proxy with embedded intelligence — built on Cloudflare Pingora
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
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
//! Thread-safe session manager using DashMap for concurrent access.
//!
//! Implements session tracking with LRU eviction and hijack detection via JA4 fingerprint binding.

use std::net::IpAddr;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use tokio::sync::Notify;

// ============================================================================
// Session Decision
// ============================================================================

/// Session validation decision returned by `validate_request`.
#[derive(Debug, Clone, PartialEq)]
pub enum SessionDecision {
    /// Session is valid, continue processing.
    Valid,
    /// Session is new, tracking initiated.
    New,
    /// Session may be hijacked - contains the alert details.
    Suspicious(HijackAlert),
    /// Session has expired (TTL or idle timeout exceeded).
    Expired,
    /// Session is invalid for the specified reason.
    Invalid(String),
}

// ============================================================================
// Hijack Alert
// ============================================================================

/// Alert for potential session hijacking.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HijackAlert {
    /// Session ID that may be hijacked.
    pub session_id: String,
    /// Type of hijacking detected.
    pub alert_type: HijackType,
    /// Original bound value (e.g., original JA4 fingerprint).
    pub original_value: String,
    /// New value that triggered the alert.
    pub new_value: String,
    /// Timestamp when the alert was generated (ms since epoch).
    pub timestamp: u64,
    /// Confidence level of the hijack detection (0.0 - 1.0).
    pub confidence: f64,
}

/// Type of session hijacking detected.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum HijackType {
    /// JA4 TLS fingerprint mismatch (high confidence).
    Ja4Mismatch,
    /// IP address changed unexpectedly.
    IpChange,
    /// Impossible travel detected (IP geolocation suggests impossible speed).
    ImpossibleTravel,
    /// Session token rotation detected unexpectedly.
    TokenRotation,
}

// ============================================================================
// Session State
// ============================================================================

/// Per-session state tracking.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionState {
    /// Unique session identifier (UUID v4).
    pub session_id: String,
    /// Hash of the session token (used as primary key).
    pub token_hash: String,
    /// Associated actor ID (if bound to an actor).
    pub actor_id: Option<String>,
    /// Creation timestamp (ms since epoch).
    pub creation_time: u64,
    /// Last activity timestamp (ms since epoch).
    pub last_activity: u64,
    /// Total request count for this session.
    pub request_count: u64,
    /// Bound JA4 fingerprint (for hijack detection).
    pub bound_ja4: Option<String>,
    /// Bound IP address (for strict mode hijack detection).
    pub bound_ip: Option<IpAddr>,
    /// Whether this session is flagged as suspicious.
    pub is_suspicious: bool,
    /// History of hijack alerts for this session.
    pub hijack_alerts: Vec<HijackAlert>,
}

impl SessionState {
    /// Create a new session state.
    pub fn new(session_id: String, token_hash: String) -> Self {
        let now = now_ms();
        Self {
            session_id,
            token_hash,
            actor_id: None,
            creation_time: now,
            last_activity: now,
            request_count: 0,
            bound_ja4: None,
            bound_ip: None,
            is_suspicious: false,
            hijack_alerts: Vec::new(),
        }
    }

    /// Update last activity timestamp and increment request count.
    pub fn touch(&mut self) {
        self.last_activity = now_ms();
        self.request_count += 1;
    }

    /// Bind JA4 fingerprint to this session.
    pub fn bind_ja4(&mut self, ja4: String) {
        if self.bound_ja4.is_none() && !ja4.is_empty() {
            self.bound_ja4 = Some(ja4);
        }
    }

    /// Bind IP address to this session.
    pub fn bind_ip(&mut self, ip: IpAddr) {
        if self.bound_ip.is_none() {
            self.bound_ip = Some(ip);
        }
    }

    /// Add a hijack alert to this session.
    pub fn add_alert(&mut self, alert: HijackAlert) {
        self.is_suspicious = true;
        self.hijack_alerts.push(alert);
    }
}

// ============================================================================
// Session Configuration
// ============================================================================

/// Configuration for SessionManager.
#[derive(Debug, Clone)]
pub struct SessionConfig {
    /// Maximum number of sessions to track (LRU eviction when exceeded).
    /// Default: 50,000
    pub max_sessions: usize,

    /// Session time-to-live in seconds (absolute expiration).
    /// Default: 3600 (1 hour)
    pub session_ttl_secs: u64,

    /// Idle timeout in seconds (inactivity expiration).
    /// Default: 900 (15 minutes)
    pub idle_timeout_secs: u64,

    /// Interval in seconds between cleanup cycles.
    /// Default: 300 (5 minutes)
    pub cleanup_interval_secs: u64,

    /// Enable JA4 fingerprint binding for hijack detection.
    /// Default: true
    pub enable_ja4_binding: bool,

    /// Enable IP binding for strict mode hijack detection.
    /// Default: false (can cause false positives for mobile users)
    pub enable_ip_binding: bool,

    /// Number of JA4 mismatches before alerting (0 = immediate).
    /// Default: 1 (immediate alert on mismatch)
    pub ja4_mismatch_threshold: u32,

    /// Window in seconds to allow IP changes (for mobile/VPN users).
    /// Default: 60 seconds
    pub ip_change_window_secs: u64,

    /// Maximum number of hijack alerts to store per session.
    /// Default: 10
    pub max_alerts_per_session: usize,

    /// Whether session tracking is enabled.
    /// Default: true
    pub enabled: bool,
}

impl Default for SessionConfig {
    fn default() -> Self {
        Self {
            max_sessions: 50_000,
            session_ttl_secs: 3600,
            idle_timeout_secs: 900,
            cleanup_interval_secs: 300,
            enable_ja4_binding: true,
            enable_ip_binding: false,
            ja4_mismatch_threshold: 1,
            ip_change_window_secs: 60,
            max_alerts_per_session: 10,
            enabled: true,
        }
    }
}

// ============================================================================
// Session Statistics
// ============================================================================

/// Statistics for monitoring the session manager.
#[derive(Debug, Default)]
pub struct SessionStats {
    /// Total number of sessions currently tracked.
    pub total_sessions: AtomicU64,
    /// Number of active sessions (not expired).
    pub active_sessions: AtomicU64,
    /// Number of suspicious sessions.
    pub suspicious_sessions: AtomicU64,
    /// Total hijack alerts generated.
    pub hijack_alerts: AtomicU64,
    /// Total sessions expired (TTL or idle).
    pub expired_sessions: AtomicU64,
    /// Total sessions evicted due to LRU capacity.
    pub evictions: AtomicU64,
    /// Total sessions created.
    pub total_created: AtomicU64,
    /// Total sessions invalidated.
    pub total_invalidated: AtomicU64,
}

impl SessionStats {
    /// Create a new stats instance.
    pub fn new() -> Self {
        Self::default()
    }

    /// Get a snapshot of the current statistics.
    pub fn snapshot(&self) -> SessionStatsSnapshot {
        SessionStatsSnapshot {
            total_sessions: self.total_sessions.load(Ordering::Relaxed),
            active_sessions: self.active_sessions.load(Ordering::Relaxed),
            suspicious_sessions: self.suspicious_sessions.load(Ordering::Relaxed),
            hijack_alerts: self.hijack_alerts.load(Ordering::Relaxed),
            expired_sessions: self.expired_sessions.load(Ordering::Relaxed),
            evictions: self.evictions.load(Ordering::Relaxed),
            total_created: self.total_created.load(Ordering::Relaxed),
            total_invalidated: self.total_invalidated.load(Ordering::Relaxed),
        }
    }
}

/// Snapshot of session statistics (for serialization).
#[derive(Debug, Clone, Serialize)]
pub struct SessionStatsSnapshot {
    pub total_sessions: u64,
    pub active_sessions: u64,
    pub suspicious_sessions: u64,
    pub hijack_alerts: u64,
    pub expired_sessions: u64,
    pub evictions: u64,
    pub total_created: u64,
    pub total_invalidated: u64,
}

// ============================================================================
// Session Manager
// ============================================================================

/// Manages session state with LRU eviction and hijack detection.
///
/// Thread-safe implementation using DashMap for lock-free concurrent access.
pub struct SessionManager {
    /// Sessions by token_hash (primary storage).
    sessions: DashMap<String, SessionState>,

    /// Session ID to token_hash mapping (for lookup by session ID).
    session_by_id: DashMap<String, String>,

    /// Actor ID to session IDs mapping (for listing actor's sessions).
    actor_sessions: DashMap<String, Vec<String>>,

    /// Configuration.
    config: SessionConfig,

    /// Statistics.
    stats: Arc<SessionStats>,

    /// Shutdown signal for background tasks.
    shutdown: Arc<Notify>,

    /// Touch counter for lazy eviction.
    touch_counter: AtomicU32,
}

impl SessionManager {
    /// Create a new session manager with the given configuration.
    pub fn new(config: SessionConfig) -> Self {
        Self {
            sessions: DashMap::with_capacity(config.max_sessions),
            session_by_id: DashMap::with_capacity(config.max_sessions),
            actor_sessions: DashMap::with_capacity(config.max_sessions / 10),
            config,
            stats: Arc::new(SessionStats::new()),
            shutdown: Arc::new(Notify::new()),
            touch_counter: AtomicU32::new(0),
        }
    }

    /// Get the configuration.
    pub fn config(&self) -> &SessionConfig {
        &self.config
    }

    /// Check if session tracking is enabled.
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    /// Get the number of tracked sessions.
    pub fn len(&self) -> usize {
        self.sessions.len()
    }

    /// Check if the store is empty.
    pub fn is_empty(&self) -> bool {
        self.sessions.is_empty()
    }

    // ========================================================================
    // Primary API
    // ========================================================================

    /// Validate an incoming request's session.
    ///
    /// This is the primary entry point - call on every request with a session token.
    ///
    /// # Arguments
    /// * `token_hash` - Hash of the session token (not the raw token)
    /// * `ip` - Client IP address
    /// * `ja4` - Optional JA4 TLS fingerprint
    ///
    /// # Returns
    /// A `SessionDecision` indicating the validation result.
    pub fn validate_request(
        &self,
        token_hash: &str,
        ip: IpAddr,
        ja4: Option<&str>,
    ) -> SessionDecision {
        if !self.config.enabled {
            return SessionDecision::Valid;
        }

        // Check capacity and evict if needed
        self.maybe_evict();

        // Use entry API for atomic check-and-modify to prevent TOCTOU races
        // This ensures the session state is consistent throughout the operation
        match self.sessions.entry(token_hash.to_string()) {
            dashmap::mapref::entry::Entry::Occupied(mut entry) => {
                let session = entry.get_mut();

                // Check expiration - if expired, remove atomically while holding the lock
                if self.is_session_expired(session) {
                    let session_id = session.session_id.clone();
                    let actor_id = session.actor_id.clone();
                    let was_suspicious = session.is_suspicious;

                    // Remove from primary store (still holding entry lock)
                    entry.remove();

                    // Clean up secondary indices
                    self.session_by_id.remove(&session_id);
                    if let Some(aid) = actor_id {
                        if let Some(mut actor_entry) = self.actor_sessions.get_mut(&aid) {
                            actor_entry.retain(|id| id != &session_id);
                        }
                    }

                    // Update stats
                    self.stats.total_sessions.fetch_sub(1, Ordering::Relaxed);
                    self.stats.active_sessions.fetch_sub(1, Ordering::Relaxed);
                    self.stats.expired_sessions.fetch_add(1, Ordering::Relaxed);
                    if was_suspicious {
                        self.stats
                            .suspicious_sessions
                            .fetch_sub(1, Ordering::Relaxed);
                    }

                    return SessionDecision::Expired;
                }

                // Check for hijacking
                if let Some(alert) = self.detect_hijack(session, ip, ja4) {
                    let was_suspicious = session.is_suspicious;
                    session.add_alert(alert.clone());
                    session.touch();

                    // Trim alerts if needed
                    if session.hijack_alerts.len() > self.config.max_alerts_per_session {
                        let excess =
                            session.hijack_alerts.len() - self.config.max_alerts_per_session;
                        session.hijack_alerts.drain(0..excess);
                    }

                    self.stats.hijack_alerts.fetch_add(1, Ordering::Relaxed);

                    // Update suspicious count if first alert
                    if !was_suspicious {
                        self.stats
                            .suspicious_sessions
                            .fetch_add(1, Ordering::Relaxed);
                    }

                    return SessionDecision::Suspicious(alert);
                }

                // Valid session - update activity
                session.touch();

                // Bind fingerprint if first request or not yet bound
                if let Some(ja4_str) = ja4 {
                    session.bind_ja4(ja4_str.to_string());
                }

                if self.config.enable_ip_binding {
                    session.bind_ip(ip);
                }

                SessionDecision::Valid
            }
            dashmap::mapref::entry::Entry::Vacant(entry) => {
                // Session doesn't exist - create atomically
                let session_id = generate_session_id();
                let mut session = SessionState::new(session_id.clone(), token_hash.to_string());
                session.touch();

                // Bind fingerprint and IP
                if let Some(ja4_str) = ja4 {
                    session.bind_ja4(ja4_str.to_string());
                }

                if self.config.enable_ip_binding {
                    session.bind_ip(ip);
                }

                // Insert atomically into primary store
                entry.insert(session);

                // Update secondary index
                self.session_by_id
                    .insert(session_id, token_hash.to_string());

                // Update stats
                self.stats.total_sessions.fetch_add(1, Ordering::Relaxed);
                self.stats.active_sessions.fetch_add(1, Ordering::Relaxed);
                self.stats.total_created.fetch_add(1, Ordering::Relaxed);

                SessionDecision::New
            }
        }
    }

    /// Create a new session.
    ///
    /// # Arguments
    /// * `token_hash` - Hash of the session token
    /// * `ip` - Client IP address
    /// * `ja4` - Optional JA4 TLS fingerprint
    ///
    /// # Returns
    /// The newly created session state.
    pub fn create_session(&self, token_hash: &str, ip: IpAddr, ja4: Option<&str>) -> SessionState {
        if !self.config.enabled {
            return SessionState::new(generate_session_id(), token_hash.to_string());
        }

        // Check capacity and evict if needed
        self.maybe_evict();

        let session_id = generate_session_id();
        let mut session = SessionState::new(session_id.clone(), token_hash.to_string());
        session.touch();

        // Bind fingerprint and IP
        if let Some(ja4_str) = ja4 {
            session.bind_ja4(ja4_str.to_string());
        }

        if self.config.enable_ip_binding {
            session.bind_ip(ip);
        }

        // Insert into maps
        self.session_by_id
            .insert(session_id.clone(), token_hash.to_string());
        self.sessions
            .insert(token_hash.to_string(), session.clone());

        // Update stats
        self.stats.total_sessions.fetch_add(1, Ordering::Relaxed);
        self.stats.active_sessions.fetch_add(1, Ordering::Relaxed);
        self.stats.total_created.fetch_add(1, Ordering::Relaxed);

        session
    }

    /// Get session by token hash.
    pub fn get_session(&self, token_hash: &str) -> Option<SessionState> {
        self.sessions
            .get(token_hash)
            .map(|entry| entry.value().clone())
    }

    /// Get session by session ID.
    pub fn get_session_by_id(&self, session_id: &str) -> Option<SessionState> {
        self.session_by_id.get(session_id).and_then(|token_hash| {
            self.sessions
                .get(token_hash.value())
                .map(|e| e.value().clone())
        })
    }

    /// Touch session to update activity timestamp.
    pub fn touch_session(&self, token_hash: &str) {
        if let Some(mut entry) = self.sessions.get_mut(token_hash) {
            entry.value_mut().touch();
        }
    }

    /// Bind session to an actor.
    ///
    /// Uses atomic operations to prevent TOCTOU race conditions when
    /// updating both the session and actor_sessions mappings.
    ///
    /// # Arguments
    /// * `token_hash` - Hash of the session token
    /// * `actor_id` - Actor ID to bind to
    ///
    /// # Returns
    /// `true` if the binding was successful, `false` if session not found.
    pub fn bind_to_actor(&self, token_hash: &str, actor_id: &str) -> bool {
        // Use entry API for atomic modification
        match self.sessions.entry(token_hash.to_string()) {
            dashmap::mapref::entry::Entry::Occupied(mut entry) => {
                let session = entry.get_mut();

                // Check if already bound to same actor (idempotent)
                if session.actor_id.as_deref() == Some(actor_id) {
                    return true;
                }

                // If bound to different actor, remove from old actor's list first
                if let Some(ref old_actor_id) = session.actor_id {
                    if let Some(mut old_actor_entry) = self.actor_sessions.get_mut(old_actor_id) {
                        old_actor_entry.retain(|id| id != &session.session_id);
                    }
                }

                let session_id = session.session_id.clone();

                // Update session's actor_id atomically while holding the lock
                session.actor_id = Some(actor_id.to_string());

                // Update actor_sessions mapping
                self.actor_sessions
                    .entry(actor_id.to_string())
                    .or_insert_with(Vec::new)
                    .push(session_id);

                true
            }
            dashmap::mapref::entry::Entry::Vacant(_) => false,
        }
    }

    /// Get all sessions for an actor.
    ///
    /// # Arguments
    /// * `actor_id` - Actor ID to look up
    ///
    /// # Returns
    /// Vector of session states associated with the actor.
    pub fn get_actor_sessions(&self, actor_id: &str) -> Vec<SessionState> {
        self.actor_sessions
            .get(actor_id)
            .map(|session_ids| {
                session_ids
                    .iter()
                    .filter_map(|session_id| self.get_session_by_id(session_id))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// List sessions for an actor with pagination.
    ///
    /// Results are sorted by last_activity (most recent first).
    pub fn list_sessions_by_actor(
        &self,
        actor_id: &str,
        limit: usize,
        offset: usize,
    ) -> Vec<SessionState> {
        let mut sessions = self.get_actor_sessions(actor_id);
        sessions.sort_by_key(|s| std::cmp::Reverse(s.last_activity));
        sessions.into_iter().skip(offset).take(limit).collect()
    }

    /// Invalidate a session.
    ///
    /// # Arguments
    /// * `token_hash` - Hash of the session token to invalidate
    ///
    /// # Returns
    /// `true` if the session was invalidated, `false` if not found.
    pub fn invalidate_session(&self, token_hash: &str) -> bool {
        if self.remove_session(token_hash) {
            self.stats.total_invalidated.fetch_add(1, Ordering::Relaxed);
            true
        } else {
            false
        }
    }

    /// Mark session as suspicious with a hijack alert.
    ///
    /// Uses atomic operations to prevent TOCTOU race conditions.
    ///
    /// # Arguments
    /// * `token_hash` - Hash of the session token
    /// * `alert` - Hijack alert to add
    ///
    /// # Returns
    /// `true` if the session was marked suspicious, `false` if not found.
    pub fn mark_suspicious(&self, token_hash: &str, alert: HijackAlert) -> bool {
        // Use entry API for atomic modification
        match self.sessions.entry(token_hash.to_string()) {
            dashmap::mapref::entry::Entry::Occupied(mut entry) => {
                let session = entry.get_mut();
                let was_suspicious = session.is_suspicious;
                session.add_alert(alert);

                // Trim alerts if needed
                if session.hijack_alerts.len() > self.config.max_alerts_per_session {
                    let excess = session.hijack_alerts.len() - self.config.max_alerts_per_session;
                    session.hijack_alerts.drain(0..excess);
                }

                self.stats.hijack_alerts.fetch_add(1, Ordering::Relaxed);

                // Update suspicious count if first alert
                if !was_suspicious {
                    self.stats
                        .suspicious_sessions
                        .fetch_add(1, Ordering::Relaxed);
                }

                true
            }
            dashmap::mapref::entry::Entry::Vacant(_) => false,
        }
    }

    /// List sessions with pagination.
    ///
    /// # Arguments
    /// * `limit` - Maximum number of sessions to return
    /// * `offset` - Number of sessions to skip
    ///
    /// # Returns
    /// Vector of session states sorted by last_activity (most recent first).
    pub fn list_sessions(&self, limit: usize, offset: usize) -> Vec<SessionState> {
        let mut sessions: Vec<SessionState> = self
            .sessions
            .iter()
            .map(|entry| entry.value().clone())
            .collect();

        // Sort by last_activity (most recent first)
        sessions.sort_by_key(|s| std::cmp::Reverse(s.last_activity));

        // Apply pagination
        sessions.into_iter().skip(offset).take(limit).collect()
    }

    /// List suspicious sessions.
    ///
    /// # Returns
    /// Vector of session states that have been flagged as suspicious.
    pub fn list_suspicious_sessions(&self) -> Vec<SessionState> {
        self.sessions
            .iter()
            .filter(|entry| entry.value().is_suspicious)
            .map(|entry| entry.value().clone())
            .collect()
    }

    /// List suspicious sessions with pagination.
    ///
    /// Results are sorted by last_activity (most recent first).
    pub fn list_suspicious_sessions_paginated(
        &self,
        limit: usize,
        offset: usize,
    ) -> Vec<SessionState> {
        let mut sessions = self.list_suspicious_sessions();
        sessions.sort_by_key(|s| std::cmp::Reverse(s.last_activity));
        sessions.into_iter().skip(offset).take(limit).collect()
    }

    /// Start background cleanup tasks.
    ///
    /// Spawns a background task that periodically:
    /// 1. Removes expired sessions (TTL and idle timeout)
    /// 2. Evicts oldest sessions if over capacity
    pub fn start_background_tasks(self: Arc<Self>) {
        let manager = self;
        let cleanup_interval = Duration::from_secs(manager.config.cleanup_interval_secs);

        tokio::spawn(async move {
            let mut interval = tokio::time::interval(cleanup_interval);

            loop {
                tokio::select! {
                    _ = interval.tick() => {
                        // Check shutdown
                        if Arc::strong_count(&manager.shutdown) == 1 {
                            // Only this task holds a reference, shutting down
                            break;
                        }

                        // Cleanup expired sessions
                        manager.cleanup_expired_sessions();

                        // Evict if over capacity
                        manager.evict_if_needed();
                    }
                    _ = manager.shutdown.notified() => {
                        log::info!("Session manager background tasks shutting down");
                        break;
                    }
                }
            }
        });
    }

    /// Signal shutdown for background tasks.
    pub fn shutdown(&self) {
        self.shutdown.notify_one();
    }

    /// Get statistics.
    pub fn stats(&self) -> &SessionStats {
        &self.stats
    }

    /// Clear all sessions (primarily for testing).
    pub fn clear(&self) {
        self.sessions.clear();
        self.session_by_id.clear();
        self.actor_sessions.clear();
        self.stats.total_sessions.store(0, Ordering::Relaxed);
        self.stats.active_sessions.store(0, Ordering::Relaxed);
        self.stats.suspicious_sessions.store(0, Ordering::Relaxed);
    }

    // ========================================================================
    // Private Methods
    // ========================================================================

    /// Detect potential session hijacking.
    ///
    /// # Arguments
    /// * `session` - Current session state
    /// * `ip` - Client IP address
    /// * `ja4` - Optional JA4 TLS fingerprint
    ///
    /// # Returns
    /// A hijack alert if hijacking is detected, None otherwise.
    fn detect_hijack(
        &self,
        session: &SessionState,
        ip: IpAddr,
        ja4: Option<&str>,
    ) -> Option<HijackAlert> {
        let now = now_ms();

        // Check JA4 fingerprint binding
        if self.config.enable_ja4_binding {
            if let (Some(bound_ja4), Some(current_ja4)) = (&session.bound_ja4, ja4) {
                if bound_ja4 != current_ja4 {
                    return Some(HijackAlert {
                        session_id: session.session_id.clone(),
                        alert_type: HijackType::Ja4Mismatch,
                        original_value: bound_ja4.clone(),
                        new_value: current_ja4.to_string(),
                        timestamp: now,
                        confidence: 0.9, // High confidence - fingerprint changed
                    });
                }
            }
        }

        // Check IP binding (if enabled in strict mode)
        if self.config.enable_ip_binding {
            if let Some(bound_ip) = session.bound_ip {
                if bound_ip != ip {
                    // Allow IP changes within the grace window (for mobile users)
                    // Only alert if the change happens OUTSIDE the allowed window
                    let time_since_last = now.saturating_sub(session.last_activity);
                    let window_ms = self.config.ip_change_window_secs * 1000;

                    if time_since_last >= window_ms {
                        return Some(HijackAlert {
                            session_id: session.session_id.clone(),
                            alert_type: HijackType::IpChange,
                            original_value: bound_ip.to_string(),
                            new_value: ip.to_string(),
                            timestamp: now,
                            confidence: 0.7, // Lower confidence - could be legitimate
                        });
                    }
                }
            }
        }

        None
    }

    /// Check if a session has expired.
    ///
    /// # Arguments
    /// * `session` - Session state to check
    ///
    /// # Returns
    /// `true` if the session has expired (TTL or idle timeout), `false` otherwise.
    fn is_session_expired(&self, session: &SessionState) -> bool {
        let now = now_ms();

        // Check absolute TTL
        let ttl_ms = self.config.session_ttl_secs * 1000;
        if now.saturating_sub(session.creation_time) > ttl_ms {
            return true;
        }

        // Check idle timeout
        let idle_ms = self.config.idle_timeout_secs * 1000;
        if now.saturating_sub(session.last_activity) > idle_ms {
            return true;
        }

        false
    }

    /// Cleanup expired sessions.
    fn cleanup_expired_sessions(&self) {
        let mut to_remove = Vec::new();

        for entry in self.sessions.iter() {
            if self.is_session_expired(entry.value()) {
                to_remove.push(entry.key().clone());
            }
        }

        for token_hash in to_remove {
            self.remove_session(&token_hash);
            self.stats.expired_sessions.fetch_add(1, Ordering::Relaxed);
        }
    }

    /// Evict sessions if over capacity.
    fn evict_if_needed(&self) {
        let current_len = self.sessions.len();
        if current_len <= self.config.max_sessions {
            return;
        }

        // Evict oldest 1% of sessions
        let evict_count = (self.config.max_sessions / 100).max(1);
        self.evict_oldest(evict_count);
    }

    /// Maybe evict oldest sessions if at capacity.
    ///
    /// Uses lazy eviction: only check every 100th operation.
    fn maybe_evict(&self) {
        let count = self.touch_counter.fetch_add(1, Ordering::Relaxed);
        if !count.is_multiple_of(100) {
            return;
        }

        if self.sessions.len() < self.config.max_sessions {
            return;
        }

        // Evict oldest 1% of sessions
        let evict_count = (self.config.max_sessions / 100).max(1);
        self.evict_oldest(evict_count);
    }

    /// Evict the N oldest sessions by last_activity timestamp.
    ///
    /// Uses sampling to avoid O(n) collection of all sessions.
    fn evict_oldest(&self, count: usize) {
        let sample_size = (count * 10).min(1000).min(self.sessions.len());

        if sample_size == 0 {
            return;
        }

        // Sample sessions
        let mut candidates: Vec<(String, u64)> = Vec::with_capacity(sample_size);
        for entry in self.sessions.iter().take(sample_size) {
            candidates.push((entry.key().clone(), entry.value().last_activity));
        }

        // Sort by last_activity (oldest first)
        candidates.sort_unstable_by_key(|(_, ts)| *ts);

        // Evict oldest N from sample
        for (token_hash, _) in candidates.into_iter().take(count) {
            self.remove_session(&token_hash);
            self.stats.evictions.fetch_add(1, Ordering::Relaxed);
        }
    }

    /// Remove a session and clean up all mappings.
    fn remove_session(&self, token_hash: &str) -> bool {
        if let Some((_, session)) = self.sessions.remove(token_hash) {
            // Remove session_id mapping
            self.session_by_id.remove(&session.session_id);

            // Remove from actor's sessions list
            if let Some(actor_id) = &session.actor_id {
                if let Some(mut entry) = self.actor_sessions.get_mut(actor_id) {
                    entry.retain(|id| id != &session.session_id);
                    if entry.is_empty() {
                        drop(entry);
                        self.actor_sessions.remove(actor_id);
                    }
                }
            }

            // Update stats
            self.stats.total_sessions.fetch_sub(1, Ordering::Relaxed);
            self.stats.active_sessions.fetch_sub(1, Ordering::Relaxed);

            if session.is_suspicious {
                self.stats
                    .suspicious_sessions
                    .fetch_sub(1, Ordering::Relaxed);
            }

            return true;
        }

        false
    }
}

impl Default for SessionManager {
    fn default() -> Self {
        Self::new(SessionConfig::default())
    }
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Generate a unique session ID using cryptographically secure random bytes.
fn generate_session_id() -> String {
    // Use getrandom for cryptographically secure random bytes
    let mut bytes = [0u8; 16];
    if let Err(err) = getrandom::getrandom(&mut bytes) {
        log::error!("Failed to get random bytes for session id: {}", err);
        for byte in bytes.iter_mut() {
            *byte = fastrand::u8(..);
        }
    }

    // Format as UUID v4 with proper version and variant bits
    bytes[6] = (bytes[6] & 0x0F) | 0x40; // Version 4
    bytes[8] = (bytes[8] & 0x3F) | 0x80; // Variant 1

    format!(
        "sess-{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
        u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]),
        u16::from_be_bytes([bytes[4], bytes[5]]),
        u16::from_be_bytes([bytes[6], bytes[7]]),
        u16::from_be_bytes([bytes[8], bytes[9]]),
        u64::from_be_bytes([
            0, 0, bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]
        ])
    )
}

/// Get current time in milliseconds since Unix epoch.
#[inline]
fn now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

// ============================================================================
// Tests
// ============================================================================

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

    // ========================================================================
    // Helper Functions
    // ========================================================================

    fn create_test_manager() -> SessionManager {
        SessionManager::new(SessionConfig {
            max_sessions: 1000,
            session_ttl_secs: 3600,
            idle_timeout_secs: 900,
            ..Default::default()
        })
    }

    fn create_test_ip(last_octet: u8) -> IpAddr {
        format!("192.168.1.{}", last_octet).parse().unwrap()
    }

    // ========================================================================
    // Session Creation and Retrieval Tests
    // ========================================================================

    #[test]
    fn test_session_creation() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        let session = manager.create_session("token_hash_1", ip, None);

        assert!(!session.session_id.is_empty());
        assert!(session.session_id.starts_with("sess-"));
        assert_eq!(session.token_hash, "token_hash_1");
        assert_eq!(manager.len(), 1);
    }

    #[test]
    fn test_session_retrieval_by_token_hash() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        manager.create_session("token_hash_1", ip, None);

        let retrieved = manager.get_session("token_hash_1").unwrap();
        assert_eq!(retrieved.token_hash, "token_hash_1");
    }

    #[test]
    fn test_session_retrieval_by_id() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        let session = manager.create_session("token_hash_1", ip, None);
        let retrieved = manager.get_session_by_id(&session.session_id).unwrap();

        assert_eq!(retrieved.token_hash, "token_hash_1");
    }

    #[test]
    fn test_session_nonexistent() {
        let manager = create_test_manager();

        assert!(manager.get_session("nonexistent").is_none());
        assert!(manager.get_session_by_id("nonexistent").is_none());
    }

    // ========================================================================
    // Session Validation Tests
    // ========================================================================

    #[test]
    fn test_validate_new_session() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        let decision = manager.validate_request("token_hash_1", ip, None);

        assert_eq!(decision, SessionDecision::New);
        assert_eq!(manager.len(), 1);
    }

    #[test]
    fn test_validate_existing_session() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        // Create session first
        manager.create_session("token_hash_1", ip, Some("ja4_fingerprint"));

        // Validate again with same fingerprint
        let decision = manager.validate_request("token_hash_1", ip, Some("ja4_fingerprint"));

        assert_eq!(decision, SessionDecision::Valid);
        assert_eq!(manager.len(), 1);
    }

    #[test]
    fn test_validate_increments_request_count() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        manager.validate_request("token_hash_1", ip, None);
        manager.validate_request("token_hash_1", ip, None);
        manager.validate_request("token_hash_1", ip, None);

        let session = manager.get_session("token_hash_1").unwrap();
        assert_eq!(session.request_count, 3);
    }

    // ========================================================================
    // JA4 Fingerprint Binding Tests
    // ========================================================================

    #[test]
    fn test_ja4_binding() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        manager.create_session("token_hash_1", ip, Some("ja4_fingerprint_1"));

        let session = manager.get_session("token_hash_1").unwrap();
        assert_eq!(session.bound_ja4, Some("ja4_fingerprint_1".to_string()));
    }

    #[test]
    fn test_ja4_mismatch_detection() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        // Create session with fingerprint
        manager.create_session("token_hash_1", ip, Some("ja4_fingerprint_1"));

        // Validate with different fingerprint
        let decision = manager.validate_request("token_hash_1", ip, Some("ja4_fingerprint_2"));

        match decision {
            SessionDecision::Suspicious(alert) => {
                assert_eq!(alert.alert_type, HijackType::Ja4Mismatch);
                assert_eq!(alert.original_value, "ja4_fingerprint_1");
                assert_eq!(alert.new_value, "ja4_fingerprint_2");
                assert!(alert.confidence >= 0.9);
            }
            _ => panic!("Expected Suspicious decision, got {:?}", decision),
        }
    }

    #[test]
    fn test_ja4_binding_first_value_only() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        // Create session without fingerprint
        manager.create_session("token_hash_1", ip, None);

        // First request with fingerprint binds it
        manager.validate_request("token_hash_1", ip, Some("ja4_fingerprint_1"));

        let session = manager.get_session("token_hash_1").unwrap();
        assert_eq!(session.bound_ja4, Some("ja4_fingerprint_1".to_string()));
    }

    #[test]
    fn test_ja4_binding_disabled() {
        let config = SessionConfig {
            enable_ja4_binding: false,
            ..Default::default()
        };
        let manager = SessionManager::new(config);
        let ip = create_test_ip(1);

        // Create session with fingerprint
        manager.create_session("token_hash_1", ip, Some("ja4_fingerprint_1"));

        // Different fingerprint should NOT trigger alert when binding is disabled
        let decision = manager.validate_request("token_hash_1", ip, Some("ja4_fingerprint_2"));

        assert_eq!(decision, SessionDecision::Valid);
    }

    // ========================================================================
    // IP Binding Tests
    // ========================================================================

    #[test]
    fn test_ip_binding_strict_mode_within_window() {
        let config = SessionConfig {
            enable_ip_binding: true,
            ip_change_window_secs: 60,
            ..Default::default()
        };
        let manager = SessionManager::new(config);
        let ip1 = create_test_ip(1);
        let ip2 = create_test_ip(2);

        // Create session with IP1
        manager.create_session("token_hash_1", ip1, None);

        // Validate with different IP immediately (within window) - should be allowed
        let decision = manager.validate_request("token_hash_1", ip2, None);

        // IP changes within the grace window should be allowed (no alert)
        assert_eq!(decision, SessionDecision::Valid);
    }

    #[test]
    fn test_ip_binding_strict_mode_outside_window() {
        let config = SessionConfig {
            enable_ip_binding: true,
            ip_change_window_secs: 0, // No grace window - immediate alert on IP change
            ..Default::default()
        };
        let manager = SessionManager::new(config);
        let ip1 = create_test_ip(1);
        let ip2 = create_test_ip(2);

        // Create session with IP1
        manager.create_session("token_hash_1", ip1, None);

        // Small sleep to ensure time passes beyond the 0-second window
        std::thread::sleep(std::time::Duration::from_millis(10));

        // Validate with different IP - should trigger alert (outside window)
        let decision = manager.validate_request("token_hash_1", ip2, None);

        match decision {
            SessionDecision::Suspicious(alert) => {
                assert_eq!(alert.alert_type, HijackType::IpChange);
                assert!(alert.confidence >= 0.5 && alert.confidence < 0.9);
            }
            _ => panic!("Expected Suspicious decision, got {:?}", decision),
        }
    }

    #[test]
    fn test_ip_binding_disabled_by_default() {
        let manager = create_test_manager();
        let ip1 = create_test_ip(1);
        let ip2 = create_test_ip(2);

        // Create session with IP1
        manager.create_session("token_hash_1", ip1, None);

        // Different IP should NOT trigger alert when IP binding is disabled
        let decision = manager.validate_request("token_hash_1", ip2, None);

        assert_eq!(decision, SessionDecision::Valid);
    }

    // ========================================================================
    // Session Expiration Tests
    // ========================================================================

    #[test]
    fn test_session_ttl_expiration() {
        let config = SessionConfig {
            session_ttl_secs: 0, // Immediate expiration
            idle_timeout_secs: 3600,
            ..Default::default()
        };
        let manager = SessionManager::new(config);
        let ip = create_test_ip(1);

        manager.create_session("token_hash_1", ip, None);

        // Small sleep to ensure time passes
        std::thread::sleep(std::time::Duration::from_millis(10));

        let decision = manager.validate_request("token_hash_1", ip, None);
        assert_eq!(decision, SessionDecision::Expired);
    }

    #[test]
    fn test_session_idle_expiration() {
        let config = SessionConfig {
            session_ttl_secs: 3600,
            idle_timeout_secs: 0, // Immediate idle timeout
            ..Default::default()
        };
        let manager = SessionManager::new(config);
        let ip = create_test_ip(1);

        manager.create_session("token_hash_1", ip, None);

        // Small sleep to ensure time passes
        std::thread::sleep(std::time::Duration::from_millis(10));

        let decision = manager.validate_request("token_hash_1", ip, None);
        assert_eq!(decision, SessionDecision::Expired);
    }

    // ========================================================================
    // Actor Binding Tests
    // ========================================================================

    #[test]
    fn test_bind_to_actor() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        manager.create_session("token_hash_1", ip, None);
        let result = manager.bind_to_actor("token_hash_1", "actor_123");

        assert!(result);
        let session = manager.get_session("token_hash_1").unwrap();
        assert_eq!(session.actor_id, Some("actor_123".to_string()));
    }

    #[test]
    fn test_bind_to_actor_nonexistent() {
        let manager = create_test_manager();

        let result = manager.bind_to_actor("nonexistent", "actor_123");
        assert!(!result);
    }

    #[test]
    fn test_bind_to_actor_idempotent() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        manager.create_session("token_hash_1", ip, None);

        // Bind twice to same actor should succeed
        assert!(manager.bind_to_actor("token_hash_1", "actor_123"));
        assert!(manager.bind_to_actor("token_hash_1", "actor_123"));

        // Should still only have one entry in actor_sessions
        let sessions = manager.get_actor_sessions("actor_123");
        assert_eq!(sessions.len(), 1);
    }

    #[test]
    fn test_bind_to_actor_rebind() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        manager.create_session("token_hash_1", ip, None);

        // Bind to first actor
        assert!(manager.bind_to_actor("token_hash_1", "actor_123"));
        assert_eq!(manager.get_actor_sessions("actor_123").len(), 1);

        // Rebind to second actor
        assert!(manager.bind_to_actor("token_hash_1", "actor_456"));

        // Old actor should have no sessions
        assert_eq!(manager.get_actor_sessions("actor_123").len(), 0);
        // New actor should have the session
        assert_eq!(manager.get_actor_sessions("actor_456").len(), 1);

        let session = manager.get_session("token_hash_1").unwrap();
        assert_eq!(session.actor_id, Some("actor_456".to_string()));
    }

    #[test]
    fn test_remove_session_cleans_actor_sessions() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        manager.create_session("token_hash_1", ip, None);
        assert!(manager.bind_to_actor("token_hash_1", "actor_cleanup"));
        assert!(manager.actor_sessions.contains_key("actor_cleanup"));

        assert!(manager.remove_session("token_hash_1"));
        assert!(!manager.actor_sessions.contains_key("actor_cleanup"));
    }

    #[test]
    fn test_get_actor_sessions() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        // Create multiple sessions for same actor
        manager.create_session("token_1", ip, None);
        manager.create_session("token_2", ip, None);
        manager.create_session("token_3", ip, None);

        assert!(manager.bind_to_actor("token_1", "actor_123"));
        assert!(manager.bind_to_actor("token_2", "actor_123"));
        assert!(manager.bind_to_actor("token_3", "actor_456"));

        let actor_sessions = manager.get_actor_sessions("actor_123");
        assert_eq!(actor_sessions.len(), 2);
    }

    // ========================================================================
    // LRU Eviction Tests
    // ========================================================================

    #[test]
    fn test_lru_eviction() {
        let config = SessionConfig {
            max_sessions: 100,
            ..Default::default()
        };
        let manager = SessionManager::new(config);

        // Add 150 sessions (over capacity)
        for i in 0..150 {
            let ip = create_test_ip((i % 256) as u8);
            manager.create_session(&format!("token_{}", i), ip, None);
        }

        // Lazy eviction doesn't aggressively enforce the limit
        assert!(manager.len() <= 150);

        // Force more evictions
        for i in 150..300 {
            let ip = create_test_ip((i % 256) as u8);
            manager.create_session(&format!("token_{}", i), ip, None);
        }

        // Verify evictions occurred
        let evictions = manager.stats().evictions.load(Ordering::Relaxed);
        assert!(evictions > 0);
    }

    // ========================================================================
    // Session Invalidation Tests
    // ========================================================================

    #[test]
    fn test_invalidate_session() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        manager.create_session("token_hash_1", ip, None);
        assert_eq!(manager.len(), 1);

        let result = manager.invalidate_session("token_hash_1");
        assert!(result);
        assert_eq!(manager.len(), 0);
    }

    #[test]
    fn test_invalidate_nonexistent_session() {
        let manager = create_test_manager();

        let result = manager.invalidate_session("nonexistent");
        assert!(!result);
    }

    // ========================================================================
    // Suspicious Session Tests
    // ========================================================================

    #[test]
    fn test_mark_suspicious() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        manager.create_session("token_hash_1", ip, None);

        let alert = HijackAlert {
            session_id: "test".to_string(),
            alert_type: HijackType::Ja4Mismatch,
            original_value: "old".to_string(),
            new_value: "new".to_string(),
            timestamp: now_ms(),
            confidence: 0.9,
        };

        let result = manager.mark_suspicious("token_hash_1", alert);
        assert!(result);

        let session = manager.get_session("token_hash_1").unwrap();
        assert!(session.is_suspicious);
        assert_eq!(session.hijack_alerts.len(), 1);
    }

    #[test]
    fn test_mark_suspicious_nonexistent() {
        let manager = create_test_manager();

        let alert = HijackAlert {
            session_id: "test".to_string(),
            alert_type: HijackType::Ja4Mismatch,
            original_value: "old".to_string(),
            new_value: "new".to_string(),
            timestamp: now_ms(),
            confidence: 0.9,
        };

        let result = manager.mark_suspicious("nonexistent", alert);
        assert!(!result);
    }

    #[test]
    fn test_list_suspicious_sessions() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        // Create sessions and mark some as suspicious
        for i in 0..10 {
            manager.create_session(&format!("token_{}", i), ip, None);
        }

        let alert = HijackAlert {
            session_id: "test".to_string(),
            alert_type: HijackType::Ja4Mismatch,
            original_value: "old".to_string(),
            new_value: "new".to_string(),
            timestamp: now_ms(),
            confidence: 0.9,
        };

        assert!(manager.mark_suspicious("token_0", alert.clone()));
        assert!(manager.mark_suspicious("token_2", alert.clone()));
        assert!(manager.mark_suspicious("token_4", alert));

        let suspicious = manager.list_suspicious_sessions();
        assert_eq!(suspicious.len(), 3);
    }

    // ========================================================================
    // List Tests
    // ========================================================================

    #[test]
    fn test_list_sessions() {
        let manager = create_test_manager();

        for i in 0..10 {
            let ip = create_test_ip(i);
            manager.create_session(&format!("token_{}", i), ip, None);
            std::thread::sleep(std::time::Duration::from_millis(1));
        }

        // Test pagination
        let first_page = manager.list_sessions(5, 0);
        assert_eq!(first_page.len(), 5);

        let second_page = manager.list_sessions(5, 5);
        assert_eq!(second_page.len(), 5);

        // Should be sorted by last_activity (most recent first)
        for window in first_page.windows(2) {
            assert!(window[0].last_activity >= window[1].last_activity);
        }
    }

    // ========================================================================
    // Concurrent Access Tests
    // ========================================================================

    #[test]
    fn test_concurrent_access() {
        let manager = Arc::new(create_test_manager());
        let mut handles = vec![];

        // Spawn 10 threads, each creating and validating sessions
        for thread_id in 0..10 {
            let manager = Arc::clone(&manager);
            handles.push(thread::spawn(move || {
                for i in 0..100 {
                    let ip: IpAddr = format!("10.{}.0.{}", thread_id, i % 256).parse().unwrap();
                    let token = format!("token_t{}_{}", thread_id, i);
                    let ja4 = format!("ja4_t{}_{}", thread_id, i % 5);

                    manager.validate_request(&token, ip, Some(&ja4));
                }
            }));
        }

        for handle in handles {
            handle.join().unwrap();
        }

        // Verify no panics and reasonable state
        assert!(manager.len() > 0);
        assert!(manager.stats().total_created.load(Ordering::Relaxed) > 0);
    }

    #[test]
    fn test_stress_concurrent_sessions() {
        let manager = Arc::new(SessionManager::new(SessionConfig {
            max_sessions: 10_000,
            session_ttl_secs: 86_400,
            idle_timeout_secs: 86_400,
            ..Default::default()
        }));
        let mut handles = vec![];

        for thread_id in 0..16 {
            let manager = Arc::clone(&manager);
            handles.push(thread::spawn(move || {
                let actor_id = format!("actor_{}", thread_id);
                for i in 0..300 {
                    let ip: IpAddr = format!("10.{}.{}.{}", thread_id, i / 256, i % 256)
                        .parse()
                        .unwrap();
                    let token = format!("token_t{}_{}", thread_id, i);
                    let ja4 = format!("ja4_t{}_{}", thread_id, i % 10);

                    manager.validate_request(&token, ip, Some(&ja4));

                    if i % 3 == 0 {
                        let _ = manager.bind_to_actor(&token, &actor_id);
                    }
                    if i % 2 == 0 {
                        manager.touch_session(&token);
                    }
                }
            }));
        }

        for handle in handles {
            handle.join().unwrap();
        }

        let stats = manager.stats();
        assert!(manager.len() > 0);
        assert!(stats.total_created.load(Ordering::Relaxed) > 0);
        assert!(!manager.get_actor_sessions("actor_0").is_empty());
    }

    // ========================================================================
    // Statistics Tests
    // ========================================================================

    #[test]
    fn test_stats() {
        let manager = create_test_manager();

        // Initial stats
        let stats = manager.stats().snapshot();
        assert_eq!(stats.total_sessions, 0);
        assert_eq!(stats.suspicious_sessions, 0);

        // Create sessions
        for i in 0..5 {
            let ip = create_test_ip(i);
            manager.create_session(&format!("token_{}", i), ip, Some(&format!("ja4_{}", i)));
        }

        let stats = manager.stats().snapshot();
        assert_eq!(stats.total_sessions, 5);
        assert_eq!(stats.active_sessions, 5);
        assert_eq!(stats.total_created, 5);
    }

    // ========================================================================
    // Clear Tests
    // ========================================================================

    #[test]
    fn test_clear() {
        let manager = create_test_manager();

        for i in 0..10 {
            let ip = create_test_ip(i);
            manager.create_session(&format!("token_{}", i), ip, None);
        }

        assert_eq!(manager.len(), 10);

        manager.clear();

        assert_eq!(manager.len(), 0);
        assert!(manager.session_by_id.is_empty());
        assert!(manager.actor_sessions.is_empty());
    }

    // ========================================================================
    // Default Implementation Tests
    // ========================================================================

    #[test]
    fn test_default() {
        let manager = SessionManager::default();

        assert!(manager.is_enabled());
        assert!(manager.is_empty());
        assert_eq!(manager.config().max_sessions, 50_000);
    }

    // ========================================================================
    // Session ID Generation Tests
    // ========================================================================

    #[test]
    fn test_session_id_uniqueness() {
        let mut ids = std::collections::HashSet::new();
        for _ in 0..1000 {
            let id = generate_session_id();
            assert!(!ids.contains(&id), "Duplicate ID generated: {}", id);
            ids.insert(id);
        }
    }

    #[test]
    fn test_session_id_format() {
        let id = generate_session_id();

        // Should be sess-xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx format
        assert!(id.starts_with("sess-"));
        assert_eq!(id.len(), 41); // "sess-" (5) + UUID (36)
    }

    // ========================================================================
    // Edge Case Tests
    // ========================================================================

    #[test]
    fn test_empty_ja4_fingerprint() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        manager.create_session("token_hash_1", ip, Some(""));

        let session = manager.get_session("token_hash_1").unwrap();
        assert!(session.bound_ja4.is_none());
    }

    #[test]
    fn test_ipv6_addresses() {
        let manager = create_test_manager();

        let ipv6: IpAddr = "2001:db8::1".parse().unwrap();

        let session = manager.create_session("token_hash_1", ipv6, None);
        assert_eq!(session.request_count, 1);

        let decision = manager.validate_request("token_hash_1", ipv6, None);
        assert_eq!(decision, SessionDecision::Valid);
    }

    #[test]
    fn test_disabled_manager() {
        let config = SessionConfig {
            enabled: false,
            ..Default::default()
        };
        let manager = SessionManager::new(config);

        assert!(!manager.is_enabled());

        let ip = create_test_ip(1);
        let decision = manager.validate_request("token_hash_1", ip, None);

        // Should return Valid without creating session when disabled
        assert_eq!(decision, SessionDecision::Valid);
        assert!(manager.is_empty());
    }

    // ========================================================================
    // Hijack Alert Trimming Tests
    // ========================================================================

    #[test]
    fn test_alert_trimming() {
        let config = SessionConfig {
            max_alerts_per_session: 3,
            ..Default::default()
        };
        let manager = SessionManager::new(config);
        let ip = create_test_ip(1);

        manager.create_session("token_hash_1", ip, Some("ja4_original"));

        // Add more alerts than max
        for i in 0..10 {
            let alert = HijackAlert {
                session_id: "test".to_string(),
                alert_type: HijackType::Ja4Mismatch,
                original_value: "old".to_string(),
                new_value: format!("new_{}", i),
                timestamp: now_ms(),
                confidence: 0.9,
            };
            assert!(manager.mark_suspicious("token_hash_1", alert));
        }

        let session = manager.get_session("token_hash_1").unwrap();
        assert_eq!(session.hijack_alerts.len(), 3);

        // Should keep most recent
        assert_eq!(session.hijack_alerts[2].new_value, "new_9");
    }

    // ========================================================================
    // Session Touch Tests
    // ========================================================================

    #[test]
    fn test_touch_session() {
        let manager = create_test_manager();
        let ip = create_test_ip(1);

        manager.create_session("token_hash_1", ip, None);

        let before = manager.get_session("token_hash_1").unwrap().last_activity;

        std::thread::sleep(std::time::Duration::from_millis(10));

        manager.touch_session("token_hash_1");

        let after = manager.get_session("token_hash_1").unwrap().last_activity;
        assert!(after > before);
    }
}