synapse-waf 0.9.1

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
//! Synapse-Pingora: High-performance WAF proxy using Cloudflare Pingora.
//!
//! This library provides multi-site reverse proxy capabilities with integrated
//! WAF detection using the Synapse engine.
//!
//! # Phase 1 Modules (Core Features)
//!
//! - [`vhost`] - Virtual host matching for multi-site routing
//! - [`config`] - Configuration loading and validation
//! - [`tls`] - TLS certificate management with SNI support
//! - [`health`] - Health check endpoint for monitoring
//! - [`site_waf`] - Per-site WAF configuration management
//!
//! # Phase 2 Modules (Management Features)
//!
//! - [`metrics`] - Prometheus metrics endpoint
//! - [`reload`] - Configuration hot-reload via SIGHUP
//! - [`access`] - CIDR-based allow/deny access lists
//! - [`ratelimit`] - Per-site rate limiting with token bucket
//! - [`api`] - Management HTTP API
//!
//! # Phase 3 Modules (Feature Migration from risk-server)
//!
//! - [`fingerprint`] - JA4/JA4H TLS and HTTP fingerprinting
//! - [`entity`] - Per-IP entity tracking with risk scoring and decay
//! - [`tarpit`] - Progressive response delays for slow-drip defense
//! - [`dlp`] - Data Loss Prevention with 23 sensitive data patterns

// Phase 1: Core Features
pub mod config;
pub mod config_manager;
pub mod health;
pub mod site_waf;
pub mod tls;
pub mod utils;
pub mod vhost;

// Phase 2: Management Features
pub mod access;
pub mod admin_server;
pub mod api;
pub mod intelligence;
pub mod metrics;
pub mod ratelimit;
pub mod reload;

// Phase 3: Feature Migration from risk-server
pub mod dlp;
pub mod entity;
pub mod fingerprint;
pub mod tarpit;

// Phase 6: Security Hardening
pub mod sni_validation;
pub mod validation;

// Phase 7: Persistence
pub mod persistence;

// Phase 3: Telemetry (Alerting)
pub mod signals;
pub mod telemetry;

// Phase 3: Honeypot Trap Detection
pub mod trap;

// Phase 4: Campaign Correlation
pub mod correlation;

// Phase 5: Actor State Management
pub mod actor;

// Phase 5: Session State Management
pub mod session;

// Phase 6: Interrogator System (Progressive Challenge Escalation)
pub mod interrogator;

// Phase 7: Shadow Mirroring (Honeypot Integration)
pub mod shadow;

// Phase 8: API Profiler (Behavioral Learning)
pub mod profiler;

// Phase 9: Risk-Server Port (Payload, Crawler, Trends, Horizon)
pub mod crawler;
pub mod horizon;
pub mod payload;
pub mod trends;
pub mod tunnel;

// Phase 10: Libsynapse Consolidation (Geo, WAF Engine, Credential Stuffing)
pub mod detection;
pub mod geo;
pub mod waf;

// Dashboard support
pub mod block_log;
pub mod tui;

// Header Manipulation
pub mod headers;

// Body Inspection
pub mod body;

// Block Page Rendering
pub mod block_page;

// Re-export commonly used types from Phase 1
pub use config::{ConfigFile, ConfigLoader, GlobalConfig};
pub use health::{HealthChecker, HealthResponse, HealthStatus};
pub use site_waf::{SiteWafConfig, SiteWafManager, WafAction};
pub use tls::{TlsManager, TlsVersion};
pub use vhost::{SiteConfig, VhostMatcher};

// Re-export commonly used types from Phase 2
pub use access::{AccessDecision, AccessList, AccessListManager};
pub use api::{ApiHandler, ApiResponse, EvaluateResult};
pub use metrics::{BandwidthDataPoint, BandwidthStats, MetricsRegistry, ProfilingMetrics};
pub use ratelimit::{RateLimitConfig, RateLimitDecision, RateLimitManager};
pub use reload::{ConfigReloader, ReloadResult};

