wafrift-detect 0.2.10

WAF detection from response headers and body, response fingerprint drift analysis.
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
//! Runtime-loaded WAF detection rules from `rules/detect/*.toml`.
//!
//! # Performance architecture
//!
//! All body-regex patterns from all 160+ WAFs are compiled into a single
//! [`regex::RegexSet`].  When a response arrives, the body is scanned
//! **once** against the entire set — O(n) in body length regardless of
//! pattern count.  The set returns which pattern indices matched, and
//! we map those back to their owning WAF rules to accumulate scores.
//!
//! Header and cookie patterns remain per-signature `Regex` objects
//! because the scan input is small (a few header values) and pattern
//! count per-header is low.
//!
//! # Signature provenance
//!
//! The catalog under `rules/detect/*.toml` is derived from the
//! [wafw00f](https://github.com/EnableSecurity/wafw00f) project
//! (BSD-3-Clause) plus selective contributions from
//! [identYwaf](https://github.com/stamparm/identYwaf) (MIT) and
//! locally researched additions. Every rule carries a `source`
//! field (`WAFW00F:<plugin>`, `IDENTYWAF:<probe>`, or
//! `wafrift:<context>`) that points back at the originating
//! plugin/probe so signature provenance is auditable.

use once_cell::sync::Lazy;
use regex::{Regex, RegexSet};
use serde::Deserialize;
use std::collections::HashMap;
use std::sync::RwLock;

/// Maximum length of an individual regex pattern (bytes). Patterns
/// exceeding this are skipped to mitigate ReDoS and pathological
/// compilation times from malicious or corrupted rule files.
const MAX_REGEX_PATTERN_LEN: usize = 4096;

/// Maximum number of body-regex patterns compiled into the global
/// `RegexSet`. Excess patterns are dropped with a warning.
const MAX_BODY_REGEX_PATTERNS: usize = 2000;

/// Minimum confidence required for detections based only on body text.
///
/// Body-only matches are easier to spoof with generic wording (for example
/// benign 404 pages containing "forbidden"), so require stronger evidence.
const BODY_ONLY_MIN_CONFIDENCE: f64 = 0.5;

/// Global in-memory rule database.
static RULE_DB: Lazy<RwLock<RuleEngine>> = Lazy::new(|| {
    let engine = RuleEngine::load_embedded().unwrap_or_else(|e| {
        tracing::warn!("Failed to load embedded WAF rules: {e}");
        RuleEngine::default()
    });
    RwLock::new(engine)
});

/// A loaded and compiled WAF rule engine.
///
/// Contains both per-rule compiled signatures (for headers/cookies/status)
/// and a global `RegexSet` that batches all body patterns for O(n) scanning.
#[derive(Debug, Default, Clone)]
pub struct RuleEngine {
    /// All compiled WAF rules, keyed by normalized name.
    pub rules: HashMap<String, CompiledWafRule>,
    /// Ordered list of rule names for deterministic iteration.
    pub names: Vec<String>,

    /// All body-regex patterns compiled into a single `RegexSet`.
    /// Each pattern index maps to an entry in `body_pattern_map`.
    body_regex_set: Option<RegexSet>,

    /// Maps each `RegexSet` pattern index → `(waf_name, signature_index, weight)`.
    ///
    /// When the `RegexSet` reports pattern `i` matched, we look up
    /// `body_pattern_map[i]` to find which WAF rule and signature
    /// produced the hit.
    body_pattern_map: Vec<BodyPatternRef>,

    /// Individual body regexes (same order as `body_pattern_map`) used
    /// to extract match snippets for indicator messages.  The `RegexSet`
    /// tells us *which* patterns matched; these tell us *where*.
    body_regexes: Vec<Regex>,
}

/// Reference from a body pattern index back to its owning WAF rule.
#[derive(Debug, Clone)]
struct BodyPatternRef {
    /// WAF rule name (key into `RuleEngine::rules`).
    waf_name: String,
    /// Index of the signature within the WAF rule.
    #[allow(dead_code)]
    sig_index: usize,
    /// Weight of this signature.
    weight: f64,
}

/// A WAF rule with compiled regex patterns.
#[derive(Debug, Clone)]
pub struct CompiledWafRule {
    pub name: String,
    #[allow(dead_code)]
    pub vendor: String,
    pub confidence_threshold: f64,
    pub evasions: Vec<String>,
    #[allow(dead_code)]
    pub source: String,
    pub signatures: Vec<CompiledSignature>,
}

