Skip to main content

rsigma_eval/engine/
mod.rs

1//! Rule evaluation engine with logsource routing.
2//!
3//! The `Engine` manages a set of compiled Sigma rules and evaluates events
4//! against them. It supports optional logsource-based pre-filtering to
5//! reduce the number of rules evaluated per event.
6
7pub(crate) mod bloom_index;
8#[cfg(feature = "daachorse-index")]
9pub(crate) mod cross_rule_ac;
10#[cfg(test)]
11mod diff_tests;
12mod filters;
13#[cfg(test)]
14mod tests;
15
16use std::sync::atomic::{AtomicU64, Ordering};
17
18use rsigma_parser::{
19    ConditionExpr, FilterRule, FilterRuleTarget, LogSource, SigmaCollection, SigmaRule,
20};
21
22use rsigma_ir::{IrRule, LowerOptions, lower_rule};
23
24use crate::candidate_index::CandidateIndex;
25use crate::compiler::{
26    CompiledRule, compile_detection, compile_to_compiled, evaluate_rule_with_bloom,
27};
28use crate::error::{EvalError, Result};
29use crate::event::Event;
30use crate::logsource::{ExtractLogSource, LogSourceExtractor};
31use crate::pipeline::{Pipeline, TransformedRule, apply_pipelines, transform_collection};
32use crate::result::{EvaluationResult, MatchDetailLevel};
33use crate::rule_metadata::{RuleBundleMetadata, RuleMetadataLookup};
34
35use bloom_index::{BloomCache, BloomLookup, FieldBloomIndex};
36
37pub use filters::apply_filters;
38use filters::{
39    FilterTarget, filter_detection_key, filter_targets, logsource_compatible, logsource_matches,
40    namespaced_filter_condition, stable_references,
41};
42
43#[derive(Debug)]
44pub(crate) struct IdentifiedEvaluation {
45    pub result: EvaluationResult,
46    pub rule_id: Option<String>,
47    pub rule_name: Option<String>,
48}
49
50/// The main rule evaluation engine.
51///
52/// Holds a set of compiled rules and provides methods to evaluate events
53/// against them. Supports optional logsource routing for performance.
54///
55/// The engine is generic over its logsource extractor `L`, which defaults to
56/// the field-reading [`LogSourceExtractor`]. Build an engine around a custom
57/// [`ExtractLogSource`] implementation with
58/// [`Engine::with_logsource_extractor`].
59///
60/// # Example
61///
62/// ```rust
63/// use rsigma_parser::parse_sigma_yaml;
64/// use rsigma_eval::{Engine, Event};
65/// use rsigma_eval::event::JsonEvent;
66/// use serde_json::json;
67///
68/// let yaml = r#"
69/// title: Detect Whoami
70/// logsource:
71///     product: windows
72///     category: process_creation
73/// detection:
74///     selection:
75///         CommandLine|contains: 'whoami'
76///     condition: selection
77/// level: medium
78/// "#;
79///
80/// let collection = parse_sigma_yaml(yaml).unwrap();
81/// let mut engine = Engine::new();
82/// engine.add_collection(&collection).unwrap();
83///
84/// let event_val = json!({"CommandLine": "cmd /c whoami"});
85/// let event = JsonEvent::borrow(&event_val);
86/// let matches = engine.evaluate(&event);
87/// assert_eq!(matches.len(), 1);
88/// assert_eq!(matches[0].header.rule_title, "Detect Whoami");
89/// ```
90pub struct Engine<L = LogSourceExtractor> {
91    rules: Vec<CompiledRule>,
92    /// Post-pipeline, pre-filter HIR for rules added via the parsed-rule paths,
93    /// retained so [`Engine::save_hir`] can serialize a restart cache. Empty
94    /// unless [`Engine::set_retain_hir`] enabled retention; rules added via
95    /// `add_compiled_rule` have no HIR and are not represented here.
96    ir_rules: Vec<IrRule>,
97    /// Whether the parsed-rule paths keep each rule's HIR in `ir_rules`.
98    retain_hir: bool,
99    /// Rules added via the parsed-rule paths while retention was off. A
100    /// non-zero count makes `save_hir` fail instead of writing a cache that
101    /// silently misses them.
102    unretained_hir: usize,
103    pipelines: Vec<Pipeline>,
104    /// Global override: include the full event JSON in all match results.
105    /// When `true`, overrides per-rule `rsigma.include_event` custom attributes.
106    include_event: bool,
107    /// Verbosity of the match detail recorded on detection results.
108    /// `Off` by default, which preserves the historical `{ field, value }`
109    /// wire shape. See [`Engine::set_match_detail`].
110    match_detail: MatchDetailLevel,
111    /// Monotonic counter used to namespace injected filter detections,
112    /// preventing key collisions when multiple filters share detection names.
113    filter_counter: usize,
114    /// Witness-based inverted index from event shape to candidate rule
115    /// indices. Rebuilt after every rule mutation (add, filter).
116    rule_index: CandidateIndex,
117    /// Per-field bloom filter over positive substring needles. Rebuilt
118    /// alongside `rule_index`. Consulted only when `bloom_prefilter` is
119    /// enabled.
120    bloom_index: FieldBloomIndex,
121    /// Toggle for bloom pre-filtering. Off by default: the per-event probe
122    /// overhead exceeds the savings on rule sets where most events overlap
123    /// with at least one needle's trigrams. Workloads with many substring
124    /// rules and mostly-non-matching events (e.g. high-volume telemetry
125    /// streams against an active threat-intel ruleset) opt in via
126    /// [`Engine::set_bloom_prefilter`].
127    bloom_prefilter: bool,
128    /// Memory budget the bloom builder is allowed to consume across all
129    /// per-field filters. `None` means use the crate default
130    /// (`bloom_index::DEFAULT_MAX_TOTAL_BYTES`, 1 MB).
131    bloom_max_bytes: Option<usize>,
132    /// Opt-in event-logsource extractor for conflict-based rule pruning.
133    /// `None` (default) leaves the hot path unchanged; when `Some`, the
134    /// engine extracts each event's logsource once and skips rules whose
135    /// logsource conflicts (see [`Engine::set_logsource_extractor`]).
136    logsource_extractor: Option<L>,
137    /// Monotonic count of rules skipped because their logsource conflicts
138    /// with the event's, whether pruned by the index's product partitioning
139    /// or by the residual check in the evaluation loop. Incremented only when
140    /// an extractor is set; surfaced via [`Engine::logsource_pruned_total`].
141    logsource_pruned: AtomicU64,
142    /// Monotonic count of `evaluate` calls where the extractor produced no
143    /// logsource at all (fail-open: every rule was evaluated). Surfaced via
144    /// [`Engine::logsource_absent_total`].
145    logsource_absent: AtomicU64,
146    /// Cross-rule Aho-Corasick index for substring patterns, gated on the
147    /// `daachorse-index` feature. Built only when [`cross_rule_ac_enabled`]
148    /// is `true`; [`cross_rule_ac_prunable`] is the conservative per-rule
149    /// flag computed at the same time so the `evaluate` hot path can drop
150    /// rules safely.
151    ///
152    /// [`cross_rule_ac_enabled`]: Self::cross_rule_ac_enabled
153    /// [`cross_rule_ac_prunable`]: Self::cross_rule_ac_prunable
154    #[cfg(feature = "daachorse-index")]
155    cross_rule_ac_index: cross_rule_ac::CrossRuleAcIndex,
156    /// Toggle for the cross-rule AC pre-filter. Off by default; the index
157    /// only pays off on rule sets > 5K rules with many shared substring
158    /// patterns. See [`Engine::set_cross_rule_ac`].
159    #[cfg(feature = "daachorse-index")]
160    cross_rule_ac_enabled: bool,
161    /// Per-rule conservative AC-prunability flag. `true` iff the rule's
162    /// firing requires at least one positive substring match (no `Exact`,
163    /// `Regex`, `Numeric`, `Not`, etc.), so dropping the rule on a
164    /// "no AC hit" verdict is provably correct.
165    #[cfg(feature = "daachorse-index")]
166    cross_rule_ac_prunable: Vec<bool>,
167}
168
169impl Engine {
170    /// Create a new empty engine.
171    pub fn new() -> Self {
172        Self::from_parts(Vec::new(), None)
173    }
174
175    /// Create a new engine with a pipeline.
176    pub fn new_with_pipeline(pipeline: Pipeline) -> Self {
177        Self::from_parts(vec![pipeline], None)
178    }
179}
180
181impl<L> Engine<L> {
182    /// Create a new empty engine that prunes with `extractor`.
183    ///
184    /// This is the constructor for a custom [`ExtractLogSource`]
185    /// implementation: it fixes the engine's extractor type to `L`. Add
186    /// pipelines and rules afterwards as with [`Engine::new`].
187    pub fn with_logsource_extractor(extractor: L) -> Self {
188        Self::from_parts(Vec::new(), Some(extractor))
189    }
190
191    fn from_parts(pipelines: Vec<Pipeline>, logsource_extractor: Option<L>) -> Self {
192        Engine {
193            rules: Vec::new(),
194            ir_rules: Vec::new(),
195            retain_hir: false,
196            unretained_hir: 0,
197            pipelines,
198            include_event: false,
199            match_detail: MatchDetailLevel::Off,
200            filter_counter: 0,
201            rule_index: CandidateIndex::empty(),
202            bloom_index: FieldBloomIndex::empty(),
203            bloom_prefilter: false,
204            bloom_max_bytes: None,
205            logsource_extractor,
206            logsource_pruned: AtomicU64::new(0),
207            logsource_absent: AtomicU64::new(0),
208            #[cfg(feature = "daachorse-index")]
209            cross_rule_ac_index: cross_rule_ac::CrossRuleAcIndex::empty(),
210            #[cfg(feature = "daachorse-index")]
211            cross_rule_ac_enabled: false,
212            #[cfg(feature = "daachorse-index")]
213            cross_rule_ac_prunable: Vec::new(),
214        }
215    }
216
217    /// Enable or disable bloom-filter pre-filtering of positive substring
218    /// detection items.
219    ///
220    /// When enabled, `evaluate*` short-circuits any positive substring
221    /// matcher (`Contains` / `StartsWith` / `EndsWith` / `AhoCorasickSet`,
222    /// alone or wrapped in `CaseInsensitiveGroup`) whose field cannot
223    /// possibly contain a needle trigram.
224    ///
225    /// Disabled by default. The per-event probe (trigram extraction +
226    /// double hashing) costs ~1 µs on a typical CommandLine field, which
227    /// outweighs the savings on rule sets where most events overlap with
228    /// at least one needle. Enable for workloads that pair many substring
229    /// rules with mostly-non-matching events; benchmark with
230    /// `eval_bloom_rejection` before flipping it on in production.
231    pub fn set_bloom_prefilter(&mut self, enabled: bool) {
232        self.bloom_prefilter = enabled;
233    }
234
235    /// Returns whether bloom pre-filtering is currently enabled.
236    pub fn bloom_prefilter_enabled(&self) -> bool {
237        self.bloom_prefilter
238    }
239
240    /// Set the memory budget for the per-field bloom index.
241    ///
242    /// Must be called **before** `add_collection` / `add_rule` for the new
243    /// budget to take effect on the existing rule set; otherwise it is
244    /// applied at the next index rebuild. The default budget is 1 MB,
245    /// shared across all per-field filters. Lower the cap on memory-
246    /// constrained deployments; raise it for large rule sets where the
247    /// default starts evicting useful filters.
248    pub fn set_bloom_max_bytes(&mut self, max_bytes: usize) {
249        self.bloom_max_bytes = Some(max_bytes);
250        if !self.rules.is_empty() {
251            self.rebuild_index();
252        }
253    }
254
255    /// Returns the configured bloom memory budget, if one has been set
256    /// explicitly. `None` means the crate default (1 MB) is in use.
257    pub fn bloom_max_bytes(&self) -> Option<usize> {
258        self.bloom_max_bytes
259    }
260
261    /// Enable or disable opt-in, conflict-based logsource pruning.
262    ///
263    /// When set to `Some`, `evaluate` extracts each event's logsource once via
264    /// the extractor and skips any candidate rule whose logsource
265    /// conflicts with the event's (a dimension set on both sides that
266    /// disagrees). A dimension unset on either side is a wildcard, so an event
267    /// tagged only `product: windows` skips `product: linux` rules while still
268    /// evaluating Windows-category and logsource-less rules.
269    ///
270    /// Disabled by default (`None`), leaving the hot path unchanged. Pruning
271    /// fails open: an event with no extractable logsource evaluates every
272    /// rule. The extractor is read on every `evaluate` call, so it can be
273    /// swapped at runtime (e.g. carried across a hot-reload).
274    pub fn set_logsource_extractor(&mut self, extractor: Option<L>) {
275        self.logsource_extractor = extractor;
276    }
277
278    /// Returns the configured logsource extractor, if any. `None` means
279    /// logsource pruning is disabled.
280    pub fn logsource_extractor(&self) -> Option<&L> {
281        self.logsource_extractor.as_ref()
282    }
283
284    /// Total rules skipped because their logsource conflicted with an event's,
285    /// since engine creation. Zero unless an extractor is set.
286    ///
287    /// Counts both sources of conflict pruning: always-evaluated rules the
288    /// candidate index never returns because their `product` bucket conflicts,
289    /// and candidate rules the residual `logsource_compatible` check drops in
290    /// the evaluation loop.
291    pub fn logsource_pruned_total(&self) -> u64 {
292        self.logsource_pruned.load(Ordering::Relaxed)
293    }
294
295    /// Total `evaluate` calls where the extractor produced no logsource and
296    /// pruning failed open (every rule evaluated). Zero unless an extractor
297    /// is set.
298    pub fn logsource_absent_total(&self) -> u64 {
299        self.logsource_absent.load(Ordering::Relaxed)
300    }
301
302    /// Static view of how many loaded rules are eligible (logsource-compatible)
303    /// versus pruned (conflicting) for `event_logsource`, returned as
304    /// `(eligible, pruned)`. Used to report how much of a ruleset a given
305    /// logsource (for example a schema's implied logsource) actually evaluates,
306    /// independent of any specific event's field values.
307    pub fn logsource_eligibility(&self, event_logsource: &LogSource) -> (usize, usize) {
308        let mut eligible = 0;
309        let mut pruned = 0;
310        for rule in &self.rules {
311            if logsource_compatible(&rule.logsource, event_logsource) {
312                eligible += 1;
313            } else {
314                pruned += 1;
315            }
316        }
317        (eligible, pruned)
318    }
319
320    /// Enable or disable the cross-rule Aho-Corasick pre-filter.
321    ///
322    /// When enabled, the engine builds a single per-field
323    /// `DoubleArrayAhoCorasick` automaton over every positive substring
324    /// needle from every rule and drops AC-prunable rules from the
325    /// candidate set when none of their patterns hit the event.
326    ///
327    /// Off by default. Pays off on large rule sets (> ~5K rules) with many
328    /// shared substring patterns (threat-intel feeds, IOC packs). For
329    /// smaller rule sets the per-rule [`AhoCorasickSet`] matcher already
330    /// handles the workload optimally; the cross-rule index only adds
331    /// build-time and lookup overhead. Benchmark with `eval_cross_rule_ac`
332    /// against representative rule sets before enabling in production.
333    ///
334    /// Available behind the `daachorse-index` Cargo feature.
335    ///
336    /// [`AhoCorasickSet`]: crate::matcher::CompiledMatcher::AhoCorasickSet
337    #[cfg(feature = "daachorse-index")]
338    pub fn set_cross_rule_ac(&mut self, enabled: bool) {
339        self.cross_rule_ac_enabled = enabled;
340        if enabled && !self.rules.is_empty() {
341            self.rebuild_index();
342        }
343    }
344
345    /// Returns whether the cross-rule AC pre-filter is currently enabled.
346    /// Available behind the `daachorse-index` Cargo feature.
347    #[cfg(feature = "daachorse-index")]
348    pub fn cross_rule_ac_enabled(&self) -> bool {
349        self.cross_rule_ac_enabled
350    }
351
352    /// Enable or disable retention of each loaded rule's HIR for
353    /// [`Engine::save_hir`].
354    ///
355    /// Off by default: nothing on the evaluation path reads the HIR, so
356    /// keeping it only costs memory. Enable it before loading rules when the
357    /// engine's rules will be saved as a restart cache. Disabling it drops
358    /// any HIR already retained.
359    pub fn set_retain_hir(&mut self, enabled: bool) {
360        if !enabled {
361            self.unretained_hir += self.ir_rules.len();
362            self.ir_rules = Vec::new();
363        }
364        self.retain_hir = enabled;
365    }
366
367    /// Returns whether loaded rules keep their HIR for [`Engine::save_hir`].
368    pub fn retain_hir_enabled(&self) -> bool {
369        self.retain_hir
370    }
371
372    /// Set global `include_event` — when `true`, all match results include
373    /// the full event JSON regardless of per-rule custom attributes.
374    pub fn set_include_event(&mut self, include: bool) {
375        self.include_event = include;
376    }
377
378    /// Set the match-detail verbosity for detection results.
379    ///
380    /// `Off` (default) records each match as `{ field, value }`, identical to
381    /// pre-enrichment releases. `Summary` adds the originating selection, the
382    /// matcher kind, and case sensitivity, and reports keyword and absence
383    /// matches that `Off` omits. `Full` additionally records the pattern that
384    /// fired. The extra work runs only when a rule matches and only above
385    /// `Off`, so the default hot path is unchanged.
386    pub fn set_match_detail(&mut self, level: MatchDetailLevel) {
387        self.match_detail = level;
388    }
389
390    /// Returns the configured match-detail verbosity.
391    pub fn match_detail(&self) -> MatchDetailLevel {
392        self.match_detail
393    }
394
395    /// Add a pipeline to the engine.
396    ///
397    /// Pipelines are applied to rules during `add_rule` / `add_collection`.
398    /// Only affects rules added **after** this call.
399    pub fn add_pipeline(&mut self, pipeline: Pipeline) {
400        self.pipelines.push(pipeline);
401        self.pipelines.sort_by_key(|p| p.priority);
402    }
403
404    /// Add a single parsed Sigma rule.
405    ///
406    /// If pipelines are set, the rule is cloned and transformed before
407    /// compilation. The rule index folds the new rule incrementally; the
408    /// bloom index also folds it incrementally and only triggers a full
409    /// rebuild when its doubling watermark is reached, so this call is
410    /// amortized O(1) per rule. With the `daachorse-index` feature
411    /// enabled **and** the cross-rule AC index turned on at runtime, the
412    /// call falls back to a full rebuild because the daachorse automaton
413    /// has no incremental update path.
414    pub fn add_rule(&mut self, rule: &SigmaRule) -> Result<()> {
415        self.compile_and_store(rule)?;
416        self.index_append_last_rule();
417        Ok(())
418    }
419
420    /// Add many parsed Sigma rules in a single batch.
421    ///
422    /// Each rule is compiled (with the engine's pipelines applied, if any)
423    /// and pushed onto the rule set. Compilation errors are collected and
424    /// returned as `(rule_index_in_input, error)` pairs without aborting the
425    /// batch; rules that did compile remain loaded. The inverted index and
426    /// per-field bloom filter are rebuilt **once** at the end of the batch.
427    ///
428    /// Prefer this over a loop of [`Engine::add_rule`] when loading large
429    /// rule sets: the per-call rebuild is O(N) in the total rule count, so
430    /// per-rule adds turn a 3K-rule corpus into O(N²) work.
431    pub fn add_rules<'a, I>(&mut self, rules: I) -> Vec<(usize, EvalError)>
432    where
433        I: IntoIterator<Item = &'a SigmaRule>,
434    {
435        let mut errors = Vec::new();
436        for (idx, rule) in rules.into_iter().enumerate() {
437            if let Err(e) = self.compile_and_store(rule) {
438                errors.push((idx, e));
439            }
440        }
441        self.rebuild_index();
442        errors
443    }
444
445    /// Add all detection rules from a parsed collection, then apply filters.
446    ///
447    /// Filter rules modify referenced detection rules by appending exclusion
448    /// conditions. Correlation rules are handled by `CorrelationEngine`.
449    /// The inverted index is rebuilt once after all rules and filters are loaded.
450    pub fn add_collection(&mut self, collection: &SigmaCollection) -> Result<()> {
451        for rule in &collection.rules {
452            self.compile_and_store(rule)?;
453        }
454        for filter in &collection.filters {
455            self.apply_filter_no_rebuild(filter)?;
456        }
457        self.rebuild_index();
458        Ok(())
459    }
460
461    /// Lower a rule to HIR (applying any configured pipelines first), compile
462    /// it, and store the compiled rule, plus its HIR when retention is on.
463    /// Shared by the single- and batched-add paths so they stay behaviourally
464    /// identical, and so the retained HIR (`ir_rules`) tracks `rules` for
465    /// [`Engine::save_hir`].
466    ///
467    /// Both pushes happen only after lowering and compilation succeed, so a
468    /// failing rule leaves neither vector mutated.
469    fn compile_and_store(&mut self, rule: &SigmaRule) -> Result<()> {
470        let ir = self.lower_with_pipelines(rule)?;
471        let compiled = compile_to_compiled(&ir)?;
472        self.store(ir, compiled);
473        Ok(())
474    }
475
476    fn store(&mut self, ir: IrRule, compiled: CompiledRule) {
477        if self.retain_hir {
478            self.ir_rules.push(ir);
479        } else {
480            self.unretained_hir += 1;
481        }
482        self.rules.push(compiled);
483    }
484
485    /// Lower a rule to HIR, applying any configured pipelines first.
486    fn lower_with_pipelines(&self, rule: &SigmaRule) -> Result<IrRule> {
487        if self.pipelines.is_empty() {
488            Ok(lower_rule(rule, &LowerOptions::default())?)
489        } else {
490            let mut transformed = rule.clone();
491            apply_pipelines(&self.pipelines, &mut transformed)?;
492            Ok(lower_rule(&transformed, &LowerOptions::default())?)
493        }
494    }
495
496    /// Serialize the retained rule HIR to a versioned cache blob (see
497    /// [`rsigma_ir::encode_rules`]).
498    ///
499    /// The blob captures rules added via the parsed-rule paths (`add_rule`,
500    /// `add_rules`, `add_collection`, and the pipeline variants) in
501    /// post-pipeline, pre-filter form. It does **not** capture filter
502    /// injections (applied to the compiled rules) or rules added via
503    /// [`Engine::add_compiled_rule`] / [`Engine::extend_compiled_rules`].
504    /// Re-apply any filters after [`Engine::load_hir`] if the engine used them.
505    ///
506    /// Requires HIR retention ([`Engine::set_retain_hir`]) to have been on
507    /// for every rule loaded through those paths; otherwise this returns
508    /// [`EvalError::HirCache`] rather than a cache that misses rules.
509    pub fn save_hir(&self) -> Result<Vec<u8>> {
510        if !self.retain_hir {
511            return Err(EvalError::HirCache(
512                "HIR retention is off; call Engine::set_retain_hir(true) before loading rules"
513                    .to_string(),
514            ));
515        }
516        if self.unretained_hir > 0 {
517            return Err(EvalError::HirCache(format!(
518                "{} rules were loaded while HIR retention was off and cannot be saved",
519                self.unretained_hir
520            )));
521        }
522        Ok(rsigma_ir::encode_rules(&self.ir_rules)?)
523    }
524
525    /// Load rules from a HIR cache blob produced by [`Engine::save_hir`],
526    /// compiling each into the engine and rebuilding the indexes once.
527    ///
528    /// Rules are appended to any already loaded, so a warm start loads into a
529    /// fresh [`Engine::new`]. A blob whose schema version differs from this
530    /// build's is rejected (see [`rsigma_ir::decode_rules`]). The loaded HIR
531    /// is retained only when [`Engine::set_retain_hir`] is on.
532    pub fn load_hir(&mut self, bytes: &[u8]) -> Result<()> {
533        let rules = rsigma_ir::decode_rules(bytes)?;
534        for ir in rules {
535            let compiled = compile_to_compiled(&ir)?;
536            self.store(ir, compiled);
537        }
538        self.rebuild_index();
539        Ok(())
540    }
541
542    /// Apply this engine's pipelines to `rule` and return the rewritten rule,
543    /// without compiling or loading anything.
544    ///
545    /// Use this to read what the configured pipelines do to a rule: the
546    /// rewritten `logsource`, the conditions a pipeline injected, or which
547    /// transformation ids fired. Loading a rule discards the rewritten Sigma AST
548    /// and keeps only the compiled form, so this is the way to see it.
549    ///
550    /// The engine is not modified and no rule is added. Cost is one clone plus
551    /// one pipeline pass, the same as the load path pays, so call it once per
552    /// rule set load rather than per event. If only the rewritten logsource
553    /// matters, read it from [`Engine::rules`] after loading instead: the
554    /// compiled rules already carry it.
555    pub fn transform_rule(&self, rule: &SigmaRule) -> Result<TransformedRule> {
556        crate::pipeline::transform_rule(&self.pipelines, rule)
557    }
558
559    /// Apply this engine's pipelines to every detection rule in `collection`.
560    ///
561    /// Per-rule equivalent of [`Engine::transform_rule`], in collection order.
562    pub fn transform_collection(
563        &self,
564        collection: &SigmaCollection,
565    ) -> Result<Vec<TransformedRule>> {
566        transform_collection(&self.pipelines, collection)
567    }
568
569    /// Add all detection rules from a collection, applying the given pipelines.
570    ///
571    /// This is a convenience method that temporarily sets pipelines, adds the
572    /// collection, then clears them. The inverted index is rebuilt once after
573    /// all rules and filters are loaded.
574    pub fn add_collection_with_pipelines(
575        &mut self,
576        collection: &SigmaCollection,
577        pipelines: &[Pipeline],
578    ) -> Result<()> {
579        let prev = std::mem::take(&mut self.pipelines);
580        self.pipelines = pipelines.to_vec();
581        self.pipelines.sort_by_key(|p| p.priority);
582        let result = self.add_collection(collection);
583        self.pipelines = prev;
584        result
585    }
586
587    /// Apply a filter rule to all referenced detection rules and rebuild the index.
588    pub fn apply_filter(&mut self, filter: &FilterRule) -> Result<()> {
589        self.apply_filter_no_rebuild(filter)?;
590        self.rebuild_index();
591        Ok(())
592    }
593
594    /// Apply a filter rule without rebuilding the index.
595    /// Used internally when multiple mutations are batched.
596    fn apply_filter_no_rebuild(&mut self, filter: &FilterRule) -> Result<()> {
597        // Compile filter detections
598        let mut filter_detections = Vec::new();
599        for (name, detection) in &filter.detection.named {
600            let compiled = compile_detection(detection)?;
601            filter_detections.push((name.clone(), compiled));
602        }
603
604        if filter_detections.is_empty() {
605            return Ok(());
606        }
607
608        let fc = self.filter_counter;
609        self.filter_counter += 1;
610
611        let identities: Vec<_> = self
612            .rules
613            .iter()
614            .map(|rule| (rule.id.as_deref(), rule.name.as_deref()))
615            .collect();
616        let stable = stable_references(filter, &identities);
617        let rewritten_cond = namespaced_filter_condition(filter, fc);
618
619        let mut matched_any = false;
620        for rule in &mut self.rules {
621            let target = FilterTarget {
622                id: rule.id.as_deref(),
623                name: rule.name.as_deref(),
624                title: &rule.title,
625                logsource: &rule.logsource,
626            };
627            if !filter_targets(filter, &stable, &target) {
628                continue;
629            }
630            for (name, compiled) in &filter_detections {
631                rule.detections
632                    .insert(filter_detection_key(fc, name), compiled.clone());
633            }
634            rule.conditions = rule
635                .conditions
636                .iter()
637                .map(|cond| ConditionExpr::And(vec![cond.clone(), rewritten_cond.clone()]))
638                .collect();
639            matched_any = true;
640        }
641
642        if let FilterRuleTarget::Specific(_) = &filter.rules
643            && !matched_any
644        {
645            log::warn!(
646                "filter '{}' references rules {:?} but none matched any loaded rule",
647                filter.title,
648                filter.rules
649            );
650        }
651
652        Ok(())
653    }
654
655    /// Add a pre-compiled rule directly. The rule index folds the new
656    /// rule incrementally; the bloom index also folds it incrementally
657    /// and only triggers a full rebuild when its doubling watermark is
658    /// reached, so this call is amortized O(1) per rule. With the
659    /// cross-rule AC index enabled (`daachorse-index` feature, runtime
660    /// toggle), this falls back to a full rebuild because daachorse has
661    /// no incremental update path.
662    pub fn add_compiled_rule(&mut self, rule: CompiledRule) {
663        self.rules.push(rule);
664        self.index_append_last_rule();
665    }
666
667    /// Add many pre-compiled rules in a single batch. The inverted index
668    /// and bloom filter are rebuilt exactly once at the end, regardless of
669    /// how many rules are appended.
670    pub fn extend_compiled_rules<I>(&mut self, rules: I)
671    where
672        I: IntoIterator<Item = CompiledRule>,
673    {
674        self.rules.extend(rules);
675        self.rebuild_index();
676    }
677
678    /// Rebuild every per-engine index from the current rule set.
679    ///
680    /// Used by batched rule loads (`add_rules`, `extend_compiled_rules`,
681    /// `add_collection`) and by mutations that rewrite existing rules
682    /// (`apply_filter`), where rebuilding once over the final shape is
683    /// cheaper than maintaining incremental state across mutations. The
684    /// single-rule paths use [`Engine::index_append_last_rule`] instead.
685    fn rebuild_index(&mut self) {
686        self.rule_index = CandidateIndex::build(&self.rules);
687        self.bloom_index = match self.bloom_max_bytes {
688            Some(budget) => FieldBloomIndex::build_with_budget(&self.rules, budget),
689            None => FieldBloomIndex::build(&self.rules),
690        };
691        #[cfg(feature = "daachorse-index")]
692        {
693            if self.cross_rule_ac_enabled {
694                self.cross_rule_ac_index = cross_rule_ac::CrossRuleAcIndex::build(&self.rules);
695                self.cross_rule_ac_prunable = self
696                    .rules
697                    .iter()
698                    .map(cross_rule_ac::rule_is_ac_prunable)
699                    .collect();
700            } else {
701                self.cross_rule_ac_index = cross_rule_ac::CrossRuleAcIndex::empty();
702                self.cross_rule_ac_prunable.clear();
703            }
704        }
705    }
706
707    /// Fold the rule most recently pushed onto `self.rules` into the
708    /// inverted and bloom indexes incrementally. Cost is bounded by the
709    /// new rule's detection tree size, not by the total rule count.
710    ///
711    /// The bloom index periodically forces a full rebuild via its
712    /// doubling watermark to re-enforce the memory budget and reset the
713    /// FPR drift that incremental inserts accumulate. Cross-rule AC
714    /// (daachorse) has no incremental story, so when it is enabled this
715    /// call falls back to [`Engine::rebuild_index`].
716    fn index_append_last_rule(&mut self) {
717        #[cfg(feature = "daachorse-index")]
718        {
719            if self.cross_rule_ac_enabled {
720                self.rebuild_index();
721                return;
722            }
723        }
724
725        let new_idx = self.rules.len() - 1;
726        let rule = &self.rules[new_idx];
727        self.rule_index.append_rule(new_idx, rule);
728        self.bloom_index.append_rule(rule);
729
730        // Both indexes carry an automaton that cannot absorb a single rule in
731        // place, so each parks the affected rules in a conservative fallback
732        // and clears it at its own doubling watermark.
733        if self.rule_index.should_rebuild(self.rules.len()) {
734            self.rule_index = CandidateIndex::build(&self.rules);
735        }
736        if self.bloom_index.should_rebuild(self.rules.len()) {
737            self.bloom_index = match self.bloom_max_bytes {
738                Some(budget) => FieldBloomIndex::build_with_budget(&self.rules, budget),
739                None => FieldBloomIndex::build(&self.rules),
740            };
741        }
742    }
743
744    /// Evaluate an event against candidate rules using the inverted index.
745    ///
746    /// When a logsource extractor is configured (see
747    /// [`Engine::set_logsource_extractor`]) the event's logsource is derived
748    /// from it and used for conflict-based pruning.
749    pub fn evaluate<E: Event>(&self, event: &E) -> Vec<EvaluationResult>
750    where
751        L: ExtractLogSource<E>,
752    {
753        self.evaluate_identified(event)
754            .into_iter()
755            .map(|identified| identified.result)
756            .collect()
757    }
758
759    pub(crate) fn evaluate_identified<E: Event>(&self, event: &E) -> Vec<IdentifiedEvaluation>
760    where
761        L: ExtractLogSource<E>,
762    {
763        let event_logsource = self
764            .logsource_extractor
765            .as_ref()
766            .map(|ex| ex.extract(event));
767        self.evaluate_identified_inner(event, event_logsource.as_ref())
768    }
769
770    /// Evaluate an event with a caller-resolved event logsource for
771    /// conflict-based pruning, bypassing the engine's own extractor.
772    ///
773    /// The schema router uses this to feed a per-event logsource resolved from
774    /// the event's explicit fields plus the recognized schema's implied
775    /// logsource, so cross-product rules are pruned even when the event carries
776    /// no explicit `product`/`service`/`category` field. Pruning is
777    /// conflict-based: a rule is skipped only when a dimension is set on both
778    /// the rule and `event_logsource` and the values differ.
779    pub fn evaluate_pruned<E: Event>(
780        &self,
781        event: &E,
782        event_logsource: &LogSource,
783    ) -> Vec<EvaluationResult> {
784        self.evaluate_pruned_identified(event, event_logsource)
785            .into_iter()
786            .map(|identified| identified.result)
787            .collect()
788    }
789
790    pub(crate) fn evaluate_pruned_identified<E: Event>(
791        &self,
792        event: &E,
793        event_logsource: &LogSource,
794    ) -> Vec<IdentifiedEvaluation> {
795        self.evaluate_identified_inner(event, Some(event_logsource))
796    }
797
798    fn evaluate_identified_inner<E: Event>(
799        &self,
800        event: &E,
801        event_logsource: Option<&LogSource>,
802    ) -> Vec<IdentifiedEvaluation> {
803        if self.bloom_prefilter {
804            let bloom = BloomCache::new(&self.bloom_index, event);
805            self.evaluate_candidates(event, event_logsource, &bloom)
806        } else {
807            // `NoBloom` is zero-sized, so this instantiation compiles to the
808            // same straight-line code as an engine without a bloom filter.
809            self.evaluate_candidates(event, event_logsource, &bloom_index::NoBloom)
810        }
811    }
812
813    /// Build the cross-rule AC keep-mask for `event`, or `None` when the
814    /// cross-rule index is disabled or empty (no filtering needed).
815    ///
816    /// `Some(mask)` answers "should this rule survive the cross-rule AC
817    /// filter": `mask[idx] = true` means keep, `false` means drop.
818    /// Non-AC-prunable rules are always kept.
819    #[cfg(feature = "daachorse-index")]
820    fn cross_rule_ac_keep_mask<E: Event>(&self, event: &E) -> Option<Vec<bool>> {
821        if !self.cross_rule_ac_enabled || self.cross_rule_ac_index.is_empty() {
822            return None;
823        }
824        let mut hits = vec![false; self.rules.len()];
825        self.cross_rule_ac_index.mark_hits(event, &mut hits);
826        // Compose: keep = !ac_prunable OR ac_hit. The prunable vector and
827        // the rule slice are kept aligned by `rebuild_index`.
828        for (idx, slot) in hits.iter_mut().enumerate() {
829            if !self
830                .cross_rule_ac_prunable
831                .get(idx)
832                .copied()
833                .unwrap_or(false)
834            {
835                *slot = true;
836            }
837        }
838        Some(hits)
839    }
840
841    #[cfg(not(feature = "daachorse-index"))]
842    #[inline(always)]
843    fn cross_rule_ac_keep_mask<E: Event>(&self, _event: &E) -> Option<Vec<bool>> {
844        None
845    }
846
847    /// Pick the candidate rule set for `event`. When a logsource extractor
848    /// produced an event logsource, the product-partitioned index drops
849    /// always-evaluated rules of a conflicting product; otherwise the full
850    /// candidate set is returned (zero behaviour change when pruning is off).
851    fn logsource_candidates<E: Event>(
852        &self,
853        event: &E,
854        event_logsource: Option<&LogSource>,
855    ) -> Vec<usize> {
856        match event_logsource {
857            Some(ls) => {
858                // Observability: count the fail-open case (no logsource at all)
859                // and the always-evaluated rules pruned by product conflict.
860                if ls.product.is_none() && ls.service.is_none() && ls.category.is_none() {
861                    self.logsource_absent.fetch_add(1, Ordering::Relaxed);
862                }
863                let pruned = self
864                    .rule_index
865                    .conflicting_unindexable_count(ls.product.as_deref());
866                if pruned > 0 {
867                    self.logsource_pruned
868                        .fetch_add(pruned as u64, Ordering::Relaxed);
869                }
870                self.rule_index
871                    .candidates_with_logsource(event, ls.product.as_deref())
872            }
873            None => self.rule_index.candidates(event),
874        }
875    }
876
877    fn evaluate_candidates<E: Event, B: BloomLookup>(
878        &self,
879        event: &E,
880        event_logsource: Option<&LogSource>,
881        bloom: &B,
882    ) -> Vec<IdentifiedEvaluation> {
883        let keep = self.cross_rule_ac_keep_mask(event);
884        // `event_logsource` is `None` (the default) unless pruning is enabled,
885        // leaving the loop's behaviour unchanged.
886        let candidates = self.logsource_candidates(event, event_logsource);
887        let mut results = Vec::new();
888        let mut pruned = 0u64;
889        for idx in candidates {
890            if let Some(ref mask) = keep
891                && !mask[idx]
892            {
893                continue;
894            }
895            let rule = &self.rules[idx];
896            if let Some(event_ls) = event_logsource
897                && !logsource_compatible(&rule.logsource, event_ls)
898            {
899                pruned += 1;
900                continue;
901            }
902            if let Some(m) = self.evaluate_one(rule, event, bloom) {
903                results.push(IdentifiedEvaluation {
904                    result: m,
905                    rule_id: rule.id.clone(),
906                    rule_name: rule.name.clone(),
907                });
908            }
909        }
910        self.record_logsource_pruned(pruned);
911        results
912    }
913
914    /// Evaluate one rule, attaching the event when `include_event` is set.
915    fn evaluate_one<E: Event, B: BloomLookup>(
916        &self,
917        rule: &CompiledRule,
918        event: &E,
919        bloom: &B,
920    ) -> Option<EvaluationResult> {
921        let mut m = evaluate_rule_with_bloom(rule, event, bloom, self.match_detail)?;
922        if self.include_event
923            && let Some(d) = m.as_detection_mut()
924            && d.event.is_none()
925        {
926            d.event = Some(event.to_json());
927        }
928        Some(m)
929    }
930
931    /// Fold one event's residual logsource-conflict tally into the counter.
932    ///
933    /// Kept out of the loop so a conflicting rule costs an increment on a
934    /// local rather than an atomic.
935    fn record_logsource_pruned(&self, pruned: u64) {
936        if pruned > 0 {
937            self.logsource_pruned.fetch_add(pruned, Ordering::Relaxed);
938        }
939    }
940
941    /// Evaluate an event against candidate rules matching the given logsource.
942    ///
943    /// Uses the inverted index for candidate pre-filtering, then applies the
944    /// logsource constraint. Only rules whose logsource is compatible with
945    /// `event_logsource` are evaluated.
946    pub fn evaluate_with_logsource<E: Event>(
947        &self,
948        event: &E,
949        event_logsource: &LogSource,
950    ) -> Vec<EvaluationResult> {
951        if self.bloom_prefilter {
952            let bloom = BloomCache::new(&self.bloom_index, event);
953            self.evaluate_matching_logsource(event, event_logsource, &bloom)
954        } else {
955            self.evaluate_matching_logsource(event, event_logsource, &bloom_index::NoBloom)
956        }
957    }
958
959    fn evaluate_matching_logsource<E: Event, B: BloomLookup>(
960        &self,
961        event: &E,
962        event_logsource: &LogSource,
963        bloom: &B,
964    ) -> Vec<EvaluationResult> {
965        let keep = self.cross_rule_ac_keep_mask(event);
966        let mut results = Vec::new();
967        for idx in self.rule_index.candidates(event) {
968            if let Some(ref mask) = keep
969                && !mask[idx]
970            {
971                continue;
972            }
973            let rule = &self.rules[idx];
974            if logsource_matches(&rule.logsource, event_logsource)
975                && let Some(m) = self.evaluate_one(rule, event, bloom)
976            {
977                results.push(m);
978            }
979        }
980        results
981    }
982
983    /// Reference evaluator: evaluate every loaded rule, bypassing the
984    /// candidate index, the cross-rule AC keep-mask, and the bloom
985    /// pre-filter.
986    ///
987    /// This is the differential oracle for every pre-filter layer. It is
988    /// authoritative by construction, because it applies nothing but
989    /// [`evaluate_rule_with_bloom`] and the same logsource-conflict rule the
990    /// production path applies to a surviving candidate. Any disagreement
991    /// with [`Engine::evaluate`] is therefore a pre-filter bug: a pre-filter
992    /// may only ever over-approximate the candidate set.
993    ///
994    /// Results come back in ascending rule order. Callers comparing against
995    /// [`Engine::evaluate`] must compare order-insensitively, since candidate
996    /// iteration order is not part of the engine's contract.
997    #[cfg(test)]
998    pub(crate) fn evaluate_full_scan<E: Event>(&self, event: &E) -> Vec<EvaluationResult>
999    where
1000        L: ExtractLogSource<E>,
1001    {
1002        let event_logsource = self
1003            .logsource_extractor
1004            .as_ref()
1005            .map(|ex| ex.extract(event));
1006        self.full_scan_filtered(event, |rule| match event_logsource.as_ref() {
1007            Some(event_ls) => logsource_compatible(&rule.logsource, event_ls),
1008            None => true,
1009        })
1010    }
1011
1012    /// [`Engine::evaluate_full_scan`] for the caller-resolved-logsource path,
1013    /// mirroring [`Engine::evaluate_pruned`]'s conflict-based filtering.
1014    #[cfg(test)]
1015    pub(crate) fn evaluate_pruned_full_scan<E: Event>(
1016        &self,
1017        event: &E,
1018        event_logsource: &LogSource,
1019    ) -> Vec<EvaluationResult> {
1020        self.full_scan_filtered(event, |rule| {
1021            logsource_compatible(&rule.logsource, event_logsource)
1022        })
1023    }
1024
1025    /// [`Engine::evaluate_full_scan`] for the strict-routing path, mirroring
1026    /// [`Engine::evaluate_with_logsource`]'s use of `logsource_matches`.
1027    #[cfg(test)]
1028    pub(crate) fn evaluate_with_logsource_full_scan<E: Event>(
1029        &self,
1030        event: &E,
1031        event_logsource: &LogSource,
1032    ) -> Vec<EvaluationResult> {
1033        self.full_scan_filtered(event, |rule| {
1034            logsource_matches(&rule.logsource, event_logsource)
1035        })
1036    }
1037
1038    #[cfg(test)]
1039    fn full_scan_filtered<E: Event>(
1040        &self,
1041        event: &E,
1042        keep: impl Fn(&CompiledRule) -> bool,
1043    ) -> Vec<EvaluationResult> {
1044        let mut results = Vec::new();
1045        for rule in &self.rules {
1046            if !keep(rule) {
1047                continue;
1048            }
1049            if let Some(m) = self.evaluate_one(rule, event, &bloom_index::NoBloom) {
1050                results.push(m);
1051            }
1052        }
1053        results
1054    }
1055
1056    /// Evaluate a batch of events, returning per-event match results.
1057    ///
1058    /// When the `parallel` feature is enabled, events are evaluated concurrently
1059    /// using rayon's work-stealing thread pool. Otherwise, falls back to
1060    /// sequential evaluation.
1061    pub fn evaluate_batch<E: Event + Sync>(&self, events: &[&E]) -> Vec<Vec<EvaluationResult>>
1062    where
1063        L: ExtractLogSource<E> + Sync,
1064    {
1065        #[cfg(feature = "parallel")]
1066        {
1067            use rayon::prelude::*;
1068            events.par_iter().map(|e| self.evaluate(e)).collect()
1069        }
1070        #[cfg(not(feature = "parallel"))]
1071        {
1072            events.iter().map(|e| self.evaluate(e)).collect()
1073        }
1074    }
1075
1076    /// Number of rules loaded in the engine.
1077    pub fn rule_count(&self) -> usize {
1078        self.rules.len()
1079    }
1080
1081    /// Access the compiled rules.
1082    pub fn rules(&self) -> &[CompiledRule] {
1083        &self.rules
1084    }
1085
1086    /// Resolve a rule key (an id, or a title for a rule without one) to the
1087    /// documentation of every loaded rule that carries it.
1088    pub fn rule_metadata(&self, key: &str) -> RuleMetadataLookup {
1089        let mut variants = Vec::new();
1090        self.collect_rule_metadata(key, &mut variants);
1091        RuleMetadataLookup::from_variants(variants)
1092    }
1093
1094    pub(crate) fn collect_rule_metadata(&self, key: &str, out: &mut Vec<RuleBundleMetadata>) {
1095        crate::rule_metadata::matching_detections(&self.rules, key, out);
1096    }
1097}
1098
1099impl Default for Engine {
1100    fn default() -> Self {
1101        Self::new()
1102    }
1103}