lonkero 3.6.2

Web scanner built for actual pentests. Fast, modular, Rust.
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
// Copyright (c) 2026 Bountyy Oy. All rights reserved.
// This software is proprietary and confidential.

//! Intelligence Bus - Real-time scanner communication
//!
//! Allows scanners to share discoveries in real-time so other scanners
//! can adapt their testing strategies immediately.
//!
//! # Architecture
//!
//! The Intelligence Bus uses a publish-subscribe pattern with tokio's broadcast
//! channel for real-time event distribution. Key features:
//!
//! - **Real-time broadcasting**: Events are immediately sent to all subscribers
//! - **Accumulated state**: Late-joining scanners can access all previously discovered intelligence
//! - **Thread-safe**: Uses Arc and RwLock for safe concurrent access
//! - **Typed events**: Strongly typed events prevent miscommunication between scanners
//!
//! # Example
//!
//! ```rust,ignore
//! use lonkero::analysis::intelligence_bus::{IntelligenceBus, AuthType, IntelligenceEvent};
//! use std::sync::Arc;
//!
//! #[tokio::main]
//! async fn main() {
//!     let bus = Arc::new(IntelligenceBus::new());
//!
//!     // Scanner A subscribes
//!     let mut rx = bus.subscribe();
//!
//!     // Scanner B reports a discovery
//!     bus.report_auth_type(AuthType::JWT, 0.95, "https://api.example.com/login").await;
//!
//!     // Scanner A receives the event
//!     if let Ok(event) = rx.recv().await {
//!         println!("Received: {:?}", event);
//!     }
//! }
//! ```

use std::fmt;
use std::sync::Arc;
use tokio::sync::broadcast;
use tokio::sync::RwLock;
use tracing::{debug, info, warn};

/// Default capacity for the broadcast channel
const CHANNEL_CAPACITY: usize = 1000;

/// Authentication types detected in the target application
#[derive(Debug, Clone, PartialEq)]
pub enum AuthType {
    /// JSON Web Token authentication
    JWT,
    /// OAuth 2.0 authentication
    OAuth2,
    /// Session-based authentication (cookies)
    Session,
    /// HTTP Basic authentication
    Basic,
    /// API Key authentication (header or query param)
    ApiKey,
    /// Bearer token (non-JWT)
    Bearer,
    /// SAML authentication
    SAML,
    /// OpenID Connect
    OIDC,
    /// Custom authentication scheme
    Custom(String),
}

impl fmt::Display for AuthType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AuthType::JWT => write!(f, "JWT"),
            AuthType::OAuth2 => write!(f, "OAuth2"),
            AuthType::Session => write!(f, "Session"),
            AuthType::Basic => write!(f, "Basic"),
            AuthType::ApiKey => write!(f, "API Key"),
            AuthType::Bearer => write!(f, "Bearer"),
            AuthType::SAML => write!(f, "SAML"),
            AuthType::OIDC => write!(f, "OpenID Connect"),
            AuthType::Custom(s) => write!(f, "Custom({})", s),
        }
    }
}

/// Types of parameters that may be sensitive or exploitable
#[derive(Debug, Clone, PartialEq)]
pub enum ParameterType {
    /// Identifier parameter (user_id, id, etc.)
    Id,
    /// Authentication-related parameter
    Auth,
    /// File path or name parameter
    File,
    /// URL parameter (redirect, callback, etc.)
    Url,
    /// Command or system execution parameter
    Command,
    /// Search query parameter
    Search,
    /// Email address parameter
    Email,
    /// Admin or privilege-related parameter
    Admin,
    /// Database query parameter
    Database,
    /// Template or format parameter
    Template,
    /// Numeric parameter
    Numeric,
    /// JSON or structured data parameter
    Json,
    /// Configuration parameter
    Config,
}

impl fmt::Display for ParameterType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParameterType::Id => write!(f, "ID"),
            ParameterType::Auth => write!(f, "Auth"),
            ParameterType::File => write!(f, "File"),
            ParameterType::Url => write!(f, "URL"),
            ParameterType::Command => write!(f, "Command"),
            ParameterType::Search => write!(f, "Search"),
            ParameterType::Email => write!(f, "Email"),
            ParameterType::Admin => write!(f, "Admin"),
            ParameterType::Database => write!(f, "Database"),
            ParameterType::Template => write!(f, "Template"),
            ParameterType::Numeric => write!(f, "Numeric"),
            ParameterType::Json => write!(f, "JSON"),
            ParameterType::Config => write!(f, "Config"),
        }
    }
}

/// Types of vulnerability patterns detected
#[derive(Debug, Clone, PartialEq)]
pub enum PatternType {
    /// SQL error message detected
    SqlError,
    /// File path disclosure
    PathDisclosure,
    /// Stack trace or debug output
    StackTrace,
    /// Version information leak
    VersionLeak,
    /// Internal IP address disclosure
    InternalIp,
    /// XML parsing error
    XmlError,
    /// JSON parsing error
    JsonError,
    /// Template engine error
    TemplateError,
    /// Command execution error
    CommandError,
    /// LDAP error
    LdapError,
    /// Authentication error details
    AuthError,
    /// Rate limiting response
    RateLimitResponse,
    /// Debug mode indicator
    DebugMode,
}