// Re-export commonly used types from Phase 3
pub use dlp::{
    validate_credit_card, validate_iban, validate_phone, validate_ssn, DlpConfig, DlpMatch,
    DlpScanner, DlpStats, PatternSeverity, ScanResult, SensitiveDataType,
};
pub use entity::{
    BlockDecision, EntityConfig, EntityManager, EntityMetrics, EntitySnapshot, EntityState,
    RiskApplication,
};
pub use fingerprint::{
    analyze_ja4, analyze_ja4h, extract_client_fingerprint, generate_ja4h, parse_ja4_from_header,
    ClientFingerprint, HttpHeaders, Ja4Analysis, Ja4Fingerprint, Ja4Protocol, Ja4SniType,
    Ja4hAnalysis, Ja4hFingerprint,
};
pub use tarpit::{TarpitConfig, TarpitDecision, TarpitManager, TarpitState, TarpitStats};

// Re-export validation utilities
pub use validation::{
    validate_certificate_file, validate_domain_name, validate_private_key_file,
    validate_tls_config, ValidationError, ValidationResult,
};

// Re-export SNI validation types (domain fronting prevention)
pub use sni_validation::{
    SniValidationConfig, SniValidationMode, SniValidationResult, SniValidator,
};

// Re-export honeypot trap types
pub use trap::{TrapConfig, TrapMatcher};

// Re-export dashboard support types
pub use block_log::{BlockEvent, BlockLog};

// Re-export actor management types
pub use actor::{ActorConfig, ActorManager, ActorState, ActorStats, RuleMatch};

// Re-export session management types
pub use session::{
    HijackAlert, HijackType, SessionConfig, SessionDecision, SessionManager, SessionState,
    SessionStats,
};

// Re-export interrogator types
pub use interrogator::{
    ActorChallengeState, ChallengeLevel, ChallengeResponse, CookieChallenge, CookieConfig,
    CookieManager, CookieStats, Interrogator, JsChallenge, JsChallengeConfig, JsChallengeManager,
    JsChallengeStats, ProgressionConfig, ProgressionManager, ProgressionStats,
    ValidationResult as ChallengeValidationResult,
};

// Re-export shadow mirroring types
pub use shadow::{
    MirrorPayload, RateLimiter as ShadowRateLimiter, RateLimiterStats as ShadowRateLimiterStats,
    ShadowClientStats, ShadowMirrorClient, ShadowMirrorConfig, ShadowMirrorError,
    ShadowMirrorManager, ShadowMirrorStats,
};

// Re-export profiler types
pub use profiler::{
    detect_pattern,
    entropy_z_score,
    is_entropy_anomaly,
    matches_pattern,
    normalized_entropy,
    shannon_entropy,
    AnomalyResult,
    AnomalySignal,
    AnomalySignalType,
    Distribution,
    EndpointProfile,
    FieldSchema,
    FieldType,
    HeaderAnomaly,
    HeaderAnomalyResult,
    HeaderBaseline,
    // Header profiling types (W4.1 HeaderProfiler)
    HeaderProfiler,
    HeaderProfilerStats,
    JsonEndpointSchema,
    ParameterSchema,
    PatternType,
    PercentilesTracker,
    ProfileStore,
    ProfileStoreConfig,
    ProfileStoreMetrics,
    Profiler,
    RateTracker,
    // Schema learning types (ported from libsynapse)
    SchemaLearner,
    SchemaLearnerConfig,
    SchemaLearnerStats,
    SchemaViolation,
    SegmentCardinality,
    ValueStats,
    ViolationSeverity,
    ViolationType,
};

// Re-export profiler config
pub use config::ProfilerConfig;

// Re-export crawler detection types
pub use crawler::{
    BadBotSeverity, BadBotSignature, CrawlerConfig, CrawlerDefinition, CrawlerDetection,
    CrawlerDetector, CrawlerStats, CrawlerStatsSnapshot, CrawlerVerificationResult,
    DnsFailurePolicy, VerificationMethod,
};

// Re-export Signal Horizon integration types
pub use horizon::{
    BlockType, BlocklistCache, BlocklistEntry, BlocklistUpdate, ClientStats, ConnectionState,
    HorizonClient, HorizonConfig, HorizonError, HorizonManager, HorizonStats, HorizonStatsSnapshot,
    Severity, SignalType, ThreatSignal,
};

// Re-export payload profiling types
pub use payload::{
    BandwidthBucket, EndpointPayloadStats, EndpointPayloadStatsSnapshot, EndpointSortBy,
    EntityBandwidth, PayloadAnomaly, PayloadAnomalyMetadata, PayloadAnomalySeverity,
    PayloadAnomalyType, PayloadConfig, PayloadManager, PayloadSummary, PayloadWindow, SizeStats,
};