/// A compiled signature ready for matching.
///
/// `body_regex` is `None` after engine finalization — body matching is
/// delegated to the global `RegexSet`.  The field is kept for the
/// compilation phase only.
#[derive(Debug, Clone)]
pub struct CompiledSignature {
    pub header_name: Option<String>,
    pub header_regex: Option<Regex>,
    pub cookie_regex: Option<Regex>,
    /// Kept for backward compatibility but body matching uses the
    /// engine-level `RegexSet` + `body_regexes` instead.
    pub body_regex: Option<Regex>,
    pub status_code: Option<u16>,
    pub weight: f64,
}

/// Raw TOML rule database structure.
#[derive(Debug, Clone, Deserialize)]
struct RawRuleDb {
    #[serde(default)]
    waf: Vec<RawWafRule>,
}

/// Raw TOML WAF rule.
#[derive(Debug, Clone, Deserialize)]
struct RawWafRule {
    name: String,
    vendor: String,
    #[serde(default = "default_threshold")]
    confidence_threshold: f64,
    #[serde(default)]
    evasions: Vec<String>,
    #[serde(default)]
    source: String,
    #[serde(default)]
    signature: Vec<RawSignature>,
}

/// Raw TOML signature.
#[derive(Debug, Clone, Deserialize)]
struct RawSignature {
    header_name: Option<String>,
    header_regex: Option<String>,
    cookie_regex: Option<String>,
    body_regex: Option<String>,
    status_code: Option<u16>,
    #[serde(default = "default_weight")]
    weight: f64,
}

fn default_threshold() -> f64 {
    0.3
}

fn default_weight() -> f64 {
    0.4
}

/// Compile-time embedded detection rules, generated by `build.rs`.
///
/// This is the concatenation of all `rules/detect/*.toml` files,
/// baked into the binary so `cargo install wafrift` produces a
/// standalone executable with no runtime filesystem dependency.
const EMBEDDED_RULES_TOML: &str =
    include_str!(concat!(env!("OUT_DIR"), "/embedded_detect_rules.toml"));

impl RuleEngine {
    /// Load WAF detection rules.
    ///
    /// **Loading order** (first success wins):
    ///
    /// 1. **Compile-time embedded** — `build.rs` concatenates all
    ///    `rules/detect/*.toml` into the binary.  This is the
    ///    production path for `cargo install` users.
    /// 2. **Filesystem fallback** — walks `rules/detect/` at relative
    ///    paths.  Used during development when you want hot-reload
    ///    via [`reload`].
    pub fn load_embedded() -> Result<Self, DetectRulesError> {
        let mut engine = RuleEngine {
            rules: HashMap::new(),
            names: Vec::new(),
            body_regex_set: None,
            body_pattern_map: Vec::new(),
            body_regexes: Vec::new(),
        };

        // Tier 1: Try compile-time embedded rules.
        let embedded_ok =
            engine.load_from_str(EMBEDDED_RULES_TOML).is_ok() && !engine.rules.is_empty();

        // Tier 2: Filesystem fallback (development, or if embedded is empty).
        if !embedded_ok {
            let candidates = [
                std::path::PathBuf::from("rules/detect"),
                std::path::PathBuf::from("../rules/detect"),
                std::path::PathBuf::from("../../rules/detect"),
            ];

            let mut loaded = false;
            for dir in &candidates {
                if dir.is_dir() {
                    engine.load_directory(dir)?;
                    loaded = true;
                    break;
                }
            }

            if !loaded {
                return Err(DetectRulesError::Io(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "rules/detect directory not found and no embedded rules available",
                )));
            }
        }

        // Finalize: compile the global body RegexSet.
        engine.compile_body_regex_set()?;