impl fmt::Display for PatternType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PatternType::SqlError => write!(f, "SQL Error"),
            PatternType::PathDisclosure => write!(f, "Path Disclosure"),
            PatternType::StackTrace => write!(f, "Stack Trace"),
            PatternType::VersionLeak => write!(f, "Version Leak"),
            PatternType::InternalIp => write!(f, "Internal IP"),
            PatternType::XmlError => write!(f, "XML Error"),
            PatternType::JsonError => write!(f, "JSON Error"),
            PatternType::TemplateError => write!(f, "Template Error"),
            PatternType::CommandError => write!(f, "Command Error"),
            PatternType::LdapError => write!(f, "LDAP Error"),
            PatternType::AuthError => write!(f, "Auth Error"),
            PatternType::RateLimitResponse => write!(f, "Rate Limit"),
            PatternType::DebugMode => write!(f, "Debug Mode"),
        }
    }
}

/// Types of endpoint patterns detected
#[derive(Debug, Clone, PartialEq)]
pub enum EndpointPatternType {
    /// RESTful CRUD endpoints
    RestCrud,
    /// GraphQL endpoint
    GraphQL,
    /// JSON-RPC endpoint
    JsonRpc,
    /// API versioning pattern (v1, v2, etc.)
    ApiVersioning,
    /// Internal/admin API endpoints
    InternalApi,
    /// Batch/bulk operation endpoints
    BatchApi,
    /// WebSocket endpoints
    WebSocket,
    /// Server-Sent Events endpoints
    ServerSentEvents,
    /// gRPC endpoints
    GRPC,
    /// Legacy/deprecated endpoints
    LegacyApi,
    /// Health check endpoints
    HealthCheck,
    /// Metrics/monitoring endpoints
    Metrics,
}

impl fmt::Display for EndpointPatternType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            EndpointPatternType::RestCrud => write!(f, "REST CRUD"),
            EndpointPatternType::GraphQL => write!(f, "GraphQL"),
            EndpointPatternType::JsonRpc => write!(f, "JSON-RPC"),
            EndpointPatternType::ApiVersioning => write!(f, "API Versioning"),
            EndpointPatternType::InternalApi => write!(f, "Internal API"),
            EndpointPatternType::BatchApi => write!(f, "Batch API"),
            EndpointPatternType::WebSocket => write!(f, "WebSocket"),
            EndpointPatternType::ServerSentEvents => write!(f, "SSE"),
            EndpointPatternType::GRPC => write!(f, "gRPC"),
            EndpointPatternType::LegacyApi => write!(f, "Legacy API"),
            EndpointPatternType::HealthCheck => write!(f, "Health Check"),
            EndpointPatternType::Metrics => write!(f, "Metrics"),
        }
    }
}

/// Types of insights scanners can share
#[derive(Debug, Clone, PartialEq)]
pub enum InsightType {
    /// A security bypass was found
    BypassFound,
    /// Weak input validation detected
    WeakValidation,
    /// Missing authentication on endpoint
    MissingAuth,
    /// Rate limiting can be bypassed
    RateLimitBypass,
    /// Cache control issues
    CacheControl,
    /// CORS misconfiguration
    CorsMisconfig,
    /// Session handling weakness
    SessionWeakness,
    /// Privilege escalation possibility
    PrivilegeEscalation,
    /// Information disclosure
    InfoDisclosure,
    /// Injection point found
    InjectionPoint,
}

impl fmt::Display for InsightType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            InsightType::BypassFound => write!(f, "Bypass Found"),
            InsightType::WeakValidation => write!(f, "Weak Validation"),
            InsightType::MissingAuth => write!(f, "Missing Auth"),
            InsightType::RateLimitBypass => write!(f, "Rate Limit Bypass"),
            InsightType::CacheControl => write!(f, "Cache Control"),
            InsightType::CorsMisconfig => write!(f, "CORS Misconfiguration"),
            InsightType::SessionWeakness => write!(f, "Session Weakness"),
            InsightType::PrivilegeEscalation => write!(f, "Privilege Escalation"),
            InsightType::InfoDisclosure => write!(f, "Info Disclosure"),
            InsightType::InjectionPoint => write!(f, "Injection Point"),
        }
    }
}

/// Events that can be broadcast through the Intelligence Bus
#[derive(Debug, Clone)]
pub enum IntelligenceEvent {
    /// Authentication type detected on the target
    AuthTypeDetected {
        auth_type: AuthType,
        confidence: f32,
        source_url: String,
    },

    /// Framework or technology detected
    FrameworkDetected {
        name: String,
        version: Option<String>,
        confidence: f32,
    },