// Re-export trends/signal tracking types
pub use trends::{
    Anomaly, AnomalyDetector, AnomalyDetectorConfig, AnomalyMetadata, AnomalyQueryOptions,
    AnomalySeverity, AnomalyType, BucketSummary, CategorySummary, Correlation, CorrelationEngine,
    CorrelationMetadata, CorrelationType, Signal, SignalBucket, SignalCategory, SignalExtractor,
    SignalMetadata, SignalTrend, SignalType as TrendsSignalType, TimeStore, TimeStoreStats,
    TrendHistogramBucket, TrendQueryOptions, TrendsConfig, TrendsManager, TrendsManagerStats,
    TrendsStats, TrendsSummary,
};

// Re-export intelligence signal aggregation types
pub use intelligence::{
    Signal as IntelligenceSignal, SignalCategory as IntelligenceSignalCategory, SignalManager,
    SignalManagerConfig, SignalQueryOptions, SignalSummary as IntelligenceSignalSummary,
    TopSignalType as IntelligenceTopSignalType,
};

// Re-export geo/impossible travel types
pub use geo::{
    calculate_speed, haversine_distance, is_valid_coordinates, GeoLocation,
    ImpossibleTravelDetector, LoginEvent, Severity as GeoSeverity, TravelAlert, TravelConfig,
    TravelStats,
};

// Re-export WAF engine types (Phase 10)
pub use waf::{
    boolean_operands, build_rule_index, get_candidate_rule_indices, method_to_mask, now_ms,
    repeat_multiplier, Action as WafRuleAction, AnomalyContribution as WafAnomalyContribution,
    AnomalySignal as WafAnomalySignal, AnomalySignalType as WafAnomalySignalType,
    AnomalyType as WafAnomalyType, ArgEntry, BlockingMode as WafBlockingMode, CandidateCache,
    CandidateCacheKey, Engine as WafEngine, EvalContext, Header as WafHeader, IndexedRule,
    MatchCondition, MatchValue, Request as WafRequest, RiskConfig as WafRiskConfig,
    RiskContribution as WafRiskContribution, RuleIndex, StateStore, Synapse, Verdict as WafVerdict,
    WafError, WafRule,
};

// Re-export credential stuffing detection types (Phase 10)
pub use detection::{
    AuthAttempt, AuthMetrics, AuthResult, CredentialStuffingDetector, DistributedAttack,
    EntityEndpointKey, StuffingConfig, StuffingEvent, StuffingSeverity, StuffingState,
    StuffingStats, StuffingVerdict, TakeoverAlert,
};

// ============================================================================
// Integration Tests: ActorManager + SessionManager Integration
// ============================================================================
// These tests verify the wiring between actor/session managers and the pipeline
// ============================================================================

#[cfg(test)]
mod actor_session_integration_tests {
    use super::*;
    use std::net::IpAddr;
    use std::sync::Arc;

    // ========================================================================
    // Test Helpers
    // ========================================================================

    fn create_test_actor_manager() -> Arc<ActorManager> {
        Arc::new(ActorManager::new(ActorConfig {
            max_actors: 1000,
            decay_interval_secs: 900,
            correlation_threshold: 0.7,
            risk_decay_factor: 0.9,
            max_rule_matches: 100,
            max_session_ids: 50,
            enabled: true,
            max_risk: 100.0,
            persist_interval_secs: 300,
            max_fingerprints_per_actor: 20,
            max_fingerprint_mappings: 500_000,
        }))
    }

    fn create_test_session_manager() -> Arc<SessionManager> {
        Arc::new(SessionManager::new(SessionConfig {
            max_sessions: 1000,
            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,
        }))
    }

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

    // ========================================================================
    // 1. Actor Creation from Request Tests
    // ========================================================================

    #[test]
    fn test_request_with_ip_creates_actor() {
        let actor_manager = create_test_actor_manager();
        let ip = create_test_ip(100);

        let actor_id = actor_manager.get_or_create_actor(ip, None);

        assert!(!actor_id.is_empty());
        assert_eq!(actor_manager.len(), 1);

        let actor = actor_manager.get_actor(&actor_id).unwrap();
        assert!(actor.ips.contains(&ip));
        assert!(!actor.is_blocked);
        assert_eq!(actor.risk_score, 0.0);
    }