        Ok(engine)
    }

    /// Parse a TOML string containing `[[waf]]` entries.
    ///
    /// Used by both the compile-time embedded path and hot-reload.
    pub fn load_from_str(&mut self, toml_content: &str) -> Result<(), DetectRulesError> {
        let raw: RawRuleDb = toml::from_str(toml_content)
            .map_err(|e| DetectRulesError::Parse(format!("embedded rules: {e}")))?;
        for waf in raw.waf {
            let compiled = Self::compile_waf(waf)
                .map_err(|e| DetectRulesError::Parse(format!("embedded rules: {e}")))?;
            let key = compiled.name.clone();
            if !self.rules.contains_key(&key) {
                self.names.push(key.clone());
            }
            self.rules.insert(key, compiled);
        }
        Ok(())
    }

    /// Load all `.toml` files from a directory.
    pub fn load_directory(&mut self, path: &std::path::Path) -> Result<(), DetectRulesError> {
        let mut entries: Vec<_> = std::fs::read_dir(path)?
            .filter_map(|e| e.ok())
            .filter(|e| {
                e.path()
                    .extension()
                    .map(|ext| ext.eq_ignore_ascii_case("toml"))
                    .unwrap_or(false)
            })
            .map(|e| e.path())
            .collect();
        entries.sort();

        for entry in entries {
            let content = std::fs::read_to_string(&entry)?;
            let raw: RawRuleDb = toml::from_str(&content)
                .map_err(|e| DetectRulesError::Parse(format!("{}: {e}", entry.display())))?;
            for waf in raw.waf {
                let compiled = Self::compile_waf(waf)
                    .map_err(|e| DetectRulesError::Parse(format!("{}: {e}", entry.display())))?;
                let key = compiled.name.clone();
                if !self.rules.contains_key(&key) {
                    self.names.push(key.clone());
                }
                self.rules.insert(key, compiled);
            }
        }
        Ok(())
    }

    fn compile_waf(raw: RawWafRule) -> Result<CompiledWafRule, String> {
        let mut signatures = Vec::with_capacity(raw.signature.len());
        for sig in raw.signature {
            let header_regex = sig
                .header_regex
                .as_ref()
                .filter(|p| {
                    if p.len() > MAX_REGEX_PATTERN_LEN {
                        tracing::warn!(
                            waf = %raw.name,
                            pattern_len = p.len(),
                            max = MAX_REGEX_PATTERN_LEN,
                            "skipping oversized header regex"
                        );
                        false
                    } else {
                        true
                    }
                })
                .map(|p| Regex::new(p).map_err(|e| format!("bad header regex '{p}': {e}")))
                .transpose()?;
            let cookie_regex = sig
                .cookie_regex
                .as_ref()
                .filter(|p| {
                    if p.len() > MAX_REGEX_PATTERN_LEN {
                        tracing::warn!(
                            waf = %raw.name,
                            pattern_len = p.len(),
                            max = MAX_REGEX_PATTERN_LEN,
                            "skipping oversized cookie regex"
                        );
                        false
                    } else {
                        true
                    }
                })
                .map(|p| Regex::new(p).map_err(|e| format!("bad cookie regex '{p}': {e}")))
                .transpose()?;
            let body_regex = sig
                .body_regex
                .as_ref()
                .filter(|p| {
                    if p.len() > MAX_REGEX_PATTERN_LEN {
                        tracing::warn!(
                            waf = %raw.name,
                            pattern_len = p.len(),
                            max = MAX_REGEX_PATTERN_LEN,
                            "skipping oversized body regex"
                        );
                        false
                    } else {
                        true
                    }
                })
                .map(|p| Regex::new(p).map_err(|e| format!("bad body regex '{p}': {e}")))
                .transpose()?;
            signatures.push(CompiledSignature {
                header_name: sig.header_name.map(|s| s.to_ascii_lowercase()),
                header_regex,
                cookie_regex,
                body_regex,
                status_code: sig.status_code,
                weight: sig.weight,
            });
        }
        Ok(CompiledWafRule {
            name: raw.name,
            vendor: raw.vendor,
            confidence_threshold: raw.confidence_threshold,
            evasions: raw.evasions,
            source: raw.source,
            signatures,
        })
    }

    /// Compile all body-regex patterns across all rules into a single
    /// `RegexSet` for batch scanning.
    ///
    /// Must be called after all rules are loaded.  Populates
    /// `body_regex_set`, `body_pattern_map`, and `body_regexes`.
    pub fn compile_body_regex_set(&mut self) -> Result<(), DetectRulesError> {
        let mut patterns: Vec<String> = Vec::new();
        let mut map: Vec<BodyPatternRef> = Vec::new();
        let mut regexes: Vec<Regex> = Vec::new();

        for name in &self.names {
            let rule = &self.rules[name];
            for (sig_idx, sig) in rule.signatures.iter().enumerate() {
                if let Some(ref re) = sig.body_regex {
                    if patterns.len() >= MAX_BODY_REGEX_PATTERNS {
                        tracing::warn!(
                            limit = MAX_BODY_REGEX_PATTERNS,
                            "truncating body regex set; some WAF signatures will not match on body text"
                        );
                        break;
                    }
                    patterns.push(re.as_str().to_string());
                    map.push(BodyPatternRef {
                        waf_name: name.clone(),
                        sig_index: sig_idx,
                        weight: sig.weight,
                    });
                    regexes.push(re.clone());
                }
            }
            if patterns.len() >= MAX_BODY_REGEX_PATTERNS {
                break;
            }
        }

        if !patterns.is_empty() {
            let set = RegexSet::new(&patterns).map_err(|e| {
                DetectRulesError::Parse(format!("failed to compile body RegexSet: {e}"))
            })?;
            self.body_regex_set = Some(set);
        }

        self.body_pattern_map = map;
        self.body_regexes = regexes;
        Ok(())
    }

    /// Run detection against all rules and return scored matches.
    ///
    /// Body scanning is performed once via the compiled `RegexSet`,
    /// then header/cookie/status checks run per-rule only for WAFs
    /// that have non-body signatures.
    pub fn detect(
        &self,
        status: u16,
        headers: &[(String, String)],
        body: &str,
    ) -> Vec<DetectedWaf> {
        // ── Phase 1: Batch body scan ──
        //
        // Single-pass scan of the body against ALL body patterns.
        // Returns the set of pattern indices that matched.
        let body_hits: Vec<usize> = self
            .body_regex_set
            .as_ref()
            .map(|set| set.matches(body).into_iter().collect())
            .unwrap_or_default();

        // Accumulate body-hit scores per WAF.
        let mut waf_scores: HashMap<&str, (f64, Vec<String>)> = HashMap::new();

        for &pattern_idx in &body_hits {
            let pref = &self.body_pattern_map[pattern_idx];
            let entry = waf_scores
                .entry(&pref.waf_name)
                .or_insert_with(|| (0.0, Vec::new()));
            entry.0 += pref.weight;

            // Extract match snippet for the indicator message.
            if let Some(m) = self.body_regexes[pattern_idx].find(body) {
                let snippet = &body[m.start()..m.end().min(m.start() + 40)];
                entry.1.push(format!("body: {snippet}"));
            }
        }

        // ── Phase 2: Per-rule header/cookie/status scoring ──
        //
        // Only iterate signatures that have non-body matchers.
        for name in &self.names {
            let rule = &self.rules[name];
            for sig in &rule.signatures {
                // Skip body-only signatures — already handled by RegexSet.
                if sig.header_regex.is_none()
                    && sig.cookie_regex.is_none()
                    && sig.status_code.is_none()
                {
                    continue;
                }

                let mut matched = false;
                let entry = waf_scores.entry(name).or_insert_with(|| (0.0, Vec::new()));

                if let Some(expected) = sig.status_code
                    && status == expected
                {
                    matched = true;
                    entry.1.push(format!("status: {status}"));
                }

                if let Some(ref re) = sig.header_regex {
                    let hname = sig.header_name.as_deref().unwrap_or("");
                    for (k, v) in headers {
                        if (hname.is_empty() || k.eq_ignore_ascii_case(hname))
                            && let Some(m) = re.find(v)
                        {
                            matched = true;
                            entry.1.push(format!(
                                "header {k}: {}",
                                &v[m.start()..m.end().min(m.start() + 40)]
                            ));
                            break;
                        }
                    }
                }

                if let Some(ref re) = sig.cookie_regex {
                    for (k, v) in headers {
                        if k.eq_ignore_ascii_case("set-cookie") && re.is_match(v) {
                            matched = true;
                            entry.1.push(format!("cookie: {k}"));
                            break;
                        }
                    }
                }

                if matched {
                    entry.0 += sig.weight;
                }
            }
        }

        // ── Phase 3: Filter and sort ──
        let mut results: Vec<DetectedWaf> = waf_scores
            .into_iter()
            .filter_map(|(name, (score, indicators))| {
                let rule = &self.rules[name];
                let has_non_body_indicator = indicators
                    .iter()
                    .any(|indicator| !indicator.starts_with("body: "));
                let effective_threshold = if has_non_body_indicator {
                    rule.confidence_threshold
                } else {
                    rule.confidence_threshold.max(BODY_ONLY_MIN_CONFIDENCE)
                };
                if score >= effective_threshold {
                    Some(DetectedWaf {
                        name: name.to_string(),
                        confidence: score.min(1.0),
                        indicators,
                    })
                } else {
                    None
                }
            })
            .collect();

        results.sort_by(|a, b| {
            b.confidence
                .partial_cmp(&a.confidence)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then_with(|| a.name.cmp(&b.name))
        });
        results
    }

    /// Lookup evasion techniques for a detected WAF name.
    #[must_use]
    #[allow(dead_code)]
    pub fn evasions_for(&self, name: &str) -> Vec<&str> {
        self.rules
            .get(name)
            .map(|r| r.evasions.iter().map(String::as_str).collect())
            .unwrap_or_default()
    }

    /// Number of loaded rules.
    #[must_use]
    #[allow(dead_code)]
    pub fn len(&self) -> usize {
        self.rules.len()
    }

    #[must_use]
    #[allow(dead_code)]
    pub fn is_empty(&self) -> bool {
        self.rules.is_empty()
    }
}