    /// Sensitive parameter found
    SensitiveParameterFound {
        param_name: String,
        param_type: ParameterType,
        endpoint: String,
    },

    /// Vulnerability pattern detected
    VulnerabilityPattern {
        pattern_type: PatternType,
        evidence: String,
        endpoint: Option<String>,
    },

    /// Web Application Firewall detected
    WafDetected {
        waf_type: String,
        bypass_hints: Vec<String>,
    },

    /// Endpoint pattern identified
    EndpointPattern {
        pattern: EndpointPatternType,
        examples: Vec<String>,
    },

    /// Technology stack update
    TechStackUpdate { technologies: Vec<String> },

    /// Scanner-specific insight
    ScannerInsight {
        scanner_name: String,
        insight_type: InsightType,
        data: String,
    },

    /// Custom event for extensibility
    Custom { event_type: String, data: String },
}

impl fmt::Display for IntelligenceEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            IntelligenceEvent::AuthTypeDetected {
                auth_type,
                confidence,
                source_url,
            } => {
                write!(
                    f,
                    "Auth Detected: {} (confidence: {:.0}%) from {}",
                    auth_type,
                    confidence * 100.0,
                    source_url
                )
            }
            IntelligenceEvent::FrameworkDetected {
                name,
                version,
                confidence,
            } => {
                let ver = version.as_deref().unwrap_or("unknown");
                write!(
                    f,
                    "Framework: {} v{} (confidence: {:.0}%)",
                    name,
                    ver,
                    confidence * 100.0
                )
            }
            IntelligenceEvent::SensitiveParameterFound {
                param_name,
                param_type,
                endpoint,
            } => {
                write!(
                    f,
                    "Sensitive Param: {} ({}) at {}",
                    param_name, param_type, endpoint
                )
            }
            IntelligenceEvent::VulnerabilityPattern {
                pattern_type,
                evidence,
                endpoint,
            } => {
                let ep = endpoint.as_deref().unwrap_or("unknown");
                write!(
                    f,
                    "Vuln Pattern: {} at {} - {}",
                    pattern_type,
                    ep,
                    &evidence[..evidence.len().min(50)]
                )
            }
            IntelligenceEvent::WafDetected {
                waf_type,
                bypass_hints,
            } => {
                write!(
                    f,
                    "WAF Detected: {} ({} bypass hints)",
                    waf_type,
                    bypass_hints.len()
                )
            }
            IntelligenceEvent::EndpointPattern { pattern, examples } => {
                write!(
                    f,
                    "Endpoint Pattern: {} ({} examples)",
                    pattern,
                    examples.len()
                )
            }
            IntelligenceEvent::TechStackUpdate { technologies } => {
                write!(f, "Tech Stack: {}", technologies.join(", "))
            }
            IntelligenceEvent::ScannerInsight {
                scanner_name,
                insight_type,
                data,
            } => {
                write!(
                    f,
                    "Insight from {}: {} - {}",
                    scanner_name, insight_type, data
                )
            }
            IntelligenceEvent::Custom { event_type, data } => {
                write!(f, "Custom Event: {} - {}", event_type, data)
            }
        }
    }
}

/// Accumulated intelligence from all events
///
/// This structure stores all intelligence gathered during a scan,
/// allowing late-joining scanners to access previously discovered information.
#[derive(Debug, Default, Clone)]
pub struct AccumulatedIntelligence {
    /// Detected authentication types with confidence scores
    pub auth_types: Vec<(AuthType, f32, String)>,
    /// Detected frameworks with versions and confidence
    pub frameworks: Vec<(String, Option<String>, f32)>,
    /// Sensitive parameters found
    pub sensitive_params: Vec<(String, ParameterType, String)>,
    /// WAF information if detected
    pub waf_info: Option<(String, Vec<String>)>,
    /// Endpoint patterns identified
    pub endpoint_patterns: Vec<(EndpointPatternType, Vec<String>)>,
    /// Technology stack
    pub tech_stack: Vec<String>,
    /// Vulnerability patterns found
    pub vulnerability_patterns: Vec<(PatternType, String)>,
    /// Scanner insights
    pub insights: Vec<(String, InsightType, String)>,
}

impl AccumulatedIntelligence {
    /// Create a new empty accumulated intelligence store
    pub fn new() -> Self {
        Self::default()
    }

