1use 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#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct SchemaPruning {
48 pub schema: String,
50 pub eligible: usize,
52 pub pruned: usize,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum RouteOutcome {
59 Evaluated,
61 EvaluatedUnknown,
64 Dropped,
66 Errored,
68}
69
70pub struct RouteResult {
72 pub results: ProcessResult,
74 pub schema: Option<String>,
76 pub outcome: RouteOutcome,
78}
79
80fn 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
98enum Routed1 {
100 Skip,
102 Eval {
104 set: usize,
105 detections: Vec<IdentifiedEvaluation>,
106 },
107}
108
109fn 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
119fn 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
134fn 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
165fn 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
193pub struct SchemaRouter<L = LogSourceExtractor> {
201 classifier: SchemaClassifier,
202 plan: RoutingPlan,
203 engines: Vec<Engine>,
205 field_maps: Vec<HashMap<String, Vec<String>>>,
207 correlation: Option<CorrelationEngine>,
209 logsource_extractor: Option<L>,
213}
214
215impl SchemaRouter {
216 #[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 #[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 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 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 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 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 pub fn on_unknown(&self) -> OnUnknown {
359 self.plan.on_unknown()
360 }
361
362 pub fn has_correlations(&self) -> bool {
364 self.correlation.is_some()
365 }
366
367 pub fn detection_rule_count(&self) -> usize {
372 self.engines.first().map(|e| e.rule_count()).unwrap_or(0)
373 }
374
375 pub fn engine_rule_counts(&self) -> Vec<usize> {
379 self.engines.iter().map(Engine::rule_count).collect()
380 }
381
382 pub fn logsource_pruned_total(&self) -> u64 {
385 self.engines
386 .iter()
387 .map(Engine::logsource_pruned_total)
388 .sum()
389 }
390
391 pub fn logsource_absent_total(&self) -> u64 {
394 self.engines
395 .iter()
396 .map(Engine::logsource_absent_total)
397 .sum()
398 }
399
400 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 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 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 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 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 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 pub fn export_state(&self) -> Option<CorrelationSnapshot> {
493 self.correlation.as_ref().map(|c| c.export_state())
494 }
495
496 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 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 pub fn import_state(&mut self, snapshot: CorrelationSnapshot) -> bool {
515 self.import_state_detailed(snapshot).is_some()
516 }
517
518 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 bindings: vec![],
888 };
889 let plan = RoutingPlan::from_config(&config);
890 let mut router = SchemaRouter::build(
891 &collection,
892 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 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 let event = json!({
942 "EventID": 1,
943 "ProcessGuid": "{abc}",
944 "Image": "C:/Windows/System32/cmd.exe",
945 "CommandLine": "cmd /c whoami"
946 });
947
948 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 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 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 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 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, )
1060 .unwrap();
1061
1062 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, )
1105 .unwrap();
1106 assert_eq!(router.engine_rule_counts(), vec![2, 2]);
1107 }
1108}