/// Result of WAF detection.
#[derive(Debug, Clone)]
pub struct DetectedWaf {
    pub name: String,
    pub confidence: f64,
    pub indicators: Vec<String>,
}

/// Errors that can occur while loading rules.
#[derive(Debug, thiserror::Error)]
pub enum DetectRulesError {
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    #[error("parse error: {0}")]
    Parse(String),
}

/// Access the global rule engine (read lock).
pub fn with_engine<F, R>(f: F) -> R
where
    F: FnOnce(&RuleEngine) -> R,
{
    let guard = RULE_DB.read().unwrap_or_else(|e| e.into_inner());
    f(&guard)
}

/// Reload the global rule engine from disk.
pub fn reload() -> Result<(), DetectRulesError> {
    let new_engine = RuleEngine::load_embedded()?;
    let mut guard = RULE_DB
        .write()
        .map_err(|e| DetectRulesError::Parse(format!("RULE_DB poisoned: {e}")))?;
    *guard = new_engine;
    Ok(())
}

/// Detect WAFs using the global rule engine.
#[must_use]
pub fn detect(status: u16, headers: &[(String, String)], body: &str) -> Vec<DetectedWaf> {
    with_engine(|engine| engine.detect(status, headers, body))
}

/// Returns the names of all supported WAF detectors.
#[must_use]
pub fn supported_wafs() -> Vec<String> {
    with_engine(|engine| engine.names.clone())
}