    /// Get the primary authentication type (highest confidence)
    pub fn primary_auth_type(&self) -> Option<&AuthType> {
        self.auth_types
            .iter()
            .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(auth, _, _)| auth)
    }

    /// Check if a specific framework is detected
    pub fn has_framework(&self, name: &str) -> bool {
        self.frameworks
            .iter()
            .any(|(n, _, _)| n.to_lowercase() == name.to_lowercase())
    }

    /// Check if WAF is detected
    pub fn has_waf(&self) -> bool {
        self.waf_info.is_some()
    }

    /// Get WAF bypass hints if available
    pub fn waf_bypass_hints(&self) -> Vec<String> {
        self.waf_info
            .as_ref()
            .map(|(_, hints)| hints.clone())
            .unwrap_or_default()
    }

    /// Check if a technology is in the stack
    pub fn has_technology(&self, tech: &str) -> bool {
        self.tech_stack
            .iter()
            .any(|t| t.to_lowercase().contains(&tech.to_lowercase()))
    }

    /// Get all sensitive parameters of a specific type
    pub fn params_of_type(&self, param_type: &ParameterType) -> Vec<&str> {
        self.sensitive_params
            .iter()
            .filter(|(_, pt, _)| pt == param_type)
            .map(|(name, _, _)| name.as_str())
            .collect()
    }

    /// Check if any vulnerability patterns were found
    pub fn has_vulnerability_patterns(&self) -> bool {
        !self.vulnerability_patterns.is_empty()
    }

    /// Get insights from a specific scanner
    pub fn insights_from(&self, scanner_name: &str) -> Vec<(&InsightType, &str)> {
        self.insights
            .iter()
            .filter(|(name, _, _)| name == scanner_name)
            .map(|(_, insight_type, data)| (insight_type, data.as_str()))
            .collect()
    }
}

/// The Intelligence Bus for real-time scanner communication
///
/// This is the central hub for scanner-to-scanner communication.
/// Scanners can broadcast discoveries and subscribe to updates from other scanners.
pub struct IntelligenceBus {
    /// Broadcast sender for real-time events
    sender: broadcast::Sender<IntelligenceEvent>,
    /// Accumulated intelligence for late-joining scanners
    accumulated: Arc<RwLock<AccumulatedIntelligence>>,
    /// Event counter for statistics
    event_count: Arc<std::sync::atomic::AtomicU64>,
}

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

impl IntelligenceBus {
    /// Create a new Intelligence Bus
    ///
    /// Initializes the broadcast channel with default capacity and
    /// an empty accumulated intelligence store.
    pub fn new() -> Self {
        Self::with_capacity(CHANNEL_CAPACITY)
    }

    /// Create a new Intelligence Bus with custom channel capacity
    pub fn with_capacity(capacity: usize) -> Self {
        let (sender, _) = broadcast::channel(capacity);
        Self {
            sender,
            accumulated: Arc::new(RwLock::new(AccumulatedIntelligence::new())),
            event_count: Arc::new(std::sync::atomic::AtomicU64::new(0)),
        }
    }

    /// Subscribe to intelligence events
    ///
    /// Returns a receiver that will receive all future events.
    /// Use `get_accumulated()` to get events that occurred before subscribing.
    pub fn subscribe(&self) -> broadcast::Receiver<IntelligenceEvent> {
        self.sender.subscribe()
    }

    /// Get the number of current subscribers
    pub fn subscriber_count(&self) -> usize {
        self.sender.receiver_count()
    }

    /// Get the total number of events broadcast
    pub fn event_count(&self) -> u64 {
        self.event_count.load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Broadcast an intelligence event
    ///
    /// Sends the event to all subscribers and updates the accumulated intelligence.
    pub async fn broadcast(&self, event: IntelligenceEvent) {
        // Update accumulated intelligence
        self.update_accumulated(&event).await;

        // Increment event counter
        self.event_count
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);

        // Send to subscribers
        let receiver_count = self.sender.receiver_count();
        if receiver_count > 0 {
            match self.sender.send(event.clone()) {
                Ok(count) => {
                    debug!(
                        "Broadcast intelligence event to {} receivers: {}",
                        count, event
                    );
                }
                Err(e) => {
                    warn!("Failed to broadcast intelligence event: {}", e);
                }
            }
        } else {
            debug!("No subscribers for intelligence event: {}", event);
        }
    }