    #[test]
    fn test_request_with_ip_and_fingerprint_creates_actor() {
        let actor_manager = create_test_actor_manager();
        let ip = create_test_ip(101);
        let fingerprint = "t13d1516h2_abc123_ja4hash";

        let actor_id = actor_manager.get_or_create_actor(ip, Some(fingerprint));

        let actor = actor_manager.get_actor(&actor_id).unwrap();
        assert!(actor.ips.contains(&ip));
        assert!(actor.fingerprints.contains(fingerprint));
    }

    #[test]
    fn test_multiple_ips_correlated_via_fingerprint() {
        let actor_manager = create_test_actor_manager();
        let ip1 = create_test_ip(1);
        let ip2 = create_test_ip(2);
        let ip3 = create_test_ip(3);
        let shared_fingerprint = "t13d1516h2_shared_fingerprint";

        let actor_id1 = actor_manager.get_or_create_actor(ip1, Some(shared_fingerprint));
        let actor_id2 = actor_manager.get_or_create_actor(ip2, Some(shared_fingerprint));
        let actor_id3 = actor_manager.get_or_create_actor(ip3, Some(shared_fingerprint));

        assert_eq!(actor_id1, actor_id2);
        assert_eq!(actor_id2, actor_id3);
        assert_eq!(actor_manager.len(), 1);

        let actor = actor_manager.get_actor(&actor_id1).unwrap();
        assert!(actor.ips.contains(&ip1));
        assert!(actor.ips.contains(&ip2));
        assert!(actor.ips.contains(&ip3));
        assert_eq!(actor.ips.len(), 3);
    }

    #[test]
    fn test_same_ip_subsequent_requests_correlate() {
        let actor_manager = create_test_actor_manager();
        let ip = create_test_ip(50);

        let actor_id1 = actor_manager.get_or_create_actor(ip, None);
        let actor_id2 = actor_manager.get_or_create_actor(ip, None);
        let actor_id3 = actor_manager.get_or_create_actor(ip, None);

        assert_eq!(actor_id1, actor_id2);
        assert_eq!(actor_id2, actor_id3);
        assert_eq!(actor_manager.len(), 1);
    }

    #[test]
    fn test_different_ips_without_fingerprint_create_separate_actors() {
        let actor_manager = create_test_actor_manager();
        let ip1 = create_test_ip(10);
        let ip2 = create_test_ip(20);

        let actor_id1 = actor_manager.get_or_create_actor(ip1, None);
        let actor_id2 = actor_manager.get_or_create_actor(ip2, None);

        assert_ne!(actor_id1, actor_id2);
        assert_eq!(actor_manager.len(), 2);
    }

    // ========================================================================
    // 2. Rule Match Recording Tests
    // ========================================================================

    #[test]
    fn test_matched_rules_recorded_to_actor_history() {
        let actor_manager = create_test_actor_manager();
        let ip = create_test_ip(100);

        let actor_id = actor_manager.get_or_create_actor(ip, None);
        actor_manager.record_rule_match(&actor_id, "sqli-001", 25.0, "sqli");

        let actor = actor_manager.get_actor(&actor_id).unwrap();
        assert_eq!(actor.rule_matches.len(), 1);
        assert_eq!(actor.rule_matches[0].rule_id, "sqli-001");
        assert_eq!(actor.rule_matches[0].category, "sqli");
        assert_eq!(actor.rule_matches[0].risk_contribution, 25.0);
    }

    #[test]
    fn test_risk_score_accumulates_correctly() {
        let actor_manager = create_test_actor_manager();
        let ip = create_test_ip(101);

        let actor_id = actor_manager.get_or_create_actor(ip, None);

        actor_manager.record_rule_match(&actor_id, "sqli-001", 25.0, "sqli");
        actor_manager.record_rule_match(&actor_id, "xss-001", 20.0, "xss");
        actor_manager.record_rule_match(&actor_id, "path-001", 15.0, "path_traversal");

        let actor = actor_manager.get_actor(&actor_id).unwrap();
        assert_eq!(actor.risk_score, 60.0);
        assert_eq!(actor.rule_matches.len(), 3);
    }

    #[test]
    fn test_risk_score_capped_at_max() {
        let actor_manager = create_test_actor_manager();
        let ip = create_test_ip(102);

        let actor_id = actor_manager.get_or_create_actor(ip, None);

        for i in 0..15 {
            actor_manager.record_rule_match(&actor_id, &format!("rule-{}", i), 10.0, "attack");
        }

        let actor = actor_manager.get_actor(&actor_id).unwrap();
        assert!(actor.risk_score <= 100.0);
        assert_eq!(actor.risk_score, 100.0);
    }