/// Suggest evasions for a WAF name using the global rule engine.
///
/// Returns owned `String`s so callers can keep them past the engine's
/// `RwLock` guard. The previous version returned `&'static str` via
/// `Box::leak` on every call — at sustained proxy traffic that leaked
/// ~100 KB/sec (4 strings × ~25 chars × 1000 req/s) and ~360 MB/hour.
/// The leaked-string optimisation was wrong: `suggest_evasion` runs in
/// the per-response hot path, not once at startup.
#[must_use]
pub fn suggest_evasion(waf_name: &str) -> Vec<String> {
    with_engine(|engine| {
        engine
            .rules
            .get(waf_name)
            .map(|r| r.evasions.clone())
            .unwrap_or_else(|| {
                vec![
                    "CaseAlternation".into(),
                    "SqlCommentInsertion".into(),
                    "DoubleUrlEncode".into(),
                    "ContentTypeSwitch".into(),
                ]
            })
    })
}

/// Configuration for ambiguity reporting.
#[derive(Debug, Clone, Copy)]
pub struct DetectConfig {
    /// Minimum confidence for a WAF to be reported.
    pub threshold: f64,
    /// If top-2 confidence delta is smaller than this, report both.
    pub ambiguity_delta: f64,
}

impl Default for DetectConfig {
    fn default() -> Self {
        Self {
            threshold: 0.3,
            ambiguity_delta: 0.15,
        }
    }
}

/// Detect with ambiguity filtering.
#[must_use]
pub fn detect_with_config(
    status: u16,
    headers: &[(String, String)],
    body: &str,
    config: DetectConfig,
) -> Vec<DetectedWaf> {
    let mut results = detect(status, headers, body);
    results.retain(|r| r.confidence >= config.threshold);

    if results.len() >= 2 {
        let delta = results[0].confidence - results[1].confidence;
        if delta < config.ambiguity_delta {
            // Keep top N until delta exceeds threshold
            let mut keep = 2;
            for window in results.windows(2) {
                if window[0].confidence - window[1].confidence < config.ambiguity_delta {
                    keep += 1;
                } else {
                    break;
                }
            }
            results.truncate(keep);
        } else {
            results.truncate(1);
        }
    }
    results
}

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

    const TEST_TOML: &str = r#"