    /// Update accumulated intelligence based on event
    async fn update_accumulated(&self, event: &IntelligenceEvent) {
        let mut accumulated = self.accumulated.write().await;

        match event {
            IntelligenceEvent::AuthTypeDetected {
                auth_type,
                confidence,
                source_url,
            } => {
                // Check if we already have this auth type
                let exists = accumulated
                    .auth_types
                    .iter()
                    .any(|(at, _, _)| at == auth_type);
                if !exists {
                    accumulated.auth_types.push((
                        auth_type.clone(),
                        *confidence,
                        source_url.clone(),
                    ));
                    info!(
                        "Intelligence: {} detected with {:.0}% confidence",
                        auth_type,
                        confidence * 100.0
                    );
                }
            }
            IntelligenceEvent::FrameworkDetected {
                name,
                version,
                confidence,
            } => {
                let exists = accumulated
                    .frameworks
                    .iter()
                    .any(|(n, _, _)| n.to_lowercase() == name.to_lowercase());
                if !exists {
                    accumulated
                        .frameworks
                        .push((name.clone(), version.clone(), *confidence));
                    info!(
                        "Intelligence: Framework {} {:?} detected with {:.0}% confidence",
                        name,
                        version,
                        confidence * 100.0
                    );
                }
            }
            IntelligenceEvent::SensitiveParameterFound {
                param_name,
                param_type,
                endpoint,
            } => {
                let exists = accumulated
                    .sensitive_params
                    .iter()
                    .any(|(n, _, e)| n == param_name && e == endpoint);
                if !exists {
                    accumulated.sensitive_params.push((
                        param_name.clone(),
                        param_type.clone(),
                        endpoint.clone(),
                    ));
                    debug!(
                        "Intelligence: Sensitive parameter {} ({}) found at {}",
                        param_name, param_type, endpoint
                    );
                }
            }
            IntelligenceEvent::VulnerabilityPattern {
                pattern_type,
                evidence,
                ..
            } => {
                accumulated
                    .vulnerability_patterns
                    .push((pattern_type.clone(), evidence.clone()));
                info!("Intelligence: {} pattern detected", pattern_type);
            }
            IntelligenceEvent::WafDetected {
                waf_type,
                bypass_hints,
            } => {
                if accumulated.waf_info.is_none() {
                    accumulated.waf_info = Some((waf_type.clone(), bypass_hints.clone()));
                    info!(
                        "Intelligence: WAF {} detected with {} bypass hints",
                        waf_type,
                        bypass_hints.len()
                    );
                } else if let Some((_, ref mut hints)) = accumulated.waf_info {
                    // Merge bypass hints
                    for hint in bypass_hints {
                        if !hints.contains(hint) {
                            hints.push(hint.clone());
                        }
                    }
                }
            }
            IntelligenceEvent::EndpointPattern { pattern, examples } => {
                let exists = accumulated
                    .endpoint_patterns
                    .iter()
                    .any(|(p, _)| p == pattern);
                if !exists {
                    accumulated
                        .endpoint_patterns
                        .push((pattern.clone(), examples.clone()));
                    debug!("Intelligence: {} endpoint pattern detected", pattern);
                }
            }
            IntelligenceEvent::TechStackUpdate { technologies } => {
                for tech in technologies {
                    if !accumulated.tech_stack.contains(tech) {
                        accumulated.tech_stack.push(tech.clone());
                        debug!("Intelligence: Technology {} added to stack", tech);
                    }
                }
            }
            IntelligenceEvent::ScannerInsight {
                scanner_name,
                insight_type,
                data,
            } => {
                accumulated.insights.push((
                    scanner_name.clone(),
                    insight_type.clone(),
                    data.clone(),
                ));
                info!(
                    "Intelligence: {} reported {} - {}",
                    scanner_name, insight_type, data
                );
            }
            IntelligenceEvent::Custom { event_type, data } => {
                debug!("Intelligence: Custom event {} - {}", event_type, data);
            }
        }
    }

    /// Get accumulated intelligence
    ///
    /// Returns a clone of all accumulated intelligence gathered so far.
    /// Useful for scanners that start later in the scan process.
    pub async fn get_accumulated(&self) -> AccumulatedIntelligence {
        self.accumulated.read().await.clone()
    }

    /// Clear accumulated intelligence
    ///
    /// Resets the accumulated intelligence store. Useful for starting a new scan.
    pub async fn clear(&self) {
        let mut accumulated = self.accumulated.write().await;
        *accumulated = AccumulatedIntelligence::new();
        self.event_count
            .store(0, std::sync::atomic::Ordering::Relaxed);
        info!("Intelligence Bus cleared");
    }

    // ============ Convenience methods for common broadcasts ============

    /// Report authentication type detection
    pub async fn report_auth_type(&self, auth_type: AuthType, confidence: f32, source: &str) {
        self.broadcast(IntelligenceEvent::AuthTypeDetected {
            auth_type,
            confidence: confidence.clamp(0.0, 1.0),
            source_url: source.to_string(),
        })
        .await;
    }

    /// Report framework detection
    pub async fn report_framework(&self, name: &str, version: Option<&str>, confidence: f32) {
        self.broadcast(IntelligenceEvent::FrameworkDetected {
            name: name.to_string(),
            version: version.map(String::from),
            confidence: confidence.clamp(0.0, 1.0),
        })
        .await;
    }

    /// Report WAF detection
    pub async fn report_waf(&self, waf_type: &str, bypass_hints: Vec<String>) {
        self.broadcast(IntelligenceEvent::WafDetected {
            waf_type: waf_type.to_string(),
            bypass_hints,
        })
        .await;
    }

    /// Report sensitive parameter discovery
    pub async fn report_sensitive_param(
        &self,
        name: &str,
        param_type: ParameterType,
        endpoint: &str,
    ) {
        self.broadcast(IntelligenceEvent::SensitiveParameterFound {
            param_name: name.to_string(),
            param_type,
            endpoint: endpoint.to_string(),
        })
        .await;
    }

    /// Report vulnerability pattern
    pub async fn report_vulnerability_pattern(
        &self,
        pattern_type: PatternType,
        evidence: &str,
        endpoint: Option<&str>,
    ) {
        self.broadcast(IntelligenceEvent::VulnerabilityPattern {
            pattern_type,
            evidence: evidence.to_string(),
            endpoint: endpoint.map(String::from),
        })
        .await;
    }