    #[test]
    fn test_category_mapping_works() {
        let actor_manager = create_test_actor_manager();
        let ip = create_test_ip(103);

        let actor_id = actor_manager.get_or_create_actor(ip, None);

        actor_manager.record_rule_match(&actor_id, "rule_940001", 10.0, "sqli");
        actor_manager.record_rule_match(&actor_id, "rule_941001", 10.0, "xss");
        actor_manager.record_rule_match(&actor_id, "rule_930001", 10.0, "path_traversal");
        actor_manager.record_rule_match(&actor_id, "rule_932001", 10.0, "rce");
        actor_manager.record_rule_match(&actor_id, "rule_913001", 10.0, "scanner");

        let actor = actor_manager.get_actor(&actor_id).unwrap();
        let categories: Vec<&str> = actor
            .rule_matches
            .iter()
            .map(|m| m.category.as_str())
            .collect();
        assert!(categories.contains(&"sqli"));
        assert!(categories.contains(&"xss"));
        assert!(categories.contains(&"path_traversal"));
        assert!(categories.contains(&"rce"));
        assert!(categories.contains(&"scanner"));
    }

    // ========================================================================
    // 3. Actor Blocking Tests
    // ========================================================================

    #[test]
    fn test_high_risk_actor_gets_blocked() {
        let actor_manager = create_test_actor_manager();
        let ip = create_test_ip(100);

        let actor_id = actor_manager.get_or_create_actor(ip, None);
        assert!(!actor_manager.is_blocked(&actor_id));

        let blocked = actor_manager.block_actor(&actor_id, "High risk score exceeded threshold");

        assert!(blocked);
        assert!(actor_manager.is_blocked(&actor_id));

        let actor = actor_manager.get_actor(&actor_id).unwrap();
        assert!(actor.is_blocked);
        assert_eq!(
            actor.block_reason,
            Some("High risk score exceeded threshold".to_string())
        );
        assert!(actor.blocked_since.is_some());
    }

    #[test]
    fn test_block_decision_enforced_in_subsequent_requests() {
        let actor_manager = create_test_actor_manager();
        let ip = create_test_ip(101);
        let fingerprint = "blocked_actor_fingerprint";

        let actor_id = actor_manager.get_or_create_actor(ip, Some(fingerprint));
        actor_manager.block_actor(&actor_id, "Malicious activity detected");

        let actor_id2 = actor_manager.get_or_create_actor(ip, Some(fingerprint));
        assert_eq!(actor_id, actor_id2);
        assert!(actor_manager.is_blocked(&actor_id2));

        let ip2 = create_test_ip(102);
        let actor_id3 = actor_manager.get_or_create_actor(ip2, Some(fingerprint));
        assert_eq!(actor_id, actor_id3);
        assert!(actor_manager.is_blocked(&actor_id3));
    }

    #[test]
    fn test_unblock_actor() {
        let actor_manager = create_test_actor_manager();
        let ip = create_test_ip(103);

        let actor_id = actor_manager.get_or_create_actor(ip, None);

        actor_manager.block_actor(&actor_id, "Test block");
        assert!(actor_manager.is_blocked(&actor_id));

        let unblocked = actor_manager.unblock_actor(&actor_id);
        assert!(unblocked);
        assert!(!actor_manager.is_blocked(&actor_id));

        let actor = actor_manager.get_actor(&actor_id).unwrap();
        assert!(!actor.is_blocked);
        assert!(actor.block_reason.is_none());
        assert!(actor.blocked_since.is_none());
    }

    #[test]
    fn test_list_blocked_actors() {
        let actor_manager = create_test_actor_manager();

        for i in 0..10 {
            let ip = create_test_ip(i);
            let actor_id = actor_manager.get_or_create_actor(ip, None);
            if i % 2 == 0 {
                actor_manager.block_actor(&actor_id, &format!("Blocked actor {}", i));
            }
        }

        let blocked = actor_manager.list_blocked_actors();
        assert_eq!(blocked.len(), 5);

        for actor in blocked {
            assert!(actor.is_blocked);
        }
    }