[[waf]]
name = "TestWAF"
vendor = "test"
confidence_threshold = 0.3
evasions = ["CaseAlternation", "SqlCommentInsertion"]

[[waf.signature]]
header_name = "x-test-waf"
header_regex = "active"
weight = 0.9

[[waf.signature]]
body_regex = "blocked by test"
weight = 0.95

[[waf.signature]]
status_code = 403
weight = 0.5

[[waf]]
name = "AnotherWAF"
vendor = "another"
confidence_threshold = 0.5
evasions = ["DoubleUrlEncode"]

[[waf.signature]]
body_regex = "another waf"
weight = 0.6
"#;

    fn test_engine() -> RuleEngine {
        let mut engine = RuleEngine::default();
        engine.load_from_str(TEST_TOML).expect("load test toml");
        engine.compile_body_regex_set().expect("compile regex set");
        engine
    }

    #[test]
    fn load_from_str_populates_rules() {
        let engine = test_engine();
        assert_eq!(engine.len(), 2);
        assert!(!engine.is_empty());
    }

    #[test]
    fn detect_by_header() {
        let engine = test_engine();
        let headers = vec![("x-test-waf".into(), "active".into())];
        let results = engine.detect(200, &headers, "OK");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "TestWAF");
        assert!(results[0].confidence >= 0.9);
    }

    #[test]
    fn detect_by_body() {
        let engine = test_engine();
        let headers: Vec<(String, String)> = vec![];
        let results = engine.detect(200, &headers, "you are blocked by test engine");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "TestWAF");
        assert!(results[0].confidence >= 0.95);
    }

    #[test]
    fn detect_by_status() {
        let engine = test_engine();
        let headers: Vec<(String, String)> = vec![];
        let results = engine.detect(403, &headers, "");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "TestWAF");
    }

    #[test]
    fn detect_no_match() {
        let engine = test_engine();
        let headers = vec![("server".into(), "nginx".into())];
        let results = engine.detect(200, &headers, "Welcome");
        assert!(results.is_empty());
    }

    #[test]
    fn detect_confidence_threshold_filters_body_only() {
        let engine = test_engine();
        // AnotherWAF needs 0.5 threshold, body regex gives 0.6
        let results = engine.detect(200, &[], "another waf detected");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "AnotherWAF");
    }

    #[test]
    fn evasions_for_known_waf() {
        let engine = test_engine();
        let evasions = engine.evasions_for("TestWAF");
        assert_eq!(evasions.len(), 2);
        assert!(evasions.contains(&"CaseAlternation"));
    }

    #[test]
    fn evasions_for_unknown_waf_empty() {
        let engine = test_engine();
        assert!(engine.evasions_for("Unknown").is_empty());
    }

    #[test]
    fn detect_body_only_needs_higher_threshold() {
        let mut engine = RuleEngine::default();
        engine
            .load_from_str(
                r#"
[[waf]]
name = "LowConfWAF"
vendor = "test"
confidence_threshold = 0.1

[[waf.signature]]
body_regex = "blocked"
weight = 0.4
"#,
            )
            .expect("load");
        engine.compile_body_regex_set().expect("compile");

        // body-only match with weight 0.4 < BODY_ONLY_MIN_CONFIDENCE (0.5)
        let results = engine.detect(200, &[], "blocked");
        assert!(results.is_empty());
    }

    #[test]
    fn empty_engine_returns_empty() {
        let engine = RuleEngine::default();
        assert!(engine.is_empty());
        assert_eq!(engine.len(), 0);
        let results = engine.detect(200, &[], "body");
        assert!(results.is_empty());
    }

    #[test]
    fn detect_sorts_by_confidence_desc() {
        let engine = test_engine();
        // TestWAF matches header (0.9) + body (0.95) = 1.85
        // AnotherWAF matches body (0.6)
        let headers = vec![("x-test-waf".into(), "active".into())];
        let results = engine.detect(200, &headers, "blocked by test and another waf");
        assert!(!results.is_empty());
        assert_eq!(results[0].name, "TestWAF");
    }
}