    /// Report endpoint pattern
    pub async fn report_endpoint_pattern(
        &self,
        pattern: EndpointPatternType,
        examples: Vec<String>,
    ) {
        self.broadcast(IntelligenceEvent::EndpointPattern { pattern, examples })
            .await;
    }

    /// Report technology stack update
    pub async fn report_tech_stack(&self, technologies: Vec<String>) {
        self.broadcast(IntelligenceEvent::TechStackUpdate { technologies })
            .await;
    }

    /// Report scanner insight
    pub async fn report_insight(&self, scanner_name: &str, insight_type: InsightType, data: &str) {
        self.broadcast(IntelligenceEvent::ScannerInsight {
            scanner_name: scanner_name.to_string(),
            insight_type,
            data: data.to_string(),
        })
        .await;
    }

    /// Report custom event
    pub async fn report_custom(&self, event_type: &str, data: &str) {
        self.broadcast(IntelligenceEvent::Custom {
            event_type: event_type.to_string(),
            data: data.to_string(),
        })
        .await;
    }
}

/// Trait for scanners that can receive and react to intelligence events
pub trait IntelligenceAware: Send + Sync {
    /// Handle an incoming intelligence event
    ///
    /// Implement this method to react to events from other scanners.
    fn on_intelligence(&mut self, event: &IntelligenceEvent);

    /// Get the intelligence bus if available
    fn get_bus(&self) -> Option<Arc<IntelligenceBus>>;

    /// Set the intelligence bus
    fn set_bus(&mut self, bus: Arc<IntelligenceBus>);
}

/// A simple subscriber that collects events
///
/// Useful for testing and debugging.
pub struct IntelligenceCollector {
    bus: Arc<IntelligenceBus>,
    events: Arc<RwLock<Vec<IntelligenceEvent>>>,
}

impl IntelligenceCollector {
    /// Create a new collector attached to a bus
    pub fn new(bus: Arc<IntelligenceBus>) -> Self {
        Self {
            bus,
            events: Arc::new(RwLock::new(Vec::new())),
        }
    }

    /// Start collecting events in the background
    pub fn start_collecting(&self) -> tokio::task::JoinHandle<()> {
        let mut rx = self.bus.subscribe();
        let events = self.events.clone();

        tokio::spawn(async move {
            loop {
                match rx.recv().await {
                    Ok(event) => {
                        events.write().await.push(event);
                    }
                    Err(broadcast::error::RecvError::Closed) => {
                        break;
                    }
                    Err(broadcast::error::RecvError::Lagged(count)) => {
                        warn!("Collector lagged by {} events", count);
                    }
                }
            }
        })
    }

    /// Get all collected events
    pub async fn get_events(&self) -> Vec<IntelligenceEvent> {
        self.events.read().await.clone()
    }