    #[test]
    fn test_blocking_updates_statistics() {
        let actor_manager = create_test_actor_manager();
        let ip = create_test_ip(105);

        let actor_id = actor_manager.get_or_create_actor(ip, None);

        let stats = actor_manager.stats().snapshot();
        assert_eq!(stats.blocked_actors, 0);

        actor_manager.block_actor(&actor_id, "Test");

        let stats = actor_manager.stats().snapshot();
        assert_eq!(stats.blocked_actors, 1);

        actor_manager.unblock_actor(&actor_id);

        let stats = actor_manager.stats().snapshot();
        assert_eq!(stats.blocked_actors, 0);
    }

    // ========================================================================
    // 4. Session Validation Tests
    // ========================================================================

    #[test]
    fn test_session_token_extraction_and_validation() {
        let session_manager = create_test_session_manager();
        let ip = create_test_ip(100);
        let token_hash = "abc123def456";

        let decision = session_manager.validate_request(token_hash, ip, None);
        assert_eq!(decision, SessionDecision::New);
        assert_eq!(session_manager.len(), 1);

        let decision = session_manager.validate_request(token_hash, ip, None);
        assert_eq!(decision, SessionDecision::Valid);
        assert_eq!(session_manager.len(), 1);
    }

    #[test]
    fn test_valid_session_passes() {
        let session_manager = create_test_session_manager();
        let ip = create_test_ip(101);
        let token_hash = "valid_session_hash";
        let ja4 = "t13d1516h2_fingerprint";

        session_manager.create_session(token_hash, ip, Some(ja4));

        let decision = session_manager.validate_request(token_hash, ip, Some(ja4));
        assert_eq!(decision, SessionDecision::Valid);
    }

    #[test]
    fn test_ja4_mismatch_triggers_alert() {
        let session_manager = create_test_session_manager();
        let ip = create_test_ip(102);
        let token_hash = "session_for_hijack_test";
        let original_ja4 = "t13d1516h2_original_fingerprint";
        let new_ja4 = "t13d1516h2_different_fingerprint";

        session_manager.create_session(token_hash, ip, Some(original_ja4));

        let decision = session_manager.validate_request(token_hash, ip, Some(new_ja4));

        match decision {
            SessionDecision::Suspicious(alert) => {
                assert_eq!(alert.alert_type, HijackType::Ja4Mismatch);
                assert_eq!(alert.original_value, original_ja4);
                assert_eq!(alert.new_value, new_ja4);
                assert!(
                    alert.confidence >= 0.9,
                    "JA4 mismatch should have high confidence"
                );
            }
            _ => panic!(
                "Expected Suspicious decision for JA4 mismatch, got {:?}",
                decision
            ),
        }
    }

    #[test]
    fn test_expired_session_detected() {
        let config = SessionConfig {
            session_ttl_secs: 0, // Immediate expiration
            idle_timeout_secs: 3600,
            ..SessionConfig::default()
        };
        let session_manager = Arc::new(SessionManager::new(config));
        let ip = create_test_ip(103);
        let token_hash = "expiring_session";

        session_manager.create_session(token_hash, ip, None);
        std::thread::sleep(std::time::Duration::from_millis(10));

        let decision = session_manager.validate_request(token_hash, ip, None);
        assert_eq!(decision, SessionDecision::Expired);
    }

    #[test]
    fn test_session_request_count_increments() {
        let session_manager = create_test_session_manager();
        let ip = create_test_ip(104);
        let token_hash = "counting_session";

        session_manager.validate_request(token_hash, ip, None); // New
        session_manager.validate_request(token_hash, ip, None); // Valid
        session_manager.validate_request(token_hash, ip, None); // Valid
        session_manager.validate_request(token_hash, ip, None); // Valid

        let session = session_manager.get_session(token_hash).unwrap();
        assert_eq!(session.request_count, 4);
    }

    #[test]
    fn test_first_ja4_binds_to_session() {
        let session_manager = create_test_session_manager();
        let ip = create_test_ip(105);
        let token_hash = "binding_session";
        let ja4 = "t13d1516h2_bound_fingerprint";

        session_manager.create_session(token_hash, ip, None);

        let session = session_manager.get_session(token_hash).unwrap();
        assert!(session.bound_ja4.is_none());

        session_manager.validate_request(token_hash, ip, Some(ja4));

        let session = session_manager.get_session(token_hash).unwrap();
        assert_eq!(session.bound_ja4, Some(ja4.to_string()));
    }

