Skip to main content

rsigma_eval/
rulesets.rs

1//! Several named rulesets evaluated side by side.
2//!
3//! Each [`RulesetUnit`] owns its own compiled engine, pipelines, and
4//! correlation state. Units never share a router or a correlation store:
5//! routing answers "which one pipeline set does this event belong to", while a
6//! ruleset fan-out sends an event to several independent rule sets, and a
7//! shared correlation store would double-count a rule that appears in more than
8//! one ruleset.
9//!
10//! [`RulesetEngines`] fans an event out to the units that accept it, stamps the
11//! ruleset name on every result, and keeps per-unit skip and route counters.
12
13use std::collections::{BTreeMap, HashMap};
14use std::sync::Arc;
15use std::sync::atomic::{AtomicU64, Ordering};
16
17use thiserror::Error;
18
19use crate::SchemaClassifier;
20use crate::correlation_engine::CorrelationEngine;
21use crate::event::Event;
22use crate::fields::RuleFieldSet;
23use crate::result::EvaluationResult;
24use crate::router::{RouteOutcome, SchemaRouter};
25use crate::rule_metadata::RuleMetadataLookup;
26use crate::tenant::{TenantId, tenant_at};
27use crate::{CorrelationSnapshot, CorrelationStateSnapshot, Engine, ProcessResult};
28
29/// The compiled engine behind one ruleset unit.
30#[non_exhaustive]
31pub enum UnitEngine {
32    /// A stateless detection engine.
33    Detection(Box<Engine>),
34    /// A stateful detection and correlation engine.
35    Correlation(Box<CorrelationEngine>),
36    /// A schema router over one pipeline set.
37    Routed(Box<SchemaRouter>),
38}
39
40impl UnitEngine {
41    /// Set global `include_event` on the engine. Takes effect for the next
42    /// event evaluated.
43    pub fn set_include_event(&mut self, include: bool) {
44        match self {
45            UnitEngine::Detection(engine) => engine.set_include_event(include),
46            UnitEngine::Correlation(engine) => engine.set_include_event(include),
47            UnitEngine::Routed(router) => router.set_include_event(include),
48        }
49    }
50}
51
52/// One named ruleset unit: its name, schema bindings, engine, and the field
53/// set its rules reference after pipelines.
54pub struct RulesetUnit {
55    /// Ruleset name, stamped on every result the unit produces.
56    pub name: Arc<str>,
57    /// Schema names that admit an event to this unit. Empty means every event.
58    pub when_schemas: Vec<String>,
59    /// Tenant ids admitted to this unit. Empty means every tenant.
60    pub tenants: Vec<TenantId>,
61    /// The compiled engine for this unit.
62    pub engine: UnitEngine,
63    /// Post-pipeline field set for this unit's collection.
64    pub field_set: RuleFieldSet,
65}
66
67/// One ruleset's loaded rule counts and schema bindings, for status and stats.
68#[derive(Debug, Clone, serde::Serialize)]
69pub struct RulesetStats {
70    /// Ruleset name.
71    pub name: Arc<str>,
72    /// Loaded detection rules.
73    pub detection_rules: usize,
74    /// Loaded correlation rules.
75    pub correlation_rules: usize,
76    /// Schema names that admit an event to this ruleset.
77    pub when_schemas: Vec<String>,
78    /// Tenant ids admitted to this ruleset. Empty means every tenant.
79    #[serde(skip_serializing_if = "Vec::is_empty")]
80    pub tenants: Vec<TenantId>,
81}
82
83/// Routing outcomes counted across a single routed unit.
84#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
85pub struct RouteCounts {
86    /// Events with an unrecognized schema that were evaluated against the
87    /// default set.
88    pub unknown: u64,
89    /// Events dropped without evaluation.
90    pub dropped: u64,
91    /// Events dropped and flagged as an error.
92    pub errored: u64,
93}
94
95/// Introspection of one ruleset's correlation state, as returned per ruleset
96/// by [`RulesetEngines::introspect`].
97pub type CorrelationIntrospection = CorrelationStateSnapshot;
98
99/// Construction errors for [`RulesetEngines`].
100#[derive(Debug, Error)]
101#[non_exhaustive]
102pub enum RulesetEnginesError {
103    /// No rulesets were supplied.
104    #[error("at least one ruleset is required")]
105    Empty,
106    /// Two rulesets share a name.
107    #[error("duplicate ruleset name '{0}'")]
108    DuplicateName(String),
109    /// A routed unit was supplied alongside another unit.
110    #[error("schema routing supports exactly one ruleset, found {0}")]
111    RoutedWithOthers(usize),
112    /// A routed unit carries a `when` binding.
113    #[error("ruleset '{0}' cannot use `when` with schema routing")]
114    RoutedWithWhen(String),
115    /// A unit carries `when` but no classifier is configured.
116    #[error("ruleset '{0}' has `when` but no schema classifier is configured")]
117    WhenWithoutClassifier(String),
118    /// A `when` schema is not known to the classifier.
119    #[error(
120        "ruleset '{name}' references unknown schema '{schema}'; known schemas: {}",
121        known.join(", ")
122    )]
123    UnknownSchema {
124        /// Ruleset name.
125        name: String,
126        /// Unknown schema name.
127        schema: String,
128        /// Known schema names.
129        known: Vec<String>,
130    },
131}
132
133/// A fan-out over independent named rulesets.
134pub struct RulesetEngines {
135    units: Vec<RulesetUnit>,
136    classifier: Option<Arc<SchemaClassifier>>,
137    skipped: Vec<AtomicU64>,
138    unreported_skips: Vec<AtomicU64>,
139    route_counts: RouteCounts,
140}
141
142impl RulesetEngines {
143    /// Build a fan-out from units and an optional schema classifier.
144    ///
145    /// Validation fails on an empty list, duplicate names, a routed unit with
146    /// other units or with `when`, `when` without a classifier, and `when`
147    /// schemas the classifier does not know.
148    pub fn new(
149        units: Vec<RulesetUnit>,
150        classifier: Option<Arc<SchemaClassifier>>,
151    ) -> Result<Self, RulesetEnginesError> {
152        if units.is_empty() {
153            return Err(RulesetEnginesError::Empty);
154        }
155
156        let mut names = std::collections::HashSet::new();
157        for unit in &units {
158            if !names.insert(unit.name.clone()) {
159                return Err(RulesetEnginesError::DuplicateName(unit.name.to_string()));
160            }
161        }
162
163        if let Some(unit) = units
164            .iter()
165            .find(|unit| matches!(unit.engine, UnitEngine::Routed(_)))
166        {
167            if units.len() != 1 {
168                return Err(RulesetEnginesError::RoutedWithOthers(units.len()));
169            }
170            if !unit.when_schemas.is_empty() {
171                return Err(RulesetEnginesError::RoutedWithWhen(unit.name.to_string()));
172            }
173        }
174
175        if units.iter().any(|unit| !unit.when_schemas.is_empty()) {
176            let Some(classifier) = &classifier else {
177                let name = units
178                    .iter()
179                    .find(|unit| !unit.when_schemas.is_empty())
180                    .map(|unit| unit.name.to_string())
181                    .unwrap_or_default();
182                return Err(RulesetEnginesError::WhenWithoutClassifier(name));
183            };
184            let known: Vec<String> = classifier
185                .schema_names()
186                .into_iter()
187                .map(str::to_string)
188                .collect();
189            for unit in &units {
190                for schema in &unit.when_schemas {
191                    if !known.iter().any(|known| known == schema) {
192                        return Err(RulesetEnginesError::UnknownSchema {
193                            name: unit.name.to_string(),
194                            schema: schema.clone(),
195                            known: known.clone(),
196                        });
197                    }
198                }
199            }
200        }
201
202        let skipped = units.iter().map(|_| AtomicU64::new(0)).collect::<Vec<_>>();
203        let unreported_skips = units.iter().map(|_| AtomicU64::new(0)).collect::<Vec<_>>();
204
205        Ok(Self {
206            units,
207            classifier,
208            skipped,
209            unreported_skips,
210            route_counts: RouteCounts::default(),
211        })
212    }
213
214    /// The configured units, in declaration order.
215    pub fn units(&self) -> &[RulesetUnit] {
216        &self.units
217    }
218
219    /// Set global `include_event` on every unit's engine. Takes effect for
220    /// the next event evaluated.
221    pub fn set_include_event(&mut self, include: bool) {
222        for unit in &mut self.units {
223            unit.engine.set_include_event(include);
224        }
225    }
226
227    /// Loaded rule counts and schema bindings for every unit.
228    pub fn ruleset_stats(&self) -> Vec<RulesetStats> {
229        self.units
230            .iter()
231            .map(|unit| RulesetStats {
232                name: unit.name.clone(),
233                detection_rules: unit_detection_rule_count(unit),
234                correlation_rules: unit_correlation_rule_count(unit),
235                when_schemas: unit.when_schemas.clone(),
236                tenants: unit.tenants.clone(),
237            })
238            .collect()
239    }
240
241    /// Cumulative events refused by each unit's `when` binding.
242    pub fn skipped_totals(&self) -> Vec<(Arc<str>, u64)> {
243        self.units
244            .iter()
245            .zip(&self.skipped)
246            .map(|(unit, skipped)| (unit.name.clone(), skipped.load(Ordering::Relaxed)))
247            .collect()
248    }
249
250    /// Events refused by each unit's `when` binding since the previous call.
251    ///
252    /// Each call drains the counters, so concurrent callers report every skip
253    /// exactly once. [`Self::skipped_totals`] keeps counting cumulatively.
254    pub fn take_skipped(&self) -> Vec<(Arc<str>, u64)> {
255        self.units
256            .iter()
257            .zip(&self.unreported_skips)
258            .map(|(unit, pending)| (unit.name.clone(), pending.swap(0, Ordering::Relaxed)))
259            .collect()
260    }
261
262    /// Routing outcomes counted by [`Self::process_event`] for a routed unit.
263    ///
264    /// The batch methods do not update these counts; a routed unit reports its
265    /// outcomes through its router on those paths.
266    pub fn route_counts(&self) -> RouteCounts {
267        self.route_counts
268    }
269
270    /// Summed detection rule count across units.
271    pub fn detection_rule_count(&self) -> usize {
272        self.units.iter().map(unit_detection_rule_count).sum()
273    }
274
275    /// Summed correlation rule count across units.
276    pub fn correlation_rule_count(&self) -> usize {
277        self.units.iter().map(unit_correlation_rule_count).sum()
278    }
279
280    /// Summed live correlation state entries across units.
281    pub fn state_entries(&self) -> usize {
282        self.units
283            .iter()
284            .map(|unit| match &unit.engine {
285                UnitEngine::Detection(_) => 0,
286                UnitEngine::Correlation(engine) => engine.state_count(),
287                UnitEngine::Routed(router) => router.state_count(),
288            })
289            .sum()
290    }
291
292    /// Whether concurrent stateless detection is available.
293    pub fn allows_concurrent_detection(&self) -> bool {
294        self.units
295            .iter()
296            .all(|unit| matches!(unit.engine, UnitEngine::Detection(_)))
297    }
298
299    /// Static per-schema logsource pruning summary, summed over routed units.
300    pub fn schema_pruning_summary(&self) -> Vec<crate::SchemaPruning> {
301        let mut out = Vec::new();
302        for unit in &self.units {
303            if let UnitEngine::Routed(router) = &unit.engine {
304                out.extend(router.schema_pruning_summary());
305            }
306        }
307        out
308    }
309
310    /// Total rule candidates pruned by logsource across units.
311    pub fn logsource_pruned_total(&self) -> u64 {
312        self.units
313            .iter()
314            .map(|unit| match &unit.engine {
315                UnitEngine::Detection(engine) => engine.logsource_pruned_total(),
316                UnitEngine::Correlation(engine) => engine.logsource_pruned_total(),
317                UnitEngine::Routed(router) => router.logsource_pruned_total(),
318            })
319            .sum()
320    }
321
322    /// Total evaluate calls with no extractable event logsource across units.
323    pub fn logsource_absent_total(&self) -> u64 {
324        self.units
325            .iter()
326            .map(|unit| match &unit.engine {
327                UnitEngine::Detection(engine) => engine.logsource_absent_total(),
328                UnitEngine::Correlation(engine) => engine.logsource_absent_total(),
329                UnitEngine::Routed(router) => router.logsource_absent_total(),
330            })
331            .sum()
332    }
333
334    /// Whether any unit carries correlation state.
335    pub fn has_correlations(&self) -> bool {
336        self.units.iter().any(|unit| match &unit.engine {
337            UnitEngine::Detection(_) => false,
338            UnitEngine::Correlation(_) => true,
339            UnitEngine::Routed(router) => router.has_correlations(),
340        })
341    }
342
343    /// Union of every unit's post-pipeline rule field set.
344    pub fn rule_field_set(&self) -> RuleFieldSet {
345        let mut set = RuleFieldSet::default();
346        for unit in &self.units {
347            set.extend(unit.field_set.clone());
348        }
349        set
350    }
351
352    /// Resolve a rule key across every unit. Differently overlaid copies of the
353    /// same rule report [`RuleMetadataLookup::Ambiguous`].
354    pub fn rule_metadata(&self, key: &str) -> RuleMetadataLookup {
355        let mut variants = Vec::new();
356        for unit in &self.units {
357            match &unit.engine {
358                UnitEngine::Detection(engine) => engine.collect_rule_metadata(key, &mut variants),
359                UnitEngine::Correlation(engine) => engine.collect_rule_metadata(key, &mut variants),
360                UnitEngine::Routed(router) => {
361                    variants.extend(router.rule_metadata(key).variants().iter().cloned())
362                }
363            }
364        }
365        RuleMetadataLookup::from_variants(variants)
366    }
367
368    /// Process one event through every unit that accepts it.
369    pub fn process_event<E: Event>(&mut self, event: &E) -> ProcessResult {
370        self.process_event_for_tenant(event, None)
371    }
372
373    /// Process one event as `tenant` through every unit that accepts it.
374    ///
375    /// A unit bound to tenants accepts only events carrying one of them; an
376    /// unbound unit accepts every tenant.
377    pub fn process_event_for_tenant<E: Event>(
378        &mut self,
379        event: &E,
380        tenant: Option<&TenantId>,
381    ) -> ProcessResult {
382        let accepted = self.acceptance(event, tenant);
383        let mut results = Vec::new();
384        let units = &mut self.units;
385        for (index, unit) in units.iter_mut().enumerate() {
386            if !accepted[index] {
387                count_skip(&self.skipped, &self.unreported_skips, index);
388                continue;
389            }
390            let mut batch = match &mut unit.engine {
391                UnitEngine::Detection(engine) => engine.evaluate(event),
392                UnitEngine::Correlation(engine) => engine.process_event_for_tenant(event, tenant),
393                UnitEngine::Routed(router) => {
394                    let routed = router.route_for_tenant(event, tenant);
395                    match routed.outcome {
396                        RouteOutcome::Evaluated => {}
397                        RouteOutcome::EvaluatedUnknown => self.route_counts.unknown += 1,
398                        RouteOutcome::Dropped => self.route_counts.dropped += 1,
399                        RouteOutcome::Errored => self.route_counts.errored += 1,
400                    }
401                    routed.results
402                }
403            };
404            stamp_results(&unit.name, &mut batch);
405            results.extend(batch);
406        }
407        results
408    }
409
410    /// Process a batch through every unit that accepts each event.
411    ///
412    /// Results are scattered back to their event positions in unit declaration
413    /// order.
414    pub fn process_batch<E: Event + Sync>(&mut self, events: &[&E]) -> Vec<ProcessResult> {
415        self.process_batch_for_tenants(events, &[])
416    }
417
418    /// Process a batch with a parallel tenant slice, scattering results back
419    /// to their event positions.
420    ///
421    /// `tenants` is empty (every event untenanted) or exactly parallel to
422    /// `events`; any other length logs and returns empty results.
423    pub fn process_batch_for_tenants<E: Event + Sync>(
424        &mut self,
425        events: &[&E],
426        tenants: &[Option<TenantId>],
427    ) -> Vec<ProcessResult> {
428        if !tenants.is_empty() && tenants.len() != events.len() {
429            debug_assert!(
430                false,
431                "tenants must be empty or parallel to events: {} tenants for {} events",
432                tenants.len(),
433                events.len()
434            );
435            log::error!(
436                "tenant slice length mismatch: {} tenants for {} events; returning empty results",
437                tenants.len(),
438                events.len()
439            );
440            return vec![ProcessResult::new(); events.len()];
441        }
442
443        let accepted = self.batch_acceptance(events, tenants);
444
445        let mut output: Vec<ProcessResult> = vec![Vec::new(); events.len()];
446        let units = &mut self.units;
447        for (unit_index, unit) in units.iter_mut().enumerate() {
448            let indices: Vec<usize> = accepted[unit_index]
449                .iter()
450                .enumerate()
451                .filter_map(|(event_index, accepted)| accepted.then_some(event_index))
452                .collect();
453            if indices.is_empty() {
454                continue;
455            }
456            let sub_events: Vec<&E> = indices.iter().map(|index| events[*index]).collect();
457            let sub_tenants: Vec<Option<TenantId>> = if tenants.is_empty() {
458                Vec::new()
459            } else {
460                indices
461                    .iter()
462                    .map(|index| tenants[*index].clone())
463                    .collect()
464            };
465            let results = match &mut unit.engine {
466                UnitEngine::Detection(engine) => engine.evaluate_batch(&sub_events),
467                UnitEngine::Correlation(engine) => {
468                    engine.process_batch_for_tenants(&sub_events, &sub_tenants)
469                }
470                UnitEngine::Routed(router) => {
471                    router.process_batch_for_tenants(&sub_events, &sub_tenants)
472                }
473            };
474            for (sub_index, mut batch) in results.into_iter().enumerate() {
475                stamp_results(&unit.name, &mut batch);
476                output[indices[sub_index]].extend(batch);
477            }
478        }
479        output
480    }
481
482    /// Stateless detection for every unit, when every unit is detection-only.
483    ///
484    /// Returns `None` when any unit carries correlation state or a router.
485    pub fn detect_batch<E: Event + Sync>(&self, events: &[&E]) -> Option<Vec<ProcessResult>> {
486        self.detect_batch_for_tenants(events, &[])
487    }
488
489    /// Like [`detect_batch`](Self::detect_batch) with a parallel tenant slice.
490    pub fn detect_batch_for_tenants<E: Event + Sync>(
491        &self,
492        events: &[&E],
493        tenants: &[Option<TenantId>],
494    ) -> Option<Vec<ProcessResult>> {
495        if self
496            .units
497            .iter()
498            .any(|unit| !matches!(unit.engine, UnitEngine::Detection(_)))
499        {
500            return None;
501        }
502        if !tenants.is_empty() && tenants.len() != events.len() {
503            debug_assert!(
504                false,
505                "tenants must be empty or parallel to events: {} tenants for {} events",
506                tenants.len(),
507                events.len()
508            );
509            log::error!(
510                "tenant slice length mismatch: {} tenants for {} events; returning empty results",
511                tenants.len(),
512                events.len()
513            );
514            return Some(vec![ProcessResult::new(); events.len()]);
515        }
516
517        let accepted = self.batch_acceptance(events, tenants);
518
519        let mut output: Vec<ProcessResult> = vec![Vec::new(); events.len()];
520        for (unit_index, unit) in self.units.iter().enumerate() {
521            let UnitEngine::Detection(engine) = &unit.engine else {
522                continue;
523            };
524            let indices: Vec<usize> = accepted[unit_index]
525                .iter()
526                .enumerate()
527                .filter_map(|(event_index, accepted)| accepted.then_some(event_index))
528                .collect();
529            if indices.is_empty() {
530                continue;
531            }
532            let sub_events: Vec<&E> = indices.iter().map(|index| events[*index]).collect();
533            let results = engine.evaluate_batch(&sub_events);
534            for (sub_index, mut batch) in results.into_iter().enumerate() {
535                stamp_results(&unit.name, &mut batch);
536                output[indices[sub_index]].extend(batch);
537            }
538        }
539        Some(output)
540    }
541
542    /// Entries evicted because a tenant hit its correlation quota since the
543    /// previous call, summed across units.
544    pub fn take_tenant_quota_evictions(&mut self) -> u64 {
545        self.units
546            .iter_mut()
547            .map(|unit| match &mut unit.engine {
548                UnitEngine::Detection(_) => 0,
549                UnitEngine::Correlation(engine) => engine.take_tenant_quota_evictions(),
550                UnitEngine::Routed(router) => router.take_tenant_quota_evictions(),
551            })
552            .sum()
553    }
554
555    /// Events skipped by `require_tenant` since the previous call, summed across
556    /// units.
557    pub fn take_untenanted_skipped(&mut self) -> u64 {
558        self.units
559            .iter_mut()
560            .map(|unit| match &mut unit.engine {
561                UnitEngine::Detection(_) => 0,
562                UnitEngine::Correlation(engine) => engine.take_untenanted_skipped(),
563                UnitEngine::Routed(router) => router.take_untenanted_skipped(),
564            })
565            .sum()
566    }
567
568    /// Export per-ruleset correlation state in one snapshot.
569    pub fn export_state(&self) -> CorrelationSnapshot {
570        let mut rulesets = BTreeMap::new();
571        for unit in &self.units {
572            let snapshot = match &unit.engine {
573                UnitEngine::Detection(_) => None,
574                UnitEngine::Correlation(engine) => Some(engine.export_state()),
575                UnitEngine::Routed(router) => router.export_state(),
576            };
577            if let Some(snapshot) = snapshot {
578                rulesets.insert(unit.name.to_string(), snapshot);
579            }
580        }
581        CorrelationSnapshot {
582            version: crate::correlation_engine::SNAPSHOT_VERSION,
583            windows: HashMap::new(),
584            last_alert: HashMap::new(),
585            event_buffers: HashMap::new(),
586            event_ref_buffers: HashMap::new(),
587            tenants: Vec::new(),
588            rulesets,
589        }
590    }
591
592    /// Import per-ruleset correlation state by name. Names that no longer exist
593    /// are dropped.
594    ///
595    /// A snapshot exported by a single engine imports into the only unit.
596    /// Returns `false` when the version is incompatible, when a single-engine
597    /// snapshot meets several units, or when any unit rejects its state.
598    pub fn import_state(&mut self, snapshot: &CorrelationSnapshot) -> bool {
599        self.import_state_detailed(snapshot).is_some()
600    }
601
602    /// Like [`import_state`](Self::import_state), returning the summed counts
603    /// of restored and discarded entries across units.
604    pub fn import_state_detailed(
605        &mut self,
606        snapshot: &CorrelationSnapshot,
607    ) -> Option<crate::ImportStats> {
608        if !matches!(snapshot.version, 1 | 2) {
609            return None;
610        }
611        if snapshot.rulesets.is_empty() {
612            if !snapshot.has_collection_state() {
613                return Some(crate::ImportStats::default());
614            }
615            let [unit] = self.units.as_mut_slice() else {
616                return None;
617            };
618            return import_unit_state_detailed(unit, snapshot);
619        }
620        if snapshot.has_collection_state() {
621            return None;
622        }
623        let mut units: HashMap<String, &mut RulesetUnit> = self
624            .units
625            .iter_mut()
626            .map(|unit| (unit.name.to_string(), unit))
627            .collect();
628        // Import every unit that fits, so one bad unit does not cost the
629        // others their state, then report the failure.
630        let mut stats = crate::ImportStats::default();
631        let mut failed = false;
632        for (name, state) in &snapshot.rulesets {
633            let Some(unit) = units.get_mut(name.as_str()) else {
634                continue;
635            };
636            match import_unit_state_detailed(unit, state) {
637                Some(unit_stats) => stats += unit_stats,
638                None => failed = true,
639            }
640        }
641        (!failed).then_some(stats)
642    }
643
644    /// Introspect correlation state for every unit that has it.
645    pub fn introspect(&self) -> BTreeMap<String, CorrelationIntrospection> {
646        self.introspect_filtered(None, None)
647    }
648
649    /// Introspect correlation state with optional id and group filters.
650    pub fn introspect_filtered(
651        &self,
652        id: Option<&str>,
653        group: Option<&str>,
654    ) -> BTreeMap<String, CorrelationIntrospection> {
655        self.introspect_filtered_for_tenant(id, group, None)
656    }
657
658    /// Like [`introspect_filtered`](Self::introspect_filtered), keeping only
659    /// groups owned by `tenant` when it is set.
660    pub fn introspect_filtered_for_tenant(
661        &self,
662        id: Option<&str>,
663        group: Option<&str>,
664        tenant: Option<&TenantId>,
665    ) -> BTreeMap<String, CorrelationIntrospection> {
666        let mut out = BTreeMap::new();
667        for unit in &self.units {
668            let snapshot = match &unit.engine {
669                UnitEngine::Detection(_) => None,
670                UnitEngine::Correlation(engine) => {
671                    Some(engine.introspect_for_tenant(id, group, tenant))
672                }
673                UnitEngine::Routed(router) => {
674                    router.correlation_introspect_for_tenant(id, group, tenant)
675                }
676            };
677            if let Some(snapshot) = snapshot {
678                out.insert(unit.name.to_string(), snapshot);
679            }
680        }
681        out
682    }
683
684    /// Per-unit acceptance for a batch, classifying each event once and
685    /// counting skips.
686    fn batch_acceptance<E: Event>(
687        &self,
688        events: &[&E],
689        tenants: &[Option<TenantId>],
690    ) -> Vec<Vec<bool>> {
691        let mut accepted = vec![Vec::with_capacity(events.len()); self.units.len()];
692        for (index, event) in events.iter().enumerate() {
693            let tenant = tenant_at(tenants, index);
694            for (unit_index, accepts) in self.acceptance(*event, tenant).into_iter().enumerate() {
695                if !accepts {
696                    count_skip(&self.skipped, &self.unreported_skips, unit_index);
697                }
698                accepted[unit_index].push(accepts);
699            }
700        }
701        accepted
702    }
703
704    fn acceptance<E: Event>(&self, event: &E, tenant: Option<&TenantId>) -> Vec<bool> {
705        let any_when = self.units.iter().any(|unit| !unit.when_schemas.is_empty());
706        let schema = if any_when {
707            self.classifier
708                .as_ref()
709                .and_then(|classifier| classifier.classify(event))
710                .map(|matched| matched.name)
711        } else {
712            None
713        };
714        self.units
715            .iter()
716            .map(|unit| {
717                let schema_ok = unit.when_schemas.is_empty()
718                    || schema
719                        .as_ref()
720                        .is_some_and(|schema| unit.when_schemas.iter().any(|name| name == schema));
721                let tenant_ok = unit.tenants.is_empty()
722                    || tenant.is_some_and(|tenant| unit.tenants.iter().any(|t| t == tenant));
723                schema_ok && tenant_ok
724            })
725            .collect()
726    }
727}
728
729fn count_skip(skipped: &[AtomicU64], unreported: &[AtomicU64], index: usize) {
730    skipped[index].fetch_add(1, Ordering::Relaxed);
731    unreported[index].fetch_add(1, Ordering::Relaxed);
732}
733
734fn import_unit_state_detailed(
735    unit: &mut RulesetUnit,
736    state: &CorrelationSnapshot,
737) -> Option<crate::ImportStats> {
738    match &mut unit.engine {
739        UnitEngine::Detection(_) => Some(crate::ImportStats::default()),
740        UnitEngine::Correlation(engine) => engine.import_state_detailed(state.clone()),
741        UnitEngine::Routed(router) => router.import_state_detailed(state.clone()),
742    }
743}
744
745fn stamp_results(name: &Arc<str>, results: &mut [EvaluationResult]) {
746    for result in results {
747        result.header.ruleset = Some(name.clone());
748    }
749}
750
751fn unit_detection_rule_count(unit: &RulesetUnit) -> usize {
752    match &unit.engine {
753        UnitEngine::Detection(engine) => engine.rule_count(),
754        UnitEngine::Correlation(engine) => engine.detection_rule_count(),
755        UnitEngine::Routed(router) => router.detection_rule_count(),
756    }
757}
758
759fn unit_correlation_rule_count(unit: &RulesetUnit) -> usize {
760    match &unit.engine {
761        UnitEngine::Detection(_) => 0,
762        UnitEngine::Correlation(engine) => engine.correlation_rule_count(),
763        UnitEngine::Routed(router) => router.correlation_rule_count(),
764    }
765}
766
767#[cfg(test)]
768mod tests {
769    use super::*;
770    use crate::{
771        CorrelationConfig, JsonEvent, MatchDetailLevel, OnUnknown, Pipeline, RoutingConfig,
772        RoutingPlan, SchemaPredicate, SchemaSignature, parse_pipeline,
773    };
774    use rsigma_parser::parse_sigma_yaml;
775
776    const DETECTION: &str = r#"
777title: Whoami
778id: whoami
779logsource:
780    category: process_creation
781    product: windows
782detection:
783    selection:
784        Image: whoami
785    condition: selection
786"#;
787
788    const CORRELATION: &str = r#"
789title: Whoami
790id: whoami
791logsource:
792    category: process_creation
793    product: windows
794detection:
795    selection:
796        Image: whoami
797    condition: selection
798---
799title: Burst
800id: burst
801correlation:
802    type: event_count
803    rules: [whoami]
804    group-by: [Image]
805    timespan: 5m
806    condition:
807        gte: 2
808"#;
809
810    fn pipeline(mapping: &str) -> Pipeline {
811        parse_pipeline(&format!(
812            "name: p\ntransformations:\n  - type: field_name_mapping\n    mapping:\n      Image: {mapping}\n"
813        ))
814        .unwrap()
815    }
816
817    fn detection_unit(name: &str, pipelines: Vec<Pipeline>) -> RulesetUnit {
818        let collection = parse_sigma_yaml(DETECTION).unwrap();
819        let mut engine = Engine::new();
820        engine.set_match_detail(MatchDetailLevel::Off);
821        for pipeline in pipelines {
822            engine.add_pipeline(pipeline);
823        }
824        engine.add_collection(&collection).unwrap();
825        RulesetUnit {
826            name: Arc::from(name),
827            when_schemas: Vec::new(),
828            tenants: Vec::new(),
829            engine: UnitEngine::Detection(Box::new(engine)),
830            field_set: RuleFieldSet::collect(&collection, &[], true),
831        }
832    }
833
834    fn correlation_unit(name: &str) -> RulesetUnit {
835        let collection = parse_sigma_yaml(CORRELATION).unwrap();
836        let mut engine = CorrelationEngine::new(CorrelationConfig::default());
837        engine.add_collection(&collection).unwrap();
838        RulesetUnit {
839            name: Arc::from(name),
840            when_schemas: Vec::new(),
841            tenants: Vec::new(),
842            engine: UnitEngine::Correlation(Box::new(engine)),
843            field_set: RuleFieldSet::collect(&collection, &[], true),
844        }
845    }
846
847    fn bound_unit(name: &str, schemas: &[&str]) -> RulesetUnit {
848        let mut unit = detection_unit(name, Vec::new());
849        unit.when_schemas = schemas.iter().map(|schema| (*schema).to_string()).collect();
850        unit
851    }
852
853    fn classifier_with(schemas: &[&str]) -> Arc<SchemaClassifier> {
854        Arc::new(SchemaClassifier::new(
855            schemas
856                .iter()
857                .map(|name| SchemaSignature {
858                    name: (*name).to_string(),
859                    predicates: vec![SchemaPredicate::FieldPresent("schema_marker".to_string())],
860                    specificity: 10,
861                })
862                .collect(),
863        ))
864    }
865
866    fn routed_engine(on_unknown: OnUnknown) -> RulesetEngines {
867        let collection = parse_sigma_yaml(DETECTION).unwrap();
868        let config = RoutingConfig {
869            on_unknown,
870            ..Default::default()
871        };
872        let plan = RoutingPlan::from_config(&config);
873        let router = SchemaRouter::build(
874            &collection,
875            SchemaClassifier::new(Vec::new()),
876            plan,
877            vec![Vec::new()],
878            CorrelationConfig::default(),
879            false,
880            MatchDetailLevel::Off,
881            None,
882            false,
883        )
884        .unwrap();
885        RulesetEngines::new(
886            vec![RulesetUnit {
887                name: Arc::from("routed"),
888                when_schemas: Vec::new(),
889                tenants: Vec::new(),
890                engine: UnitEngine::Routed(Box::new(router)),
891                field_set: RuleFieldSet::collect(&collection, &[], true),
892            }],
893            None,
894        )
895        .unwrap()
896    }
897
898    #[test]
899    fn two_units_with_different_pipelines_both_fire_in_order() {
900        let mut engines = RulesetEngines::new(
901            vec![
902                detection_unit("first", vec![pipeline("process.executable")]),
903                detection_unit("second", vec![pipeline("process.path")]),
904            ],
905            None,
906        )
907        .unwrap();
908        let value = serde_json::json!({
909            "process.executable": "whoami",
910            "process.path": "whoami",
911        });
912        let event = JsonEvent::borrow(&value);
913        let results = engines.process_event(&event);
914        assert_eq!(results.len(), 2);
915        assert_eq!(results[0].header.ruleset.as_deref(), Some("first"));
916        assert_eq!(results[1].header.ruleset.as_deref(), Some("second"));
917    }
918
919    #[test]
920    fn when_routes_only_to_the_bound_unit() {
921        let classifier = classifier_with(&["aws_cloudtrail"]);
922        let mut engines = RulesetEngines::new(
923            vec![
924                detection_unit("unbound", Vec::new()),
925                bound_unit("cloud", &["aws_cloudtrail"]),
926            ],
927            Some(classifier),
928        )
929        .unwrap();
930        let cloud_value = serde_json::json!({
931            "schema_marker": true,
932            "Image": "whoami",
933        });
934        let cloud = JsonEvent::borrow(&cloud_value);
935        let plain_value = serde_json::json!({"Image": "whoami"});
936        let plain = JsonEvent::borrow(&plain_value);
937
938        let cloud_results = engines.process_event(&cloud);
939        assert_eq!(cloud_results.len(), 2);
940        assert_eq!(cloud_results[0].header.ruleset.as_deref(), Some("unbound"));
941        assert_eq!(cloud_results[1].header.ruleset.as_deref(), Some("cloud"));
942
943        let plain_results = engines.process_event(&plain);
944        assert_eq!(plain_results.len(), 1);
945        assert_eq!(plain_results[0].header.ruleset.as_deref(), Some("unbound"));
946
947        let skipped = engines.skipped_totals();
948        assert_eq!(skipped[0].1, 0);
949        assert_eq!(skipped[1].1, 1);
950
951        let taken = engines.take_skipped();
952        assert_eq!(taken[1].1, 1);
953        assert_eq!(engines.take_skipped()[1].1, 0);
954        assert_eq!(engines.skipped_totals()[1].1, 1);
955    }
956
957    /// Counts classifier probes of `schema_marker`; detection never reads it.
958    struct CountingEvent<'a> {
959        inner: JsonEvent<'a>,
960        probes: &'a std::sync::atomic::AtomicUsize,
961    }
962
963    impl Event for CountingEvent<'_> {
964        fn get_field(&self, path: &str) -> Option<crate::event::EventValue<'_>> {
965            if path == "schema_marker" {
966                self.probes.fetch_add(1, Ordering::Relaxed);
967            }
968            self.inner.get_field(path)
969        }
970
971        fn any_string_value(&self, pred: &dyn Fn(&str) -> bool) -> bool {
972            self.inner.any_string_value(pred)
973        }
974
975        fn all_string_values(&self) -> Vec<std::borrow::Cow<'_, str>> {
976            self.inner.all_string_values()
977        }
978
979        fn to_json(&self) -> serde_json::Value {
980            self.inner.to_json()
981        }
982    }
983
984    #[test]
985    fn classification_runs_once_per_event_and_only_with_when() {
986        let classifier = classifier_with(&["aws_cloudtrail"]);
987        let value = serde_json::json!({"schema_marker": true, "Image": "whoami"});
988        let probes = std::sync::atomic::AtomicUsize::new(0);
989        let event = CountingEvent {
990            inner: JsonEvent::borrow(&value),
991            probes: &probes,
992        };
993        let probed = |run: &dyn Fn()| {
994            probes.store(0, Ordering::Relaxed);
995            run();
996            probes.load(Ordering::Relaxed)
997        };
998
999        let bound = || {
1000            RulesetEngines::new(
1001                vec![
1002                    detection_unit("unbound", Vec::new()),
1003                    bound_unit("cloud", &["aws_cloudtrail"]),
1004                    bound_unit("cloud_too", &["aws_cloudtrail"]),
1005                ],
1006                Some(classifier.clone()),
1007            )
1008            .unwrap()
1009        };
1010        let single = std::cell::RefCell::new(bound());
1011        assert_eq!(
1012            probed(&|| assert_eq!(single.borrow_mut().process_event(&event).len(), 3)),
1013            1
1014        );
1015        let batch = std::cell::RefCell::new(bound());
1016        assert_eq!(
1017            probed(&|| assert_eq!(batch.borrow_mut().process_batch(&[&event])[0].len(), 3)),
1018            1
1019        );
1020        let detect = bound();
1021        assert_eq!(
1022            probed(&|| assert_eq!(detect.detect_batch(&[&event]).unwrap()[0].len(), 3)),
1023            1
1024        );
1025
1026        let unbound = std::cell::RefCell::new(
1027            RulesetEngines::new(
1028                vec![detection_unit("one", Vec::new())],
1029                Some(classifier.clone()),
1030            )
1031            .unwrap(),
1032        );
1033        assert_eq!(
1034            probed(&|| assert_eq!(unbound.borrow_mut().process_event(&event).len(), 1)),
1035            0
1036        );
1037        assert_eq!(
1038            probed(&|| assert_eq!(unbound.borrow_mut().process_batch(&[&event])[0].len(), 1)),
1039            0
1040        );
1041    }
1042
1043    fn correlation_rulesets(results: &[EvaluationResult]) -> Vec<&str> {
1044        results
1045            .iter()
1046            .filter(|result| result.is_correlation())
1047            .map(|result| result.header.ruleset.as_deref().unwrap_or_default())
1048            .collect()
1049    }
1050
1051    fn whoami_at(second: u32) -> serde_json::Value {
1052        serde_json::json!({
1053            "Image": "whoami",
1054            "timestamp": format!("2026-01-01T00:00:0{second}Z"),
1055        })
1056    }
1057
1058    #[test]
1059    fn correlation_state_is_isolated_per_unit() {
1060        let mut engines =
1061            RulesetEngines::new(vec![correlation_unit("a"), correlation_unit("b")], None).unwrap();
1062        let first = whoami_at(0);
1063        let results = engines.process_event(&JsonEvent::borrow(&first));
1064        assert!(
1065            correlation_rulesets(&results).is_empty(),
1066            "a shared store would count the event twice and fire the correlation"
1067        );
1068        let second = whoami_at(1);
1069        let results = engines.process_event(&JsonEvent::borrow(&second));
1070        assert_eq!(correlation_rulesets(&results), ["a", "b"]);
1071    }
1072
1073    #[test]
1074    fn export_and_import_round_trip_by_name() {
1075        let mut engines =
1076            RulesetEngines::new(vec![correlation_unit("a"), correlation_unit("b")], None).unwrap();
1077        let first = whoami_at(0);
1078        engines.process_event(&JsonEvent::borrow(&first));
1079        assert_eq!(engines.state_entries(), 2);
1080        let snapshot = engines.export_state();
1081        assert_eq!(snapshot.rulesets.len(), 2);
1082        assert_eq!(snapshot.window_entries(), 2);
1083
1084        let mut restored = RulesetEngines::new(vec![correlation_unit("a")], None).unwrap();
1085        assert!(restored.import_state(&snapshot));
1086        assert_eq!(restored.state_entries(), 1);
1087        let introspected = restored.introspect();
1088        assert_eq!(introspected["a"].groups.len(), 1);
1089        assert!(!introspected.contains_key("b"));
1090
1091        let second = whoami_at(1);
1092        let results = restored.process_event(&JsonEvent::borrow(&second));
1093        assert_eq!(correlation_rulesets(&results), ["a"]);
1094    }
1095
1096    fn single_engine_snapshot() -> CorrelationSnapshot {
1097        let mut engine = CorrelationEngine::new(CorrelationConfig::default());
1098        engine
1099            .add_collection(&parse_sigma_yaml(CORRELATION).unwrap())
1100            .unwrap();
1101        let first = whoami_at(0);
1102        engine.process_event(&JsonEvent::borrow(&first));
1103        let snapshot = engine.export_state();
1104        assert!(snapshot.has_collection_state());
1105        snapshot
1106    }
1107
1108    #[test]
1109    fn a_single_engine_snapshot_imports_into_the_only_unit() {
1110        let snapshot = single_engine_snapshot();
1111        let mut one = RulesetEngines::new(vec![correlation_unit("a")], None).unwrap();
1112        assert!(one.import_state(&snapshot));
1113        assert_eq!(one.state_entries(), 1);
1114
1115        let mut two =
1116            RulesetEngines::new(vec![correlation_unit("a"), correlation_unit("b")], None).unwrap();
1117        assert!(!two.import_state(&snapshot));
1118        assert_eq!(two.state_entries(), 0);
1119    }
1120
1121    #[test]
1122    fn a_one_ruleset_snapshot_imports_into_a_single_engine() {
1123        let mut engines = RulesetEngines::new(vec![correlation_unit("a")], None).unwrap();
1124        let first = whoami_at(0);
1125        engines.process_event(&JsonEvent::borrow(&first));
1126        let snapshot = engines.export_state();
1127
1128        let mut engine = CorrelationEngine::new(CorrelationConfig::default());
1129        engine
1130            .add_collection(&parse_sigma_yaml(CORRELATION).unwrap())
1131            .unwrap();
1132        assert!(engine.import_state(snapshot));
1133        assert_eq!(engine.state_count(), 1);
1134
1135        let mut both =
1136            RulesetEngines::new(vec![correlation_unit("a"), correlation_unit("b")], None).unwrap();
1137        both.process_event(&JsonEvent::borrow(&first));
1138        let mut engine = CorrelationEngine::new(CorrelationConfig::default());
1139        engine
1140            .add_collection(&parse_sigma_yaml(CORRELATION).unwrap())
1141            .unwrap();
1142        assert!(!engine.import_state(both.export_state()));
1143        assert_eq!(engine.state_count(), 0);
1144    }
1145
1146    #[test]
1147    fn a_rejected_ruleset_snapshot_fails_the_import() {
1148        let mut engines = RulesetEngines::new(vec![correlation_unit("a")], None).unwrap();
1149        let first = whoami_at(0);
1150        engines.process_event(&JsonEvent::borrow(&first));
1151        let mut snapshot = engines.export_state();
1152        snapshot.rulesets.get_mut("a").unwrap().version = 999;
1153
1154        let mut restored = RulesetEngines::new(vec![correlation_unit("a")], None).unwrap();
1155        assert!(!restored.import_state(&snapshot));
1156        assert_eq!(restored.state_entries(), 0);
1157    }
1158
1159    #[test]
1160    fn a_rejected_ruleset_does_not_cost_the_others_their_state() {
1161        let units = || vec![correlation_unit("a"), correlation_unit("b")];
1162        let mut engines = RulesetEngines::new(units(), None).unwrap();
1163        engines.process_event(&JsonEvent::borrow(&whoami_at(0)));
1164        let mut snapshot = engines.export_state();
1165        snapshot.rulesets.get_mut("a").unwrap().version = 999;
1166
1167        let mut restored = RulesetEngines::new(units(), None).unwrap();
1168        assert!(!restored.import_state(&snapshot));
1169        assert_eq!(restored.state_entries(), 1, "ruleset b still restores");
1170    }
1171
1172    #[test]
1173    fn detect_batch_rejects_correlation_units() {
1174        let engines = RulesetEngines::new(
1175            vec![detection_unit("one", Vec::new()), correlation_unit("two")],
1176            None,
1177        )
1178        .unwrap();
1179        let value = serde_json::json!({"Image": "whoami"});
1180        let event = JsonEvent::borrow(&value);
1181        assert!(engines.detect_batch(&[&event]).is_none());
1182    }
1183
1184    #[test]
1185    fn routed_unit_counts_route_outcomes() {
1186        let value = serde_json::json!({"foo": "bar"});
1187        let event = JsonEvent::borrow(&value);
1188
1189        let mut unknown = routed_engine(OnUnknown::Warn);
1190        unknown.process_event(&event);
1191        assert_eq!(unknown.route_counts().unknown, 1);
1192
1193        let mut dropped = routed_engine(OnUnknown::Drop);
1194        dropped.process_event(&event);
1195        assert_eq!(dropped.route_counts().dropped, 1);
1196
1197        let mut errored = routed_engine(OnUnknown::Error);
1198        errored.process_event(&event);
1199        assert_eq!(errored.route_counts().errored, 1);
1200    }
1201
1202    #[test]
1203    fn construction_errors_are_reported() {
1204        assert!(matches!(
1205            RulesetEngines::new(Vec::new(), None),
1206            Err(RulesetEnginesError::Empty)
1207        ));
1208        assert!(matches!(
1209            RulesetEngines::new(
1210                vec![
1211                    detection_unit("a", Vec::new()),
1212                    detection_unit("a", Vec::new())
1213                ],
1214                None
1215            ),
1216            Err(RulesetEnginesError::DuplicateName(_))
1217        ));
1218        assert!(matches!(
1219            RulesetEngines::new(
1220                vec![detection_unit("a", Vec::new()), {
1221                    let mut routed = routed_engine(OnUnknown::Warn);
1222                    routed.units.remove(0)
1223                }],
1224                None
1225            ),
1226            Err(RulesetEnginesError::RoutedWithOthers(2))
1227        ));
1228        assert!(
1229            RulesetEngines::new(
1230                vec![{
1231                    let mut routed = routed_engine(OnUnknown::Warn);
1232                    routed.units.remove(0)
1233                }],
1234                None
1235            )
1236            .is_ok()
1237        );
1238        assert!(matches!(
1239            RulesetEngines::new(
1240                vec![{
1241                    let mut routed = routed_engine(OnUnknown::Warn);
1242                    let mut unit = routed.units.remove(0);
1243                    unit.when_schemas = vec!["x".to_string()];
1244                    unit
1245                }],
1246                None
1247            ),
1248            Err(RulesetEnginesError::RoutedWithWhen(_))
1249        ));
1250        assert!(matches!(
1251            RulesetEngines::new(vec![bound_unit("a", &["x"])], None),
1252            Err(RulesetEnginesError::WhenWithoutClassifier(_))
1253        ));
1254        assert!(matches!(
1255            RulesetEngines::new(
1256                vec![bound_unit("a", &["nope"])],
1257                Some(classifier_with(&["known"]))
1258            ),
1259            Err(RulesetEnginesError::UnknownSchema { .. })
1260        ));
1261    }
1262
1263    #[test]
1264    fn process_event_and_process_batch_agree() {
1265        let mut single = RulesetEngines::new(
1266            vec![
1267                detection_unit("a", Vec::new()),
1268                detection_unit("b", Vec::new()),
1269            ],
1270            None,
1271        )
1272        .unwrap();
1273        let mut batch = RulesetEngines::new(
1274            vec![
1275                detection_unit("a", Vec::new()),
1276                detection_unit("b", Vec::new()),
1277            ],
1278            None,
1279        )
1280        .unwrap();
1281        let values = [
1282            serde_json::json!({"Image": "whoami"}),
1283            serde_json::json!({"Image": "hostname"}),
1284        ];
1285        let events: Vec<JsonEvent> = values.iter().map(JsonEvent::borrow).collect();
1286        let refs: Vec<&JsonEvent> = events.iter().collect();
1287        let batched = batch.process_batch(&refs);
1288        let mut singles = Vec::new();
1289        for event in &refs {
1290            singles.push(single.process_event(*event));
1291        }
1292        for (single, batch) in singles.iter().zip(&batched) {
1293            assert_eq!(
1294                serde_json::to_string(single).unwrap(),
1295                serde_json::to_string(batch).unwrap()
1296            );
1297        }
1298    }
1299}
1300
1301#[cfg(test)]
1302mod tenant_tests {
1303    use super::*;
1304    use crate::tenant::TenantId;
1305    use crate::{JsonEvent, SchemaPredicate, SchemaSignature};
1306
1307    const DETECTION: &str = r#"
1308title: Whoami
1309id: whoami
1310logsource:
1311    category: process_creation
1312    product: windows
1313detection:
1314    selection:
1315        Image: whoami
1316    condition: selection
1317"#;
1318
1319    fn detection_unit(name: &str, schemas: &[&str]) -> RulesetUnit {
1320        let collection = rsigma_parser::parse_sigma_yaml(DETECTION).unwrap();
1321        let mut engine = Engine::new();
1322        engine.add_collection(&collection).unwrap();
1323        RulesetUnit {
1324            name: Arc::from(name),
1325            when_schemas: schemas.iter().map(|schema| (*schema).to_string()).collect(),
1326            tenants: Vec::new(),
1327            engine: UnitEngine::Detection(Box::new(engine)),
1328            field_set: RuleFieldSet::collect(&collection, &[], true),
1329        }
1330    }
1331
1332    fn tenant_bound_unit(name: &str, tenants: &[&str]) -> RulesetUnit {
1333        let mut unit = detection_unit(name, &[]);
1334        unit.tenants = tenants
1335            .iter()
1336            .map(|tenant| TenantId::new(tenant).unwrap())
1337            .collect();
1338        unit
1339    }
1340
1341    fn classifier_with(schemas: &[&str]) -> Arc<SchemaClassifier> {
1342        Arc::new(SchemaClassifier::new(
1343            schemas
1344                .iter()
1345                .map(|name| SchemaSignature {
1346                    name: (*name).to_string(),
1347                    predicates: vec![SchemaPredicate::FieldPresent("schema_marker".to_string())],
1348                    specificity: 10,
1349                })
1350                .collect(),
1351        ))
1352    }
1353
1354    fn event() -> serde_json::Value {
1355        serde_json::json!({"Image": "whoami"})
1356    }
1357
1358    #[test]
1359    fn a_tenant_bound_unit_skips_other_tenants_and_untenanted_events() {
1360        let a = TenantId::new("a").unwrap();
1361        let b = TenantId::new("b").unwrap();
1362        let mut engines =
1363            RulesetEngines::new(vec![tenant_bound_unit("bound", &["a"])], None).unwrap();
1364        let value = event();
1365        let event = JsonEvent::borrow(&value);
1366
1367        assert_eq!(engines.process_event_for_tenant(&event, Some(&a)).len(), 1);
1368        assert!(
1369            engines
1370                .process_event_for_tenant(&event, Some(&b))
1371                .is_empty()
1372        );
1373        assert!(engines.process_event_for_tenant(&event, None).is_empty());
1374
1375        let skipped = engines.skipped_totals();
1376        assert_eq!(skipped[0].1, 2);
1377    }
1378
1379    #[test]
1380    fn an_unbound_unit_accepts_every_tenant() {
1381        let a = TenantId::new("a").unwrap();
1382        let b = TenantId::new("b").unwrap();
1383        let mut engines = RulesetEngines::new(vec![detection_unit("all", &[])], None).unwrap();
1384        let value = event();
1385        let event = JsonEvent::borrow(&value);
1386
1387        for tenant in [Some(&a), Some(&b), None] {
1388            assert_eq!(engines.process_event_for_tenant(&event, tenant).len(), 1);
1389        }
1390        assert_eq!(engines.skipped_totals()[0].1, 0);
1391    }
1392
1393    #[test]
1394    fn when_and_tenants_combine_with_and() {
1395        let a = TenantId::new("a").unwrap();
1396        let b = TenantId::new("b").unwrap();
1397        let mut unit = detection_unit("cloud", &["aws_cloudtrail"]);
1398        unit.tenants = vec![a.clone()];
1399        let mut engines =
1400            RulesetEngines::new(vec![unit], Some(classifier_with(&["aws_cloudtrail"]))).unwrap();
1401
1402        let matching = serde_json::json!({"schema_marker": true, "Image": "whoami"});
1403        let matching = JsonEvent::borrow(&matching);
1404        assert_eq!(
1405            engines.process_event_for_tenant(&matching, Some(&a)).len(),
1406            1
1407        );
1408        assert!(
1409            engines
1410                .process_event_for_tenant(&matching, Some(&b))
1411                .is_empty()
1412        );
1413
1414        let other_schema = serde_json::json!({"Image": "whoami"});
1415        let other_schema = JsonEvent::borrow(&other_schema);
1416        assert!(
1417            engines
1418                .process_event_for_tenant(&other_schema, Some(&a))
1419                .is_empty()
1420        );
1421        assert_eq!(engines.skipped_totals()[0].1, 2);
1422    }
1423
1424    #[test]
1425    fn batch_processing_counts_tenant_skips_and_reports_tenants() {
1426        let a = TenantId::new("a").unwrap();
1427        let b = TenantId::new("b").unwrap();
1428        let mut engines =
1429            RulesetEngines::new(vec![tenant_bound_unit("bound", &["a"])], None).unwrap();
1430        let values = [event(), event()];
1431        let events: Vec<JsonEvent> = values.iter().map(JsonEvent::borrow).collect();
1432        let refs: Vec<&JsonEvent> = events.iter().collect();
1433        let tenants = vec![Some(a.clone()), Some(b)];
1434
1435        let output = engines.process_batch_for_tenants(&refs, &tenants);
1436        assert_eq!(output[0].len(), 1);
1437        assert!(output[1].is_empty());
1438        assert_eq!(engines.take_skipped()[0].1, 1);
1439
1440        let stats = engines.ruleset_stats();
1441        assert_eq!(stats[0].tenants, vec![a]);
1442    }
1443}