    /// Clear collected events
    pub async fn clear(&self) {
        self.events.write().await.clear();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::time::{timeout, Duration};

    #[tokio::test]
    async fn test_bus_creation() {
        let bus = IntelligenceBus::new();
        assert_eq!(bus.subscriber_count(), 0);
        assert_eq!(bus.event_count(), 0);
    }

    #[tokio::test]
    async fn test_subscribe_and_receive() {
        let bus = Arc::new(IntelligenceBus::new());
        let mut rx = bus.subscribe();

        assert_eq!(bus.subscriber_count(), 1);

        bus.report_auth_type(AuthType::JWT, 0.95, "https://example.com")
            .await;

        let event = timeout(Duration::from_millis(100), rx.recv())
            .await
            .expect("Timeout waiting for event")
            .expect("Failed to receive event");

        match event {
            IntelligenceEvent::AuthTypeDetected {
                auth_type,
                confidence,
                source_url,
            } => {
                assert_eq!(auth_type, AuthType::JWT);
                assert!((confidence - 0.95).abs() < f32::EPSILON);
                assert_eq!(source_url, "https://example.com");
            }
            _ => panic!("Unexpected event type"),
        }
    }

    #[tokio::test]
    async fn test_accumulated_intelligence() {
        let bus = IntelligenceBus::new();

        // Broadcast some events
        bus.report_auth_type(AuthType::JWT, 0.95, "https://api.example.com")
            .await;
        bus.report_framework("Django", Some("4.2"), 0.9).await;
        bus.report_waf("Cloudflare", vec!["Use case variation".to_string()])
            .await;

        // Check accumulated intelligence
        let accumulated = bus.get_accumulated().await;

        assert_eq!(accumulated.auth_types.len(), 1);
        assert_eq!(accumulated.auth_types[0].0, AuthType::JWT);

        assert_eq!(accumulated.frameworks.len(), 1);
        assert_eq!(accumulated.frameworks[0].0, "Django");
        assert_eq!(accumulated.frameworks[0].1, Some("4.2".to_string()));

        assert!(accumulated.has_waf());
        assert!(accumulated.has_framework("django"));
    }

    #[tokio::test]
    async fn test_sensitive_parameter_detection() {
        let bus = IntelligenceBus::new();

        bus.report_sensitive_param("user_id", ParameterType::Id, "/api/users")
            .await;
        bus.report_sensitive_param("admin", ParameterType::Admin, "/api/settings")
            .await;
        bus.report_sensitive_param("file", ParameterType::File, "/api/upload")
            .await;

        let accumulated = bus.get_accumulated().await;
        assert_eq!(accumulated.sensitive_params.len(), 3);

        let id_params = accumulated.params_of_type(&ParameterType::Id);
        assert_eq!(id_params.len(), 1);
        assert_eq!(id_params[0], "user_id");
    }

    #[tokio::test]
    async fn test_vulnerability_pattern() {
        let bus = IntelligenceBus::new();

        bus.report_vulnerability_pattern(
            PatternType::SqlError,
            "You have an error in your SQL syntax",
            Some("/api/search"),
        )
        .await;

        let accumulated = bus.get_accumulated().await;
        assert!(accumulated.has_vulnerability_patterns());
        assert_eq!(accumulated.vulnerability_patterns.len(), 1);
    }

    #[tokio::test]
    async fn test_endpoint_pattern() {
        let bus = IntelligenceBus::new();

        bus.report_endpoint_pattern(
            EndpointPatternType::RestCrud,
            vec!["/api/users".to_string(), "/api/products".to_string()],
        )
        .await;

        let accumulated = bus.get_accumulated().await;
        assert_eq!(accumulated.endpoint_patterns.len(), 1);
        assert_eq!(
            accumulated.endpoint_patterns[0].0,
            EndpointPatternType::RestCrud
        );
    }

    #[tokio::test]
    async fn test_tech_stack_update() {
        let bus = IntelligenceBus::new();

        bus.report_tech_stack(vec![
            "Python".to_string(),
            "PostgreSQL".to_string(),
            "Redis".to_string(),
        ])
        .await;

        let accumulated = bus.get_accumulated().await;
        assert!(accumulated.has_technology("python"));
        assert!(accumulated.has_technology("redis"));
        assert!(!accumulated.has_technology("mysql"));
    }

    #[tokio::test]
    async fn test_scanner_insight() {
        let bus = IntelligenceBus::new();

        bus.report_insight(
            "auth_bypass_scanner",
            InsightType::BypassFound,
            "Role parameter can be manipulated",
        )
        .await;

        let accumulated = bus.get_accumulated().await;
        let insights = accumulated.insights_from("auth_bypass_scanner");
        assert_eq!(insights.len(), 1);
        assert_eq!(*insights[0].0, InsightType::BypassFound);
    }

    #[tokio::test]
    async fn test_multiple_subscribers() {
        let bus = Arc::new(IntelligenceBus::new());
        let mut rx1 = bus.subscribe();
        let mut rx2 = bus.subscribe();

        assert_eq!(bus.subscriber_count(), 2);

        bus.report_framework("Express", Some("4.18"), 0.85).await;

        let event1 = timeout(Duration::from_millis(100), rx1.recv())
            .await
            .expect("Timeout")
            .expect("Failed to receive");
        let event2 = timeout(Duration::from_millis(100), rx2.recv())
            .await
            .expect("Timeout")
            .expect("Failed to receive");

        // Both should receive the same event
        match (&event1, &event2) {
            (
                IntelligenceEvent::FrameworkDetected { name: n1, .. },
                IntelligenceEvent::FrameworkDetected { name: n2, .. },
            ) => {
                assert_eq!(n1, "Express");
                assert_eq!(n2, "Express");
            }
            _ => panic!("Unexpected event types"),
        }
    }

    #[tokio::test]
    async fn test_clear_accumulated() {
        let bus = IntelligenceBus::new();

        bus.report_auth_type(AuthType::Session, 0.8, "https://example.com")
            .await;

        let accumulated = bus.get_accumulated().await;
        assert_eq!(accumulated.auth_types.len(), 1);

        bus.clear().await;

        let accumulated = bus.get_accumulated().await;
        assert_eq!(accumulated.auth_types.len(), 0);
        assert_eq!(bus.event_count(), 0);
    }

    #[tokio::test]
    async fn test_confidence_clamping() {
        let bus = IntelligenceBus::new();

        // Test that confidence is clamped to [0, 1]
        bus.report_auth_type(AuthType::JWT, 1.5, "https://example.com")
            .await;
        bus.report_framework("Rails", None, -0.5).await;

        let accumulated = bus.get_accumulated().await;
        assert!((accumulated.auth_types[0].1 - 1.0).abs() < f32::EPSILON);
        assert!(accumulated.frameworks[0].2.abs() < f32::EPSILON);
    }

    #[tokio::test]
    async fn test_no_duplicate_frameworks() {
        let bus = IntelligenceBus::new();

        bus.report_framework("Django", Some("4.2"), 0.9).await;
        bus.report_framework("django", Some("4.2"), 0.85).await; // Same framework, different case
        bus.report_framework("DJANGO", Some("4.3"), 0.95).await; // Same framework, different case

        let accumulated = bus.get_accumulated().await;
        assert_eq!(accumulated.frameworks.len(), 1); // Should only have one entry
    }

    #[tokio::test]
    async fn test_waf_bypass_hints_merge() {
        let bus = IntelligenceBus::new();

        bus.report_waf("ModSecurity", vec!["Hint 1".to_string()])
            .await;
        bus.report_waf(
            "ModSecurity",
            vec!["Hint 2".to_string(), "Hint 3".to_string()],
        )
        .await;

        let accumulated = bus.get_accumulated().await;
        let hints = accumulated.waf_bypass_hints();
        assert_eq!(hints.len(), 3);
        assert!(hints.contains(&"Hint 1".to_string()));
        assert!(hints.contains(&"Hint 2".to_string()));
        assert!(hints.contains(&"Hint 3".to_string()));
    }

    #[tokio::test]
    async fn test_primary_auth_type() {
        let bus = IntelligenceBus::new();

        bus.report_auth_type(AuthType::Session, 0.6, "https://example.com/login")
            .await;
        bus.report_auth_type(AuthType::JWT, 0.95, "https://example.com/api")
            .await;
        bus.report_auth_type(AuthType::ApiKey, 0.3, "https://example.com/public")
            .await;

        let accumulated = bus.get_accumulated().await;
        let primary = accumulated.primary_auth_type();
        assert_eq!(primary, Some(&AuthType::JWT));
    }

    #[tokio::test]
    async fn test_event_display() {
        let event = IntelligenceEvent::AuthTypeDetected {
            auth_type: AuthType::JWT,
            confidence: 0.95,
            source_url: "https://api.example.com".to_string(),
        };
        let display = format!("{}", event);
        assert!(display.contains("JWT"));
        assert!(display.contains("95%"));
    }

    #[tokio::test]
    async fn test_collector() {
        let bus = Arc::new(IntelligenceBus::new());
        let collector = IntelligenceCollector::new(bus.clone());
        let handle = collector.start_collecting();

        // Give collector time to start
        tokio::time::sleep(Duration::from_millis(10)).await;

        bus.report_auth_type(AuthType::OAuth2, 0.8, "https://oauth.example.com")
            .await;
        bus.report_framework("FastAPI", Some("0.100"), 0.9).await;

        // Give events time to propagate
        tokio::time::sleep(Duration::from_millis(50)).await;

        let events = collector.get_events().await;
        assert_eq!(events.len(), 2);

        handle.abort();
    }

    #[tokio::test]
    async fn test_event_count() {
        let bus = IntelligenceBus::new();

        bus.report_auth_type(AuthType::Basic, 0.5, "https://example.com")
            .await;
        bus.report_framework("Flask", None, 0.7).await;
        bus.report_tech_stack(vec!["Python".to_string()]).await;

        assert_eq!(bus.event_count(), 3);
    }

    #[tokio::test]
    async fn test_custom_event() {
        let bus = IntelligenceBus::new();
        let mut rx = bus.subscribe();

        bus.report_custom("rate_limit_info", "1000 requests per minute")
            .await;

        let event = timeout(Duration::from_millis(100), rx.recv())
            .await
            .expect("Timeout")
            .expect("Failed to receive");

        match event {
            IntelligenceEvent::Custom { event_type, data } => {
                assert_eq!(event_type, "rate_limit_info");
                assert_eq!(data, "1000 requests per minute");
            }
            _ => panic!("Unexpected event type"),
        }
    }

    #[test]
    fn test_auth_type_display() {
        assert_eq!(format!("{}", AuthType::JWT), "JWT");
        assert_eq!(format!("{}", AuthType::OAuth2), "OAuth2");
        assert_eq!(
            format!("{}", AuthType::Custom("HMAC".to_string())),
            "Custom(HMAC)"
        );
    }

    #[test]
    fn test_parameter_type_display() {
        assert_eq!(format!("{}", ParameterType::Id), "ID");
        assert_eq!(format!("{}", ParameterType::Command), "Command");
    }

    #[test]
    fn test_pattern_type_display() {
        assert_eq!(format!("{}", PatternType::SqlError), "SQL Error");
        assert_eq!(format!("{}", PatternType::StackTrace), "Stack Trace");
    }

    #[test]
    fn test_endpoint_pattern_type_display() {
        assert_eq!(format!("{}", EndpointPatternType::RestCrud), "REST CRUD");
        assert_eq!(format!("{}", EndpointPatternType::GraphQL), "GraphQL");
    }

    #[test]
    fn test_insight_type_display() {
        assert_eq!(format!("{}", InsightType::BypassFound), "Bypass Found");
        assert_eq!(
            format!("{}", InsightType::WeakValidation),
            "Weak Validation"
        );
    }
}