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