    #[test]
    fn test_session_with_no_ja4_binding_allows_any_fingerprint() {
        let config = SessionConfig {
            enable_ja4_binding: false,
            ..SessionConfig::default()
        };
        let session_manager = Arc::new(SessionManager::new(config));
        let ip = create_test_ip(106);
        let token_hash = "unbound_session";

        session_manager.create_session(token_hash, ip, Some("original_ja4"));

        let decision = session_manager.validate_request(token_hash, ip, Some("different_ja4"));
        assert_eq!(decision, SessionDecision::Valid);
    }

    // ========================================================================
    // 5. Admin API Integration Tests
    // ========================================================================

    #[test]
    fn test_get_actors_returns_real_data() {
        let actor_manager = create_test_actor_manager();

        for i in 0..5 {
            let ip = create_test_ip(i);
            let actor_id = actor_manager.get_or_create_actor(ip, None);
            actor_manager.record_rule_match(&actor_id, &format!("rule-{}", i), 10.0, "test");
        }

        let api_handler = api::ApiHandler::builder()
            .actor_manager(Arc::clone(&actor_manager))
            .build();

        let actors = api_handler.handle_list_actors(10);

        assert_eq!(actors.len(), 5);
        for actor in &actors {
            assert!(!actor.actor_id.is_empty());
            assert_eq!(actor.rule_matches.len(), 1);
            assert_eq!(actor.risk_score, 10.0);
        }
    }

    #[test]
    fn test_get_sessions_returns_real_data() {
        let session_manager = create_test_session_manager();

        for i in 0..5 {
            let ip = create_test_ip(i);
            let token_hash = format!("session_token_{}", i);
            session_manager.create_session(&token_hash, ip, Some(&format!("ja4_{}", i)));
        }

        let api_handler = api::ApiHandler::builder()
            .session_manager(Arc::clone(&session_manager))
            .build();

        let sessions = api_handler.handle_list_sessions(10);

        assert_eq!(sessions.len(), 5);
        for session in &sessions {
            assert!(!session.session_id.is_empty());
            assert!(session.session_id.starts_with("sess-"));
            assert!(session.bound_ja4.is_some());
        }
    }

    #[test]
    fn test_get_actor_stats_returns_real_data() {
        let actor_manager = create_test_actor_manager();

        for i in 0..10 {
            let ip = create_test_ip(i);
            let actor_id = actor_manager.get_or_create_actor(ip, None);
            actor_manager.record_rule_match(&actor_id, "test-rule", 5.0, "test");
            if i % 3 == 0 {
                actor_manager.block_actor(&actor_id, "Test block");
            }
        }

        let api_handler = api::ApiHandler::builder()
            .actor_manager(Arc::clone(&actor_manager))
            .build();

        let stats = api_handler.handle_actor_stats();

        assert!(stats.is_some());
        let stats = stats.unwrap();
        assert_eq!(stats.total_actors, 10);
        assert_eq!(stats.blocked_actors, 4); // 0, 3, 6, 9
        assert_eq!(stats.total_created, 10);
        assert_eq!(stats.total_rule_matches, 10);
    }

    #[test]
    fn test_get_session_stats_returns_real_data() {
        let session_manager = create_test_session_manager();

        for i in 0..5 {
            let ip = create_test_ip(i);
            let token_hash = format!("session_{}", i);
            session_manager.create_session(&token_hash, ip, None);
        }

        let api_handler = api::ApiHandler::builder()
            .session_manager(Arc::clone(&session_manager))
            .build();

        let stats = api_handler.handle_session_stats();

        assert!(stats.is_some());
        let stats = stats.unwrap();
        assert_eq!(stats.total_sessions, 5);
        assert_eq!(stats.active_sessions, 5);
        assert_eq!(stats.total_created, 5);
    }

    #[test]
    fn test_api_handler_without_managers_returns_empty() {
        let api_handler = api::ApiHandler::builder().build();

        let actors = api_handler.handle_list_actors(10);
        assert!(actors.is_empty());

        let sessions = api_handler.handle_list_sessions(10);
        assert!(sessions.is_empty());

        let actor_stats = api_handler.handle_actor_stats();
        assert!(actor_stats.is_none());

        let session_stats = api_handler.handle_session_stats();
        assert!(session_stats.is_none());
    }

    #[test]
    fn test_list_actors_respects_limit() {
        let actor_manager = create_test_actor_manager();

        for i in 0..20 {
            let ip = create_test_ip(i);
            actor_manager.get_or_create_actor(ip, None);
        }

        let api_handler = api::ApiHandler::builder()
            .actor_manager(Arc::clone(&actor_manager))
            .build();

        let actors = api_handler.handle_list_actors(5);
        assert_eq!(actors.len(), 5);

        let actors = api_handler.handle_list_actors(100);
        assert_eq!(actors.len(), 20);
    }

