Skip to main content

rsigma_eval/
router.rs

1//! Multi-engine schema router: classify each event, route it to the detection
2//! engine built for its schema's pipeline-set, and feed every detection into
3//! one shared correlation store.
4//!
5//! # Design
6//!
7//! - One [`Engine`] per deduplicated pipeline-set (index-aligned with
8//!   [`RoutingPlan::pipeline_sets`]). The schema's pipeline is applied to the
9//!   detection rules in its engine, exactly as a single-pipeline run would.
10//! - One shared [`CorrelationEngine`] (present only when the rule set has
11//!   correlation rules), built Sigma-native (no pipeline). Detections from any
12//!   per-schema engine feed into it via
13//!   [`CorrelationEngine::correlate_detections`].
14//! - Cross-schema correlation grouping works because the group-by extraction is
15//!   schema-aware: each set carries a `Sigma -> event field` map (derived from
16//!   its pipelines' field-name mappings), and the event is wrapped in a
17//!   [`MappedEvent`] before correlation so the Sigma-native group-by names
18//!   resolve to the schema's field names. The window store stays shared, keyed
19//!   by the logical correlation plus the extracted group values.
20//!
21//! This subsumes the single-schema case (one pipeline-set is the degenerate
22//! configuration), so there is no separate code path for "routing off".
23
24use std::collections::HashMap;
25
26use rsigma_parser::{LogSource, SigmaCollection, SigmaRule};
27
28use crate::correlation_engine::{
29    CorrelationConfig, CorrelationEngine, CorrelationSnapshot, CorrelationStateSnapshot,
30    ProcessResult,
31};
32use crate::engine::{Engine, IdentifiedEvaluation};
33use crate::error::Result;
34use crate::event::{Event, MappedEvent};
35use crate::logsource::{ExtractLogSource, LogSourceExtractor};
36use crate::pipeline::Pipeline;
37use crate::pipeline::transformations::Transformation;
38use crate::result::MatchDetailLevel;
39use crate::rule_metadata::RuleMetadataLookup;
40use crate::schema::{OnUnknown, RouteDecision, RoutingPlan, SchemaClassifier};
41
42/// Per-schema logsource pruning summary: how many rules a schema's events
43/// evaluate versus how many are pruned by its implied logsource. A static view
44/// (independent of any specific event's field values) for operator visibility.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct SchemaPruning {
47    /// The recognized schema name.
48    pub schema: String,
49    /// Rules evaluated for this schema (logsource-compatible).
50    pub eligible: usize,
51    /// Rules pruned for this schema (logsource-conflicting).
52    pub pruned: usize,
53}
54
55/// What the router did with an event, for reporting and `on_unknown` handling.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub enum RouteOutcome {
58    /// Evaluated against a bound or known schema's set.
59    Evaluated,
60    /// Evaluated against the default set because the schema was unrecognized
61    /// (`on_unknown: warn` or `passthrough`).
62    EvaluatedUnknown,
63    /// Dropped without evaluating (`on_unknown: drop`).
64    Dropped,
65    /// Dropped and flagged as an error (`on_unknown: error`).
66    Errored,
67}
68
69/// The result of routing one event.
70pub struct RouteResult {
71    /// Evaluation results (empty when dropped or errored).
72    pub results: ProcessResult,
73    /// The classified schema name, or `None` when unrecognized.
74    pub schema: Option<String>,
75    /// What the router did.
76    pub outcome: RouteOutcome,
77}
78
79/// Collect a combined `Sigma -> [event field]` map from a pipeline-set's
80/// field-name mappings, used for schema-aware correlation group-by extraction.
81fn collect_field_map(pipelines: &[Pipeline]) -> HashMap<String, Vec<String>> {
82    let mut map: HashMap<String, Vec<String>> = HashMap::new();
83    for pipeline in pipelines {
84        for item in &pipeline.transformations {
85            if let Transformation::FieldNameMapping { mapping } = &item.transformation {
86                for (from, to) in mapping {
87                    map.entry(from.clone())
88                        .or_default()
89                        .extend(to.iter().cloned());
90                }
91            }
92        }
93    }
94    map
95}
96
97/// Outcome of the stateless phase for one event in [`SchemaRouter::process_batch`].
98enum Routed1 {
99    /// Dropped or errored (`on_unknown`): no results.
100    Skip,
101    /// Evaluate detections against the shared correlation store under set `set`.
102    Eval {
103        set: usize,
104        detections: Vec<IdentifiedEvaluation>,
105    },
106}
107
108/// Keep a detection rule when partitioning a per-schema engine: rules with no
109/// product apply to every platform; a product-tagged rule is kept only when its
110/// product is among the set's allowed products (lowercased).
111fn rule_product_kept(rule: &SigmaRule, products: &std::collections::HashSet<String>) -> bool {
112    match &rule.logsource.product {
113        None => true,
114        Some(p) => products.contains(&p.to_ascii_lowercase()),
115    }
116}
117
118/// Whether a pipeline rewrites a rule's product via `change_logsource`, which
119/// makes pre-pipeline product partitioning unsafe (a rule could be re-producted
120/// at compile time). Such a set keeps its full ruleset.
121fn pipeline_changes_product(pipeline: &Pipeline) -> bool {
122    pipeline.transformations.iter().any(|item| {
123        matches!(
124            &item.transformation,
125            Transformation::ChangeLogsource {
126                product: Some(_),
127                ..
128            }
129        )
130    })
131}
132
133/// Resolve an event's logsource for conflict-based pruning: the extractor's
134/// value (explicit event fields, then static/format defaults) wins, and the
135/// recognized schema's implied logsource fills any dimension left unset. This
136/// is what lets a `product`-less event still prune cross-product rules once its
137/// schema is known (for example a `sysmon`-classified event implies
138/// `product: windows`).
139fn resolve_event_logsource<E: Event, L: ExtractLogSource<E>>(
140    extractor: &L,
141    implied: Option<&LogSource>,
142    event: &E,
143) -> LogSource {
144    let mut ls = extractor.extract(event);
145    if let Some(implied) = implied {
146        if ls.product.is_none() {
147            ls.product = implied.product.clone();
148        }
149        if ls.service.is_none() {
150            ls.service = implied.service.clone();
151        }
152        if ls.category.is_none() {
153            ls.category = implied.category.clone();
154        }
155        for (key, value) in &implied.custom {
156            ls.custom
157                .entry(key.clone())
158                .or_insert_with(|| value.clone());
159        }
160    }
161    ls
162}
163
164/// Stateless detection for one event: classify, decide, evaluate. Borrows only
165/// shared state so it can run in parallel across a batch. When a logsource
166/// extractor is configured, the event's logsource is resolved (explicit fields
167/// plus the schema's implied logsource) and fed into conflict-based pruning.
168fn detect_one<E: Event, L: ExtractLogSource<E>>(
169    classifier: &SchemaClassifier,
170    plan: &RoutingPlan,
171    engines: &[Engine],
172    extractor: Option<&L>,
173    event: &E,
174) -> Routed1 {
175    let schema = classifier.classify(event).map(|m| m.name);
176    match plan.decide(schema.as_deref()) {
177        RouteDecision::Drop | RouteDecision::Error => Routed1::Skip,
178        RouteDecision::Evaluate { set, .. } => {
179            let detections = match extractor {
180                Some(ex) => {
181                    let implied = schema.as_deref().and_then(|s| plan.schema_logsource(s));
182                    let ls = resolve_event_logsource(ex, implied, event);
183                    engines[set].evaluate_pruned_identified(event, &ls)
184                }
185                None => engines[set].evaluate_identified(event),
186            };
187            Routed1::Eval { set, detections }
188        }
189    }
190}
191
192/// A multi-engine router over a classifier, a [`RoutingPlan`], one detection
193/// engine per pipeline-set, and one shared correlation store.
194///
195/// Generic over the logsource extractor `L`, which defaults to
196/// [`LogSourceExtractor`]. Build with [`SchemaRouter::build`] for the default,
197/// or [`SchemaRouter::build_with_logsource_extractor`] for a custom
198/// [`ExtractLogSource`] implementation.
199pub struct SchemaRouter<L = LogSourceExtractor> {
200    classifier: SchemaClassifier,
201    plan: RoutingPlan,
202    /// One detection engine per pipeline-set (index = set index).
203    engines: Vec<Engine>,
204    /// `Sigma -> event field` map per pipeline-set, for correlation group-by.
205    field_maps: Vec<HashMap<String, Vec<String>>>,
206    /// Shared correlation store; `None` when there are no correlation rules.
207    correlation: Option<CorrelationEngine>,
208    /// Event-logsource extractor for conflict-based pruning; `None` disables
209    /// pruning. Resolution happens per event in the router (extractor value
210    /// plus the schema's implied logsource), so it is not set on the engines.
211    logsource_extractor: Option<L>,
212}
213
214impl SchemaRouter {
215    /// Build a router. `pipeline_sets` must be index-aligned with
216    /// `plan.pipeline_sets()` (one resolved pipeline list per set).
217    #[allow(clippy::too_many_arguments)]
218    pub fn build(
219        collection: &SigmaCollection,
220        classifier: SchemaClassifier,
221        plan: RoutingPlan,
222        pipeline_sets: Vec<Vec<Pipeline>>,
223        corr_config: CorrelationConfig,
224        include_event: bool,
225        match_detail: MatchDetailLevel,
226        logsource_extractor: Option<LogSourceExtractor>,
227        partition_rules: bool,
228    ) -> Result<Self> {
229        Self::build_inner(
230            collection,
231            classifier,
232            plan,
233            pipeline_sets,
234            corr_config,
235            include_event,
236            match_detail,
237            logsource_extractor,
238            partition_rules,
239        )
240    }
241}
242
243impl<L> SchemaRouter<L> {
244    /// Build a router that prunes with `extractor`, a custom
245    /// [`ExtractLogSource`] implementation. Arguments are otherwise as in
246    /// [`SchemaRouter::build`]. The recognized schema's implied logsource
247    /// still fills any dimension the extractor leaves unset.
248    #[allow(clippy::too_many_arguments)]
249    pub fn build_with_logsource_extractor(
250        collection: &SigmaCollection,
251        classifier: SchemaClassifier,
252        plan: RoutingPlan,
253        pipeline_sets: Vec<Vec<Pipeline>>,
254        corr_config: CorrelationConfig,
255        include_event: bool,
256        match_detail: MatchDetailLevel,
257        extractor: L,
258        partition_rules: bool,
259    ) -> Result<Self> {
260        Self::build_inner(
261            collection,
262            classifier,
263            plan,
264            pipeline_sets,
265            corr_config,
266            include_event,
267            match_detail,
268            Some(extractor),
269            partition_rules,
270        )
271    }
272
273    #[allow(clippy::too_many_arguments)]
274    fn build_inner(
275        collection: &SigmaCollection,
276        classifier: SchemaClassifier,
277        plan: RoutingPlan,
278        pipeline_sets: Vec<Vec<Pipeline>>,
279        corr_config: CorrelationConfig,
280        include_event: bool,
281        match_detail: MatchDetailLevel,
282        logsource_extractor: Option<L>,
283        partition_rules: bool,
284    ) -> Result<Self> {
285        // Optional, gated per-schema rule partitioning: each engine bound only
286        // to platform-locked schemas compiles just the rules whose product can
287        // apply, cutting the N-copies memory cost. Off by default and disabled
288        // for any set whose pipelines rewrite product.
289        let partition = if partition_rules {
290            plan.set_product_partition()
291        } else {
292            vec![None; pipeline_sets.len()]
293        };
294
295        let mut engines = Vec::with_capacity(pipeline_sets.len());
296        let mut field_maps = Vec::with_capacity(pipeline_sets.len());
297        for (idx, set) in pipeline_sets.iter().enumerate() {
298            let mut engine = Engine::new();
299            engine.set_include_event(include_event);
300            engine.set_match_detail(match_detail);
301            for p in set {
302                engine.add_pipeline(p.clone());
303            }
304            // Partition only when the set has an allowed-product set and no
305            // pipeline rewrites product; otherwise compile the full ruleset.
306            let partitioned = partition
307                .get(idx)
308                .and_then(|o| o.as_ref())
309                .filter(|_| !set.iter().any(pipeline_changes_product));
310            match partitioned {
311                Some(products) => {
312                    let mut filtered = collection.clone();
313                    filtered.rules.retain(|r| rule_product_kept(r, products));
314                    engine.add_collection(&filtered)?;
315                }
316                None => engine.add_collection(collection)?,
317            }
318            engines.push(engine);
319            field_maps.push(collect_field_map(set));
320        }
321
322        // The shared correlation store is Sigma-native (no pipeline): group-by
323        // names stay logical and are mapped per schema at feed time. Its inner
324        // detection engine is unused (routed detection runs in `engines`).
325        let correlation = if collection.correlations.is_empty() {
326            None
327        } else {
328            let mut ce = CorrelationEngine::new(corr_config);
329            ce.set_include_event(include_event);
330            ce.set_match_detail(match_detail);
331            ce.add_collection(collection)?;
332            Some(ce)
333        };
334
335        Ok(SchemaRouter {
336            classifier,
337            plan,
338            engines,
339            field_maps,
340            correlation,
341            logsource_extractor,
342        })
343    }
344
345    /// The unknown-handling policy this router enforces.
346    pub fn on_unknown(&self) -> OnUnknown {
347        self.plan.on_unknown()
348    }
349
350    /// Whether this router has a correlation store.
351    pub fn has_correlations(&self) -> bool {
352        self.correlation.is_some()
353    }
354
355    /// Number of detection rules (same across every per-schema engine, unless
356    /// per-schema rule partitioning is enabled; see [`engine_rule_counts`]).
357    ///
358    /// [`engine_rule_counts`]: SchemaRouter::engine_rule_counts
359    pub fn detection_rule_count(&self) -> usize {
360        self.engines.first().map(|e| e.rule_count()).unwrap_or(0)
361    }
362
363    /// Per-pipeline-set detection rule counts, in set order. Equal across sets
364    /// unless per-schema rule partitioning is enabled, in which case
365    /// platform-locked sets carry fewer rules than the default set.
366    pub fn engine_rule_counts(&self) -> Vec<usize> {
367        self.engines.iter().map(Engine::rule_count).collect()
368    }
369
370    /// Total rule candidates pruned by logsource across every per-schema
371    /// engine (each event routes to exactly one engine).
372    pub fn logsource_pruned_total(&self) -> u64 {
373        self.engines
374            .iter()
375            .map(Engine::logsource_pruned_total)
376            .sum()
377    }
378
379    /// Total evaluate calls with no extractable event logsource (fail-open)
380    /// across every per-schema engine.
381    pub fn logsource_absent_total(&self) -> u64 {
382        self.engines
383            .iter()
384            .map(Engine::logsource_absent_total)
385            .sum()
386    }
387
388    /// Static per-schema pruning summary: for each schema with an implied
389    /// logsource, how many rules its events evaluate versus prune. Empty when
390    /// logsource routing is disabled (no extractor). Sorted by descending
391    /// pruned count, then schema name.
392    pub fn schema_pruning_summary(&self) -> Vec<SchemaPruning> {
393        if self.logsource_extractor.is_none() {
394            return Vec::new();
395        }
396        let mut out = Vec::new();
397        for schema in self.plan.schemas_with_logsource() {
398            let Some(implied) = self.plan.schema_logsource(&schema) else {
399                continue;
400            };
401            let set = match self.plan.decide(Some(&schema)) {
402                RouteDecision::Evaluate { set, .. } => set,
403                RouteDecision::Drop | RouteDecision::Error => 0,
404            };
405            let (eligible, pruned) = self.engines[set].logsource_eligibility(implied);
406            out.push(SchemaPruning {
407                schema,
408                eligible,
409                pruned,
410            });
411        }
412        out.sort_by(|a, b| {
413            b.pruned
414                .cmp(&a.pruned)
415                .then_with(|| a.schema.cmp(&b.schema))
416        });
417        out
418    }
419
420    /// Number of correlation rules in the shared store (0 when none).
421    pub fn correlation_rule_count(&self) -> usize {
422        self.correlation
423            .as_ref()
424            .map(|c| c.correlation_rule_count())
425            .unwrap_or(0)
426    }
427
428    /// Number of live correlation window-state entries (0 when none).
429    pub fn state_count(&self) -> usize {
430        self.correlation
431            .as_ref()
432            .map(|c| c.state_count())
433            .unwrap_or(0)
434    }
435
436    /// Resolve a rule key (an id, or a title for a rule without one) to the
437    /// documentation of every loaded rule that carries it.
438    ///
439    /// A rule set is compiled once per pipeline-set, so the same rule usually
440    /// yields one candidate per schema. Candidates whose post-pipeline metadata
441    /// is identical collapse to a single answer; a rule whose pipelines rewrite
442    /// its documentation differently per schema stays
443    /// [`Ambiguous`](RuleMetadataLookup::Ambiguous).
444    pub fn rule_metadata(&self, key: &str) -> RuleMetadataLookup {
445        let mut variants = Vec::new();
446        for engine in &self.engines {
447            engine.collect_rule_metadata(key, &mut variants);
448        }
449        if let Some(correlation) = &self.correlation {
450            correlation.collect_rule_metadata(key, &mut variants);
451        }
452        RuleMetadataLookup::from_variants(variants)
453    }
454
455    /// Introspect the shared correlation store, if any (id/group filtered).
456    pub fn correlation_introspect(
457        &self,
458        id: Option<&str>,
459        group: Option<&str>,
460    ) -> Option<CorrelationStateSnapshot> {
461        self.correlation
462            .as_ref()
463            .map(|c| c.introspect_filtered(id, group))
464    }
465
466    /// Export the shared correlation state, if any, for hot-reload carry-over.
467    pub fn export_state(&self) -> Option<CorrelationSnapshot> {
468        self.correlation.as_ref().map(|c| c.export_state())
469    }
470
471    /// Import previously exported correlation state into the shared store.
472    /// No-op (returns `true`) when there is no correlation store.
473    pub fn import_state(&mut self, snapshot: CorrelationSnapshot) -> bool {
474        match &mut self.correlation {
475            Some(c) => c.import_state(snapshot),
476            None => true,
477        }
478    }
479
480    /// Stateless classify + detection for a batch. Safe to call under a shared
481    /// borrow when there is no correlation store; see [`Self::process_batch`].
482    pub fn detect_batch<E: Event + Sync>(&self, events: &[&E]) -> Vec<ProcessResult>
483    where
484        L: ExtractLogSource<E> + Sync,
485    {
486        let classifier = &self.classifier;
487        let plan = &self.plan;
488        let engines = &self.engines;
489        let extractor = self.logsource_extractor.as_ref();
490        let phase1: Vec<Routed1> = {
491            #[cfg(feature = "parallel")]
492            {
493                use rayon::prelude::*;
494                events
495                    .par_iter()
496                    .map(|e| detect_one(classifier, plan, engines, extractor, *e))
497                    .collect()
498            }
499            #[cfg(not(feature = "parallel"))]
500            {
501                events
502                    .iter()
503                    .map(|e| detect_one(classifier, plan, engines, extractor, *e))
504                    .collect()
505            }
506        };
507        phase1
508            .into_iter()
509            .map(|routed| match routed {
510                Routed1::Skip => Vec::new(),
511                Routed1::Eval { detections, .. } => detections
512                    .into_iter()
513                    .map(|identified| identified.result)
514                    .collect(),
515            })
516            .collect()
517    }
518
519    /// Route a batch of events: parallel classify + detection, then sequential
520    /// correlation into the shared store. Mirrors
521    /// `CorrelationEngine::process_batch`: the stateless phase runs concurrently
522    /// (under the `parallel` feature) and the stateful correlation phase runs
523    /// in order. Drop/error outcomes yield empty results for that event.
524    ///
525    /// When there is no correlation store this is equivalent to [`Self::detect_batch`]
526    /// and only needs a shared borrow of the router.
527    pub fn process_batch<E: Event + Sync>(&mut self, events: &[&E]) -> Vec<ProcessResult>
528    where
529        L: ExtractLogSource<E> + Sync,
530    {
531        if self.correlation.is_none() {
532            return self.detect_batch(events);
533        }
534
535        // Stateless phase: classify + route + detect. Borrows only `&self`
536        // fields, so it parallelizes; correlation state is untouched here.
537        let classifier = &self.classifier;
538        let plan = &self.plan;
539        let engines = &self.engines;
540        let extractor = self.logsource_extractor.as_ref();
541        let phase1: Vec<Routed1> = {
542            #[cfg(feature = "parallel")]
543            {
544                use rayon::prelude::*;
545                events
546                    .par_iter()
547                    .map(|e| detect_one(classifier, plan, engines, extractor, *e))
548                    .collect()
549            }
550            #[cfg(not(feature = "parallel"))]
551            {
552                events
553                    .iter()
554                    .map(|e| detect_one(classifier, plan, engines, extractor, *e))
555                    .collect()
556            }
557        };
558
559        // Stateful phase: feed detections into the shared correlation store in
560        // event order. Disjoint field borrows let the field maps and the
561        // correlation store be held at once.
562        let field_maps = &self.field_maps;
563        let correlation = self.correlation.as_mut().expect("checked above");
564        phase1
565            .into_iter()
566            .zip(events)
567            .map(|(routed, event)| match routed {
568                Routed1::Skip => Vec::new(),
569                Routed1::Eval { set, detections } => {
570                    let mapped = MappedEvent::new(*event, &field_maps[set]);
571                    correlation.correlate_identified_detections(&mapped, detections)
572                }
573            })
574            .collect()
575    }
576
577    /// Classify and route one event.
578    pub fn route<E: Event>(&mut self, event: &E) -> RouteResult
579    where
580        L: ExtractLogSource<E>,
581    {
582        let schema = self.classifier.classify(event).map(|m| m.name);
583        match self.plan.decide(schema.as_deref()) {
584            RouteDecision::Drop => RouteResult {
585                results: Vec::new(),
586                schema,
587                outcome: RouteOutcome::Dropped,
588            },
589            RouteDecision::Error => RouteResult {
590                results: Vec::new(),
591                schema,
592                outcome: RouteOutcome::Errored,
593            },
594            RouteDecision::Evaluate { set, unknown } => {
595                let detections = match self.logsource_extractor.as_ref() {
596                    Some(ex) => {
597                        let implied = schema
598                            .as_deref()
599                            .and_then(|s| self.plan.schema_logsource(s));
600                        let ls = resolve_event_logsource(ex, implied, event);
601                        self.engines[set].evaluate_pruned_identified(event, &ls)
602                    }
603                    None => self.engines[set].evaluate_identified(event),
604                };
605                let results = match &mut self.correlation {
606                    Some(ce) => {
607                        let mapped = MappedEvent::new(event, &self.field_maps[set]);
608                        ce.correlate_identified_detections(&mapped, detections)
609                    }
610                    None => detections
611                        .into_iter()
612                        .map(|identified| identified.result)
613                        .collect(),
614                };
615                RouteResult {
616                    results,
617                    schema,
618                    outcome: if unknown {
619                        RouteOutcome::EvaluatedUnknown
620                    } else {
621                        RouteOutcome::Evaluated
622                    },
623                }
624            }
625        }
626    }
627}
628
629#[cfg(test)]
630mod tests {
631    use super::*;
632    use crate::JsonEvent;
633    use crate::pipeline::parse_pipeline;
634    use crate::schema::RoutingConfig;
635    use rsigma_parser::parse_sigma_yaml;
636    use serde_json::json;
637
638    const RULES: &str = r#"
639title: Whoami
640id: rule-whoami
641logsource:
642    category: process_creation
643    product: windows
644detection:
645    selection:
646        CommandLine|contains: whoami
647    condition: selection
648level: high
649"#;
650
651    const ECS_PIPELINE: &str = r#"
652name: ecs_test
653priority: 20
654transformations:
655  - id: map
656    type: field_name_mapping
657    mapping:
658      CommandLine: process.command_line
659      User: user.name
660"#;
661
662    fn plan(bindings: &[(&str, &[&str])]) -> RoutingPlan {
663        let config = RoutingConfig {
664            on_unknown: OnUnknown::Warn,
665            default_pipelines: vec![],
666            aliases: std::collections::HashMap::new(),
667            bindings: bindings
668                .iter()
669                .map(|(s, ps)| crate::schema::SchemaBinding {
670                    schema: (*s).to_string(),
671                    pipelines: ps.iter().map(|p| (*p).to_string()).collect(),
672                    logsource: None,
673                })
674                .collect(),
675        };
676        RoutingPlan::from_config(&config)
677    }
678
679    #[test]
680    fn routes_ecs_event_to_ecs_engine() {
681        let collection = parse_sigma_yaml(RULES).unwrap();
682        // set 0 = default (no pipeline, Sigma-native fields), set 1 = ECS.
683        let ecs = parse_pipeline(ECS_PIPELINE).unwrap();
684        let plan = plan(&[("ecs", &["ecs_test"])]);
685        let mut router = SchemaRouter::build(
686            &collection,
687            SchemaClassifier::builtin(),
688            plan,
689            vec![vec![], vec![ecs]],
690            CorrelationConfig::default(),
691            false,
692            MatchDetailLevel::Off,
693            None,
694            false,
695        )
696        .unwrap();
697
698        // ECS event: fields are renamed; only the ECS engine matches it.
699        let ecs_event = json!({"ecs.version": "8.0.0", "process.command_line": "cmd /c whoami"});
700        let r = router.route(&JsonEvent::borrow(&ecs_event));
701        assert_eq!(r.schema.as_deref(), Some("ecs"));
702        assert_eq!(r.outcome, RouteOutcome::Evaluated);
703        assert_eq!(r.results.len(), 1, "ECS event matches via the ECS engine");
704
705        // A Sigma-native event with the same command is unrecognized here
706        // (no ecs.version, no sysmon markers) -> generic_json -> default set,
707        // which has no pipeline, so the rule's CommandLine matches it.
708        let native = json!({"CommandLine": "cmd /c whoami"});
709        let r = router.route(&JsonEvent::borrow(&native));
710        assert_eq!(r.schema.as_deref(), Some("generic_json"));
711        assert_eq!(r.results.len(), 1);
712    }
713
714    #[test]
715    fn cross_schema_correlation_groups_the_same_entity() {
716        // A detection rule plus an event_count correlation grouped by User.
717        // The same user appears once as an ECS event (user.name) and once as a
718        // Sigma-native event (User); they must land in the same window and fire.
719        let rules = r#"
720title: Whoami
721id: rule-whoami
722logsource:
723    category: process_creation
724    product: windows
725detection:
726    selection:
727        CommandLine|contains: whoami
728    condition: selection
729level: high
730---
731title: Repeated whoami by user
732correlation:
733    type: event_count
734    rules:
735        - rule-whoami
736    group-by:
737        - User
738    timespan: 1h
739    condition:
740        gte: 2
741level: high
742"#;
743        let collection = parse_sigma_yaml(rules).unwrap();
744        let ecs = parse_pipeline(ECS_PIPELINE).unwrap();
745        // set 0 = default (Sigma-native), set 1 = ECS. ecs schema -> set 1;
746        // everything else (incl. the generic event) -> default set 0.
747        let plan = plan(&[("ecs", &["ecs_test"])]);
748
749        let config = CorrelationConfig {
750            timestamp_fallback: crate::correlation_engine::TimestampFallback::WallClock,
751            ..Default::default()
752        };
753
754        let mut router = SchemaRouter::build(
755            &collection,
756            SchemaClassifier::builtin(),
757            plan,
758            vec![vec![], vec![ecs]],
759            config,
760            false,
761            MatchDetailLevel::Off,
762            None,
763            false,
764        )
765        .unwrap();
766
767        // First occurrence: ECS event for user alice.
768        let ecs_event = json!({
769            "ecs.version": "8.0.0",
770            "process.command_line": "cmd /c whoami",
771            "user.name": "alice"
772        });
773        let r1 = router.route(&JsonEvent::borrow(&ecs_event));
774        assert_eq!(r1.schema.as_deref(), Some("ecs"));
775        assert!(
776            !r1.results.iter().any(|r| r.is_correlation()),
777            "first event must not fire the count>=2 correlation yet"
778        );
779
780        // Second occurrence: Sigma-native event for the SAME user alice.
781        let native_event = json!({"CommandLine": "cmd /c whoami", "User": "alice"});
782        let r2 = router.route(&JsonEvent::borrow(&native_event));
783        assert!(
784            r2.results.iter().any(|r| r.is_correlation()),
785            "the two events share group User=alice across schemas and must correlate"
786        );
787    }
788
789    #[test]
790    fn drop_policy_skips_unknown_events() {
791        let collection = parse_sigma_yaml(RULES).unwrap();
792        let config = RoutingConfig {
793            on_unknown: OnUnknown::Drop,
794            default_pipelines: vec![],
795            aliases: std::collections::HashMap::new(),
796            // Bind generic_json away so a plain event is truly unknown.
797            bindings: vec![],
798        };
799        let plan = RoutingPlan::from_config(&config);
800        let mut router = SchemaRouter::build(
801            &collection,
802            // Classifier with no generic_json: only ECS recognized, everything
803            // else is unknown.
804            SchemaClassifier::new(vec![]),
805            plan,
806            vec![vec![]],
807            CorrelationConfig::default(),
808            false,
809            MatchDetailLevel::Off,
810            None,
811            false,
812        )
813        .unwrap();
814
815        let native = json!({"CommandLine": "cmd /c whoami"});
816        let r = router.route(&JsonEvent::borrow(&native));
817        assert_eq!(r.schema, None);
818        assert_eq!(r.outcome, RouteOutcome::Dropped);
819        assert!(r.results.is_empty());
820    }
821
822    #[test]
823    fn schema_derived_logsource_prunes_cross_product_rules() {
824        // A Windows rule and a Linux rule that both match the same CommandLine.
825        let rules = r#"
826title: Win whoami
827id: win-whoami
828logsource:
829    category: process_creation
830    product: windows
831detection:
832    selection:
833        CommandLine|contains: whoami
834    condition: selection
835level: high
836---
837title: Linux whoami
838id: linux-whoami
839logsource:
840    category: process_creation
841    product: linux
842detection:
843    selection:
844        CommandLine|contains: whoami
845    condition: selection
846level: high
847"#;
848        let collection = parse_sigma_yaml(rules).unwrap();
849        // A flat Sysmon event with no explicit `product` field. It classifies
850        // as `sysmon`, whose built-in implied logsource is product: windows.
851        let event = json!({
852            "EventID": 1,
853            "ProcessGuid": "{abc}",
854            "Image": "C:/Windows/System32/cmd.exe",
855            "CommandLine": "cmd /c whoami"
856        });
857
858        // Without an extractor, no pruning: both rules fire.
859        let mut plain = SchemaRouter::build(
860            &collection,
861            SchemaClassifier::builtin(),
862            plan(&[]),
863            vec![vec![]],
864            CorrelationConfig::default(),
865            false,
866            MatchDetailLevel::Off,
867            None,
868            false,
869        )
870        .unwrap();
871        let r = plain.route(&JsonEvent::borrow(&event));
872        assert_eq!(r.schema.as_deref(), Some("sysmon"));
873        assert_eq!(r.results.len(), 2, "no pruning without an extractor");
874
875        // With an extractor, the schema-derived product (windows) prunes the
876        // Linux rule while keeping the Windows rule, even though the event
877        // carries no explicit product field.
878        let mut pruned = SchemaRouter::build(
879            &collection,
880            SchemaClassifier::builtin(),
881            plan(&[]),
882            vec![vec![]],
883            CorrelationConfig::default(),
884            false,
885            MatchDetailLevel::Off,
886            Some(LogSourceExtractor::new()),
887            false,
888        )
889        .unwrap();
890        let r = pruned.route(&JsonEvent::borrow(&event));
891        assert_eq!(r.schema.as_deref(), Some("sysmon"));
892        assert_eq!(
893            r.results.len(),
894            1,
895            "schema-derived product prunes the Linux rule"
896        );
897        assert_eq!(pruned.logsource_pruned_total(), 1);
898
899        // The static per-schema summary reflects the same eligibility: for the
900        // sysmon schema (product: windows) the Linux rule is pruned and the
901        // Windows rule stays eligible. Cross-platform schemas are absent, and
902        // the summary is empty without an extractor.
903        let summary = pruned.schema_pruning_summary();
904        let sysmon = summary
905            .iter()
906            .find(|s| s.schema == "sysmon")
907            .expect("sysmon in summary");
908        assert_eq!(sysmon.eligible, 1);
909        assert_eq!(sysmon.pruned, 1);
910        assert!(!summary.iter().any(|s| s.schema == "ecs"));
911        assert!(plain.schema_pruning_summary().is_empty());
912    }
913
914    #[test]
915    fn partition_rules_compiles_only_applicable_rules_per_set() {
916        // Windows, Linux, and a product-less rule that all match `whoami`.
917        let rules = r#"
918title: Win whoami
919id: win-whoami
920logsource:
921    category: process_creation
922    product: windows
923detection:
924    selection:
925        CommandLine|contains: whoami
926    condition: selection
927level: high
928---
929title: Linux whoami
930id: linux-whoami
931logsource:
932    category: process_creation
933    product: linux
934detection:
935    selection:
936        CommandLine|contains: whoami
937    condition: selection
938level: high
939---
940title: Any whoami
941id: any-whoami
942logsource:
943    category: process_creation
944detection:
945    selection:
946        CommandLine|contains: whoami
947    condition: selection
948level: high
949"#;
950        let collection = parse_sigma_yaml(rules).unwrap();
951        // Bind sysmon (implied product: windows) to a non-default pipeline-set
952        // (a no-op field mapping so the set differs from the default set).
953        let passthrough = parse_pipeline(
954            "name: passthrough\npriority: 10\ntransformations:\n  - id: noop\n    type: field_name_mapping\n    mapping:\n      __unused_a: __unused_b\n",
955        )
956        .unwrap();
957        let plan = plan(&[("sysmon", &["passthrough"])]);
958
959        let router = SchemaRouter::build(
960            &collection,
961            SchemaClassifier::builtin(),
962            plan,
963            vec![vec![], vec![passthrough]],
964            CorrelationConfig::default(),
965            false,
966            MatchDetailLevel::Off,
967            None,
968            true, // partition rules
969        )
970        .unwrap();
971
972        // Default set keeps all 3; the sysmon set drops the Linux rule and
973        // keeps the Windows and product-less rules.
974        assert_eq!(router.engine_rule_counts(), vec![3, 2]);
975    }
976
977    #[test]
978    fn partition_rules_off_keeps_full_ruleset() {
979        let rules = r#"
980title: Win whoami
981id: win-whoami
982logsource:
983    product: windows
984detection:
985    selection:
986        CommandLine|contains: whoami
987    condition: selection
988---
989title: Linux whoami
990id: linux-whoami
991logsource:
992    product: linux
993detection:
994    selection:
995        CommandLine|contains: whoami
996    condition: selection
997"#;
998        let collection = parse_sigma_yaml(rules).unwrap();
999        let passthrough = parse_pipeline(
1000            "name: passthrough\npriority: 10\ntransformations:\n  - id: noop\n    type: field_name_mapping\n    mapping:\n      __unused_a: __unused_b\n",
1001        )
1002        .unwrap();
1003        let plan = plan(&[("sysmon", &["passthrough"])]);
1004        let router = SchemaRouter::build(
1005            &collection,
1006            SchemaClassifier::builtin(),
1007            plan,
1008            vec![vec![], vec![passthrough]],
1009            CorrelationConfig::default(),
1010            false,
1011            MatchDetailLevel::Off,
1012            None,
1013            false, // partitioning off
1014        )
1015        .unwrap();
1016        assert_eq!(router.engine_rule_counts(), vec![2, 2]);
1017    }
1018}