    // ========================================================================
    // 6. Combined Actor + Session Integration Tests
    // ========================================================================

    #[test]
    fn test_session_bound_to_actor() {
        let actor_manager = create_test_actor_manager();
        let session_manager = create_test_session_manager();
        let ip = create_test_ip(100);
        let fingerprint = "combined_test_fingerprint";
        let token_hash = "combined_session_token";

        let actor_id = actor_manager.get_or_create_actor(ip, Some(fingerprint));
        session_manager.create_session(token_hash, ip, Some(fingerprint));
        session_manager.bind_to_actor(token_hash, &actor_id);

        let session = session_manager.get_session(token_hash).unwrap();
        assert_eq!(session.actor_id, Some(actor_id.clone()));

        let actor_sessions = session_manager.get_actor_sessions(&actor_id);
        assert_eq!(actor_sessions.len(), 1);
        assert_eq!(actor_sessions[0].token_hash, token_hash);
    }

    #[test]
    fn test_multi_session_single_actor() {
        let actor_manager = create_test_actor_manager();
        let session_manager = create_test_session_manager();
        let ip = create_test_ip(101);
        let fingerprint = "multi_session_fingerprint";

        let actor_id = actor_manager.get_or_create_actor(ip, Some(fingerprint));

        session_manager.create_session("session_tab_1", ip, Some(fingerprint));
        session_manager.create_session("session_tab_2", ip, Some(fingerprint));
        session_manager.create_session("session_mobile", ip, Some(fingerprint));

        session_manager.bind_to_actor("session_tab_1", &actor_id);
        session_manager.bind_to_actor("session_tab_2", &actor_id);
        session_manager.bind_to_actor("session_mobile", &actor_id);

        let actor_sessions = session_manager.get_actor_sessions(&actor_id);
        assert_eq!(actor_sessions.len(), 3);
    }

    #[test]
    fn test_blocked_actor_affects_all_sessions() {
        let actor_manager = create_test_actor_manager();
        let session_manager = create_test_session_manager();
        let ip = create_test_ip(102);
        let fingerprint = "blocked_user_fingerprint";

        let actor_id = actor_manager.get_or_create_actor(ip, Some(fingerprint));
        session_manager.create_session("blocked_user_session_1", ip, Some(fingerprint));
        session_manager.create_session("blocked_user_session_2", ip, Some(fingerprint));
        session_manager.bind_to_actor("blocked_user_session_1", &actor_id);
        session_manager.bind_to_actor("blocked_user_session_2", &actor_id);

        actor_manager.block_actor(&actor_id, "Malicious activity");

        assert!(actor_manager.is_blocked(&actor_id));

        let sessions = session_manager.get_actor_sessions(&actor_id);
        assert_eq!(sessions.len(), 2);

        let actor_id_check = actor_manager.get_or_create_actor(ip, Some(fingerprint));
        assert_eq!(actor_id, actor_id_check);
        assert!(actor_manager.is_blocked(&actor_id_check));
    }

    #[test]
    fn test_risk_accumulation_workflow() {
        let actor_manager = create_test_actor_manager();
        let ip = create_test_ip(103);

        let actor_id = actor_manager.get_or_create_actor(ip, None);

        actor_manager.record_rule_match(&actor_id, "sqli-001", 30.0, "sqli");
        let actor = actor_manager.get_actor(&actor_id).unwrap();
        assert_eq!(actor.risk_score, 30.0);
        assert!(!actor_manager.is_blocked(&actor_id));

        actor_manager.record_rule_match(&actor_id, "sqli-002", 40.0, "sqli");
        let actor = actor_manager.get_actor(&actor_id).unwrap();
        assert_eq!(actor.risk_score, 70.0);
        assert!(!actor_manager.is_blocked(&actor_id));

        actor_manager.record_rule_match(&actor_id, "xss-001", 20.0, "xss");
        let actor = actor_manager.get_actor(&actor_id).unwrap();
        assert_eq!(actor.risk_score, 90.0);

        if actor.risk_score >= 80.0 {
            actor_manager.block_actor(&actor_id, "Risk threshold exceeded");
        }

        assert!(actor_manager.is_blocked(&actor_id));
    }
}