Skip to main content

rsigma_eval/compiler/
mod.rs

1//! Compile parsed Sigma rules into optimized in-memory representations.
2//!
3//! The primary entry point, [`compile_rule`], lowers a `SigmaRule` to HIR via
4//! `rsigma_ir::lower_rule` and then materializes the physical forms
5//! (`CompiledRule`, `CompiledDetection`, `CompiledDetectionItem`) with
6//! [`compile_to_compiled`], which builds the concrete `CompiledMatcher`
7//! variants (regex, Aho-Corasick, `IpNet`, lowercased patterns) that evaluate
8//! efficiently against events. Modifier interpretation happens during lowering;
9//! this module turns the resolved matchers into executable artifacts.
10
11mod array;
12mod from_ir;
13mod helpers;
14#[doc(hidden)]
15pub mod optimizer;
16#[cfg(test)]
17mod tests;
18mod value;
19
20pub(crate) use array::{
21    array_quantifier_from_member_matches, array_quantifier_matches_empty, decisive_member_verdict,
22    element_field, eval_array_body, eval_array_item, eval_array_quantified,
23    select_recorded_member_indices,
24};
25
26pub use from_ir::compile_to_compiled;
27
28// Re-export so equivalence proptests in other modules and the fuzz target
29// can drive the optimizer directly.
30#[cfg(test)]
31pub(crate) use optimizer::optimize_any_of as optimize_any_of_for_test;
32
33use std::collections::HashMap;
34use std::sync::Arc;
35
36#[cfg(test)]
37use rsigma_parser::DetectionItem;
38use rsigma_parser::{
39    ArrayQuantifier, ConditionExpr, Detection, Level, LogSource, Quantifier, SigmaRule,
40};
41
42use crate::error::Result;
43use crate::event::{Event, EventValue};
44use crate::matcher::CompiledMatcher;
45use crate::result::{
46    DetectionBody, EvaluationResult, FieldMatch, MatchDetailLevel, MatcherKind, ResultBody,
47    RuleHeader,
48};
49
50pub(crate) use helpers::{yaml_to_json, yaml_to_json_map};
51
52// =============================================================================
53// Compiled types
54// =============================================================================
55
56/// A compiled Sigma rule, ready for evaluation.
57#[derive(Debug, Clone)]
58pub struct CompiledRule {
59    pub title: String,
60    pub id: Option<String>,
61    pub name: Option<String>,
62    pub level: Option<Level>,
63    pub tags: Vec<String>,
64    /// The rule's `description`. Retained because it carries the ADS goal
65    /// section, which downstream consumers surface alongside a match.
66    pub description: Option<String>,
67    /// The rule's `falsepositives`, retained as the ADS false-positives
68    /// section carrier.
69    pub falsepositives: Vec<String>,
70    pub logsource: LogSource,
71    /// Compiled named detections, keyed by detection name.
72    pub detections: HashMap<String, CompiledDetection>,
73    /// Condition expression trees (usually one, but can be multiple).
74    pub conditions: Vec<ConditionExpr>,
75    /// Whether to include the full event JSON in the match result.
76    /// Controlled by the `rsigma.include_event` custom attribute.
77    pub include_event: bool,
78    /// Custom attributes from the original Sigma rule (merged view of
79    /// arbitrary top-level keys, the explicit `custom_attributes:` block,
80    /// and pipeline `SetCustomAttribute` additions). Propagated to match
81    /// results. Wrapped in `Arc` so per-match cloning is a pointer bump.
82    pub custom_attributes: Arc<HashMap<String, serde_json::Value>>,
83}
84
85/// A compiled detection definition.
86#[derive(Debug, Clone)]
87pub enum CompiledDetection {
88    /// AND-linked detection items (from a YAML mapping).
89    AllOf(Vec<CompiledDetectionItem>),
90    /// OR-linked sub-detections (from a YAML list of mappings).
91    AnyOf(Vec<CompiledDetection>),
92    /// Keyword detection: match values across all event fields.
93    Keywords(CompiledMatcher),
94    /// Array object-scope match: evaluate `body` against the members of the
95    /// array at `field`, with `any`/`all` quantification. Within `body`, a
96    /// detection item with `field == None` matches the array member itself.
97    ArrayMatch {
98        field: String,
99        quantifier: ArrayQuantifier,
100        body: Box<CompiledDetection>,
101    },
102    /// AND of heterogeneous sub-detections (a mapping mixing plain items with
103    /// array object-scope blocks).
104    And(Vec<CompiledDetection>),
105    /// Extended array object-scope body: named element-scoped sub-selections
106    /// combined by `condition` (and/or/not), evaluated against a single array
107    /// member. Appears only as an [`ArrayMatch`](CompiledDetection::ArrayMatch)
108    /// body.
109    Conditional {
110        named: HashMap<String, CompiledDetection>,
111        condition: ConditionExpr,
112    },
113}
114
115/// A compiled detection item: a field + matcher.
116#[derive(Debug, Clone)]
117pub struct CompiledDetectionItem {
118    /// The field name to check (`None` for keyword items).
119    pub field: Option<String>,
120    /// The compiled matcher combining all values with appropriate logic.
121    pub matcher: CompiledMatcher,
122    /// If `Some(true)`, field must exist; `Some(false)`, must not exist.
123    pub exists: Option<bool>,
124    /// Pre-computed flag set when the matcher is a positive substring
125    /// assertion eligible for bloom-filter pre-filtering. Recomputing the
126    /// recursive `is_positive_substring_matcher` walk for every event would
127    /// dominate the eval cost on rule sets where most items don't qualify.
128    pub bloom_eligible: bool,
129}
130
131// =============================================================================
132// Public API
133// =============================================================================
134
135/// Compile a parsed `SigmaRule` into a `CompiledRule`.
136///
137/// Routes through the IR layer: `lower_rule` → [`compile_to_compiled`].
138pub fn compile_rule(rule: &SigmaRule) -> Result<CompiledRule> {
139    let ir = rsigma_ir::lower_rule(rule, &rsigma_ir::LowerOptions::default())?;
140    compile_to_compiled(&ir)
141}
142
143/// Evaluate a compiled rule against an event, returning an
144/// [`EvaluationResult`] if it matches.
145///
146/// This is the public entry point for one-shot rule evaluation. It does no
147/// bloom pre-filtering; every detection item is evaluated directly. Engines
148/// that maintain a per-field bloom index should call the crate-private
149/// `evaluate_rule_with_bloom` variant via the `Engine` API instead.
150pub fn evaluate_rule(rule: &CompiledRule, event: &impl Event) -> Option<EvaluationResult> {
151    evaluate_rule_with_bloom(
152        rule,
153        event,
154        &crate::engine::bloom_index::NoBloom,
155        MatchDetailLevel::Off,
156    )
157}
158
159/// Evaluate a compiled rule against an event with bloom pre-filtering.
160///
161/// `bloom` provides per-field verdicts for positive substring matchers.
162/// When `bloom.verdict_for_field(field)` returns `DefinitelyNoMatch`, any
163/// positive substring item targeting that field is short-circuited to
164/// `false` without invoking its matcher. The pre-filter is purely an
165/// optimization: it never changes the eval result vs `evaluate_rule`.
166pub(crate) fn evaluate_rule_with_bloom<E, B>(
167    rule: &CompiledRule,
168    event: &E,
169    bloom: &B,
170    level: MatchDetailLevel,
171) -> Option<EvaluationResult>
172where
173    E: Event,
174    B: crate::engine::bloom_index::BloomLookup,
175{
176    for condition in &rule.conditions {
177        if eval_condition_matches_with_bloom(condition, &rule.detections, event, bloom) {
178            let mut detail = Vec::new();
179            let matched = eval_condition_detail(
180                condition,
181                &rule.detections,
182                event,
183                bloom,
184                level,
185                &mut detail,
186            );
187            debug_assert!(matched, "detail pass must agree with boolean pass");
188            let (matched_selections, matched_fields) = flatten_detail(detail);
189
190            let event_data = if rule.include_event {
191                Some(event.to_json())
192            } else {
193                None
194            };
195
196            return Some(EvaluationResult {
197                header: RuleHeader {
198                    rule_title: rule.title.clone(),
199                    rule_id: rule.id.clone(),
200                    level: rule.level,
201                    tags: rule.tags.clone(),
202                    custom_attributes: rule.custom_attributes.clone(),
203                    enrichments: None,
204                },
205                body: ResultBody::Detection(DetectionBody {
206                    matched_selections,
207                    matched_fields,
208                    event: event_data,
209                }),
210            });
211        }
212    }
213    None
214}
215
216// =============================================================================
217// Detection compilation
218// =============================================================================
219
220/// Compile a parsed detection tree into a [`CompiledDetection`].
221///
222/// Routes through the IR layer like [`compile_rule`]: `lower_detection` →
223/// the HIR compiler. Returns an error if the detection tree is empty or
224/// contains invalid items.
225pub fn compile_detection(detection: &Detection) -> Result<CompiledDetection> {
226    let opts = rsigma_ir::LowerOptions {
227        permissive_placeholders: true,
228    };
229    from_ir::compile_ir_detection(&rsigma_ir::lower::lower_detection(detection, &opts)?)
230}
231
232#[cfg(test)]
233fn compile_detection_item(item: &DetectionItem) -> Result<CompiledDetectionItem> {
234    let ir = rsigma_ir::lower::lower_detection_item(item, &rsigma_ir::LowerOptions::default())?;
235    from_ir::compile_ir_detection_item(&ir)
236}
237
238// =============================================================================
239// Condition evaluation
240// =============================================================================
241
242/// Evaluate a condition expression against the event using compiled detections.
243///
244/// Returns `true` if the condition is satisfied. Appends to
245/// `matched_selections`, once each, the matched detections that decide the
246/// result: for `(a and b) or c` firing on `c` alone, only `c`, and for
247/// `a and not b`, only `a`.
248pub fn eval_condition(
249    expr: &ConditionExpr,
250    detections: &HashMap<String, CompiledDetection>,
251    event: &impl Event,
252    matched_selections: &mut Vec<String>,
253) -> bool {
254    let mut detail = Vec::new();
255    let result = eval_condition_detail(
256        expr,
257        detections,
258        event,
259        &crate::engine::bloom_index::NoBloom,
260        MatchDetailLevel::Off,
261        &mut detail,
262    );
263    matched_selections.extend(flatten_detail(detail).0);
264    result
265}
266
267/// Evaluate a condition without collecting match details.
268///
269/// This is the production fast path for the common nonmatch case. Selectors
270/// can stop as soon as their quantifier is decided; matching rules run the
271/// detail-collecting evaluator once afterward.
272fn eval_condition_matches_with_bloom<E, B>(
273    expr: &ConditionExpr,
274    detections: &HashMap<String, CompiledDetection>,
275    event: &E,
276    bloom: &B,
277) -> bool
278where
279    E: Event,
280    B: crate::engine::bloom_index::BloomLookup,
281{
282    match expr {
283        ConditionExpr::Identifier(name) => detections
284            .get(name)
285            .is_some_and(|det| eval_detection_with_bloom(det, event, bloom)),
286        ConditionExpr::And(exprs) => exprs
287            .iter()
288            .all(|e| eval_condition_matches_with_bloom(e, detections, event, bloom)),
289        ConditionExpr::Or(exprs) => exprs
290            .iter()
291            .any(|e| eval_condition_matches_with_bloom(e, detections, event, bloom)),
292        ConditionExpr::Not(inner) => {
293            !eval_condition_matches_with_bloom(inner, detections, event, bloom)
294        }
295        ConditionExpr::Selector {
296            quantifier,
297            pattern,
298        } => {
299            let mut matching = detections
300                .iter()
301                .filter(|(name, _)| pattern.matches_detection_name(name));
302            match quantifier {
303                Quantifier::Any => {
304                    matching.any(|(_, det)| eval_detection_with_bloom(det, event, bloom))
305                }
306                Quantifier::All => {
307                    matching.all(|(_, det)| eval_detection_with_bloom(det, event, bloom))
308                }
309                Quantifier::Count(required) => {
310                    let mut matched = 0u64;
311                    matching.any(|(_, det)| {
312                        if eval_detection_with_bloom(det, event, bloom) {
313                            matched += 1;
314                        }
315                        matched >= required.get()
316                    })
317                }
318            }
319        }
320    }
321}
322
323/// A matched selection and the field matches it recorded.
324struct SelectionDetail {
325    name: String,
326    fields: Vec<FieldMatch>,
327}
328
329/// Selection names, once each in first-seen order, and their field matches.
330fn flatten_detail(detail: Vec<SelectionDetail>) -> (Vec<String>, Vec<FieldMatch>) {
331    let mut seen = std::collections::HashSet::new();
332    let mut names = Vec::new();
333    let mut fields = Vec::new();
334    for selection in detail {
335        if seen.insert(selection.name.clone()) {
336            names.push(selection.name);
337            fields.extend(selection.fields);
338        }
339    }
340    (names, fields)
341}
342
343/// The detail pass: evaluate `expr` and record in `out` the matched
344/// selections that decide its value, each with the field matches it produced
345/// while being evaluated.
346fn eval_condition_detail<E, B>(
347    expr: &ConditionExpr,
348    detections: &HashMap<String, CompiledDetection>,
349    event: &E,
350    bloom: &B,
351    level: MatchDetailLevel,
352    out: &mut Vec<SelectionDetail>,
353) -> bool
354where
355    E: Event,
356    B: crate::engine::bloom_index::BloomLookup,
357{
358    match expr {
359        ConditionExpr::Identifier(name) => {
360            let Some(det) = detections.get(name) else {
361                return false;
362            };
363            let mut fields = Vec::new();
364            let result = eval_detection_recording(name, det, event, bloom, level, &mut fields);
365            if result {
366                out.push(SelectionDetail {
367                    name: name.clone(),
368                    fields,
369                });
370            }
371            result
372        }
373
374        // A false `and` is explained by its failing child alone, and a true
375        // `or` by its true child alone, so drop what the other children
376        // recorded. `not` keeps its child's names unchanged: they explain the
377        // child's value, which decides the negation.
378        ConditionExpr::And(exprs) => {
379            let mark = out.len();
380            for e in exprs {
381                let child_mark = out.len();
382                if !eval_condition_detail(e, detections, event, bloom, level, out) {
383                    out.drain(mark..child_mark);
384                    return false;
385                }
386            }
387            true
388        }
389
390        ConditionExpr::Or(exprs) => {
391            let mark = out.len();
392            for e in exprs {
393                let child_mark = out.len();
394                if eval_condition_detail(e, detections, event, bloom, level, out) {
395                    out.drain(mark..child_mark);
396                    return true;
397                }
398            }
399            false
400        }
401
402        ConditionExpr::Not(inner) => {
403            !eval_condition_detail(inner, detections, event, bloom, level, out)
404        }
405
406        ConditionExpr::Selector {
407            quantifier,
408            pattern,
409        } => {
410            let mut candidates = 0usize;
411            let mut matched = Vec::new();
412            for (name, det) in detections
413                .iter()
414                .filter(|(name, _)| pattern.matches_detection_name(name))
415            {
416                candidates += 1;
417                let mut fields = Vec::new();
418                if eval_detection_recording(name, det, event, bloom, level, &mut fields) {
419                    matched.push(SelectionDetail {
420                        name: name.clone(),
421                        fields,
422                    });
423                }
424            }
425
426            let holds = match quantifier {
427                Quantifier::Any => !matched.is_empty(),
428                Quantifier::All => matched.len() == candidates,
429                Quantifier::Count(n) => matched.len() as u64 >= n.get(),
430            };
431            // Matched members explain a quantifier that holds; when it fails,
432            // only the members that did not match do, and those report nothing.
433            if holds {
434                out.extend(matched);
435            }
436            holds
437        }
438    }
439}
440
441/// Evaluate a compiled detection item against an event without bloom
442/// pre-filtering. Used only by the in-crate compiler tests; the production
443/// paths run through `eval_detection_item_with_bloom` from
444/// `evaluate_rule_with_bloom`.
445#[cfg(test)]
446fn eval_detection_item(item: &CompiledDetectionItem, event: &impl Event) -> bool {
447    eval_detection_item_with_bloom(item, event, &crate::engine::bloom_index::NoBloom)
448}
449
450/// Evaluate a single compiled detection item against an event without bloom
451/// pre-filtering. Used by the [`crate::explain`] recording evaluator so each
452/// per-item verdict matches the production engine exactly.
453pub(crate) fn eval_detection_item_no_bloom(
454    item: &CompiledDetectionItem,
455    event: &impl Event,
456) -> bool {
457    eval_detection_item_with_bloom(item, event, &crate::engine::bloom_index::NoBloom)
458}
459
460/// Evaluate a compiled detection against an event with a bloom lookup.
461fn eval_detection_with_bloom<E, B>(detection: &CompiledDetection, event: &E, bloom: &B) -> bool
462where
463    E: Event,
464    B: crate::engine::bloom_index::BloomLookup,
465{
466    match detection {
467        CompiledDetection::AllOf(items) => items
468            .iter()
469            .all(|item| eval_detection_item_with_bloom(item, event, bloom)),
470        CompiledDetection::AnyOf(dets) => dets
471            .iter()
472            .any(|d| eval_detection_with_bloom(d, event, bloom)),
473        CompiledDetection::Keywords(matcher) => matcher.matches_keyword(event),
474        CompiledDetection::ArrayMatch {
475            field,
476            quantifier,
477            body,
478        } => match event.get_field(field) {
479            Some(value) => eval_array_quantified(&value, *quantifier, body, event),
480            None => array_quantifier_matches_empty(*quantifier),
481        },
482        CompiledDetection::And(dets) => dets
483            .iter()
484            .all(|d| eval_detection_with_bloom(d, event, bloom)),
485        // Only produced as an `ArrayMatch` body (evaluated via
486        // `eval_array_condition`). At the top level it degenerates to a
487        // sub-rule over the event, which reuses the condition evaluator.
488        CompiledDetection::Conditional { named, condition } => {
489            eval_condition_matches_with_bloom(condition, named, event, bloom)
490        }
491    }
492}
493
494/// Evaluate a single detection item with bloom pre-filtering.
495///
496/// When the matcher targets a single field and is a positive substring
497/// matcher (not under negation), the bloom verdict is consulted first. A
498/// `DefinitelyNoMatch` verdict guarantees the matcher would return `false`,
499/// so we return early without invoking it.
500fn eval_detection_item_with_bloom<E, B>(item: &CompiledDetectionItem, event: &E, bloom: &B) -> bool
501where
502    E: Event,
503    B: crate::engine::bloom_index::BloomLookup,
504{
505    if let Some(expect_exists) = item.exists {
506        if let Some(field) = &item.field {
507            return event.get_field(field).is_some() == expect_exists;
508        }
509        return !expect_exists;
510    }
511
512    match &item.field {
513        Some(field_name) => {
514            if let Some(value) = event.get_field(field_name) {
515                if item.bloom_eligible
516                    && bloom.verdict_for_field(field_name)
517                        == crate::engine::bloom_index::BloomVerdict::DefinitelyNoMatch
518                {
519                    return false;
520                }
521                item.matcher.matches(&value, event)
522            } else {
523                item.matcher.matches_absent()
524            }
525        }
526        None => item.matcher.matches_keyword(event),
527    }
528}
529
530/// Cap on the number of keyword-match entries recorded per keyword detection
531/// at `Summary` / `Full`. A single high-cardinality event (many string
532/// leaves) cannot blow up the output line.
533const MAX_KEYWORD_MATCHES: usize = 16;
534
535/// Evaluate a detection, recording its field matches in `out` when it holds.
536///
537/// At [`MatchDetailLevel::Off`] the entries keep the historical shape: one
538/// `{ field, value }` per field-present `AllOf` item, with keyword and
539/// absence matches omitted. At `Summary` / `Full` they carry the matcher
540/// descriptor, and keyword and `Null`-on-absent matches are reported too. A
541/// detection that does not hold leaves `out` unchanged.
542fn eval_detection_recording<E, B>(
543    selection: &str,
544    detection: &CompiledDetection,
545    event: &E,
546    bloom: &B,
547    level: MatchDetailLevel,
548    out: &mut Vec<FieldMatch>,
549) -> bool
550where
551    E: Event,
552    B: crate::engine::bloom_index::BloomLookup,
553{
554    match detection {
555        CompiledDetection::AllOf(items) => {
556            let mark = out.len();
557            for item in items {
558                if !eval_item_recording(selection, item, event, bloom, level, out) {
559                    out.truncate(mark);
560                    return false;
561                }
562            }
563            true
564        }
565        CompiledDetection::AnyOf(dets) => {
566            // Every matching branch reports its fields, so evaluate them all.
567            let mut any = false;
568            for d in dets {
569                any |= eval_detection_recording(selection, d, event, bloom, level, out);
570            }
571            any
572        }
573        CompiledDetection::And(dets) => {
574            let mark = out.len();
575            for d in dets {
576                if !eval_detection_recording(selection, d, event, bloom, level, out) {
577                    out.truncate(mark);
578                    return false;
579                }
580            }
581            true
582        }
583        CompiledDetection::Keywords(matcher) => {
584            let matched = matcher.matches_keyword(event);
585            if matched && level != MatchDetailLevel::Off {
586                collect_keyword_matches(selection, matcher, event, level, out);
587            }
588            matched
589        }
590        CompiledDetection::ArrayMatch {
591            field,
592            quantifier,
593            body,
594        } => {
595            let value = event.get_field(field);
596            let Some(value) = value.as_ref() else {
597                return array_quantifier_matches_empty(*quantifier);
598            };
599            let (scalar, members) = array_members(value);
600            let verdicts: Vec<bool> = members
601                .iter()
602                .map(|m| array::eval_array_body(body, m, event))
603                .collect();
604            let holds = array::array_quantifier_from_member_matches(*quantifier, &verdicts);
605            if holds {
606                record_array_members(
607                    selection,
608                    field.clone(),
609                    body,
610                    value,
611                    scalar,
612                    &members,
613                    &verdicts,
614                    event,
615                    level,
616                    out,
617                );
618            }
619            holds
620        }
621        // Only produced as an array body, where members are recorded by
622        // `collect_array_body_fields`.
623        CompiledDetection::Conditional { named, condition } => {
624            eval_condition_matches_with_bloom(condition, named, event, bloom)
625        }
626    }
627}
628
629/// Evaluate one `AllOf` item, recording its field match in `out` when it holds.
630fn eval_item_recording<E, B>(
631    selection: &str,
632    item: &CompiledDetectionItem,
633    event: &E,
634    bloom: &B,
635    level: MatchDetailLevel,
636    out: &mut Vec<FieldMatch>,
637) -> bool
638where
639    E: Event,
640    B: crate::engine::bloom_index::BloomLookup,
641{
642    let Some(field_name) = &item.field else {
643        let matched = match item.exists {
644            Some(expect) => !expect,
645            None => item.matcher.matches_keyword(event),
646        };
647        if matched && level != MatchDetailLevel::Off {
648            collect_keyword_matches(selection, &item.matcher, event, level, out);
649        }
650        return matched;
651    };
652
653    match event.get_field(field_name) {
654        Some(value) => {
655            let matched = match item.exists {
656                Some(expect) => expect,
657                None => {
658                    !(item.bloom_eligible
659                        && bloom.verdict_for_field(field_name)
660                            == crate::engine::bloom_index::BloomVerdict::DefinitelyNoMatch)
661                        && item.matcher.matches(&value, event)
662                }
663            };
664            if matched {
665                out.push(make_field_match(
666                    selection,
667                    field_name,
668                    value.to_json(),
669                    &item.matcher,
670                    level,
671                ));
672            }
673            matched
674        }
675        None => {
676            let matched = match item.exists {
677                Some(expect) => !expect,
678                None => item.matcher.matches_absent(),
679            };
680            // Absent-field matches are never reported at `Off`, which keeps
681            // the historical wire shape.
682            if matched && level != MatchDetailLevel::Off {
683                out.push(make_field_match(
684                    selection,
685                    field_name,
686                    serde_json::Value::Null,
687                    &item.matcher,
688                    level,
689                ));
690            }
691            matched
692        }
693    }
694}
695
696/// The members of an array-match value and whether it is a scalar treated as
697/// one member. A null value has no members.
698fn array_members<'v>(value: &'v EventValue<'v>) -> (bool, Vec<&'v EventValue<'v>>) {
699    match value {
700        EventValue::Null => (false, Vec::new()),
701        EventValue::Array(items) => (false, items.iter().collect()),
702        single => (true, vec![single]),
703    }
704}
705
706/// Record the binding members of a nested `ArrayMatch` inside a matched
707/// array member.
708#[allow(clippy::too_many_arguments)]
709fn collect_array_match_fields<E: Event>(
710    selection: &str,
711    field: &str,
712    body: &CompiledDetection,
713    value: Option<&EventValue>,
714    outer: &E,
715    level: MatchDetailLevel,
716    path_prefix: &str,
717    out: &mut Vec<FieldMatch>,
718) {
719    let Some(value) = value else {
720        return;
721    };
722    let (scalar, members) = array_members(value);
723    let verdicts: Vec<bool> = members
724        .iter()
725        .map(|m| array::eval_array_body(body, m, outer))
726        .collect();
727    let container_path = if path_prefix.is_empty() {
728        field.to_string()
729    } else {
730        array::join_member_field(path_prefix, Some(field))
731    };
732    record_array_members(
733        selection,
734        container_path,
735        body,
736        value,
737        scalar,
738        &members,
739        &verdicts,
740        outer,
741        level,
742        out,
743    );
744}
745
746/// Record the binding members of a matched `ArrayMatch` from its per-member
747/// body verdicts.
748///
749/// Matching members are emitted with indexed paths (`field[i].leaf`) up to
750/// [`array::ARRAY_MEMBER_CAP`]. A scalar treated as one member uses the
751/// un-indexed path so it still resolves through [`Event::get_field`]. With no
752/// binding member (`[none]`, vacuous `[all_or_empty]`, or a null or empty
753/// array), the container is recorded.
754#[allow(clippy::too_many_arguments)]
755fn record_array_members<E: Event>(
756    selection: &str,
757    container_path: String,
758    body: &CompiledDetection,
759    value: &EventValue,
760    scalar: bool,
761    members: &[&EventValue],
762    verdicts: &[bool],
763    outer: &E,
764    level: MatchDetailLevel,
765    out: &mut Vec<FieldMatch>,
766) {
767    let binding: Vec<usize> = verdicts
768        .iter()
769        .enumerate()
770        .filter(|(_, matched)| **matched)
771        .map(|(i, _)| i)
772        .take(array::ARRAY_MEMBER_CAP)
773        .collect();
774
775    if binding.is_empty() {
776        out.push(FieldMatch::new(container_path, value.to_json()));
777        return;
778    }
779
780    for i in binding {
781        let member_path = array::array_member_path(&container_path, i, scalar);
782        let before = out.len();
783        collect_array_body_fields(selection, body, members[i], outer, level, &member_path, out);
784        // A binding member whose body produced no leaf entries (e.g. only
785        // `not` branches matched) is still recorded as a whole. At `Off` the
786        // only leafless cases are level-gated ones (keywords, absent-field
787        // matches), which top-level selections also suppress, so the fallback
788        // must not resurrect them.
789        if out.len() == before && level != MatchDetailLevel::Off {
790            out.push(FieldMatch::new(member_path, members[i].to_json()));
791        }
792    }
793}
794
795fn collect_array_body_fields<E: Event>(
796    selection: &str,
797    body: &CompiledDetection,
798    member: &EventValue,
799    outer: &E,
800    level: MatchDetailLevel,
801    member_path: &str,
802    out: &mut Vec<FieldMatch>,
803) {
804    match body {
805        CompiledDetection::AllOf(items) => {
806            for item in items {
807                if !array::eval_array_item(item, member, outer) {
808                    continue;
809                }
810                let relative = item.field.as_deref();
811                let absent =
812                    relative.is_some_and(|name| array::element_field(member, name).is_none());
813                if absent && level == MatchDetailLevel::Off {
814                    continue;
815                }
816                let path = array::join_member_field(member_path, relative);
817                let value = match relative {
818                    Some(name) => array::element_field(member, name)
819                        .map(|v| v.to_json())
820                        .unwrap_or(serde_json::Value::Null),
821                    None => member.to_json(),
822                };
823                out.push(make_field_match(
824                    selection,
825                    &path,
826                    value,
827                    &item.matcher,
828                    level,
829                ));
830            }
831        }
832        CompiledDetection::AnyOf(dets) | CompiledDetection::And(dets) => {
833            for d in dets {
834                if array::eval_array_body(d, member, outer) {
835                    collect_array_body_fields(selection, d, member, outer, level, member_path, out);
836                }
837            }
838        }
839        CompiledDetection::ArrayMatch {
840            field, body: inner, ..
841        } => {
842            collect_array_match_fields(
843                selection,
844                field,
845                inner,
846                array::element_field(member, field),
847                outer,
848                level,
849                member_path,
850                out,
851            );
852        }
853        CompiledDetection::Keywords(matcher) => {
854            if level != MatchDetailLevel::Off && matcher.matches(member, outer) {
855                let d = matcher.describe();
856                out.push(FieldMatch {
857                    field: member_path.to_string(),
858                    value: member.to_json(),
859                    selection: Some(selection.to_string()),
860                    matcher: Some(MatcherKind::Keyword),
861                    pattern: if level == MatchDetailLevel::Full {
862                        d.pattern
863                    } else {
864                        None
865                    },
866                    case_sensitive: d.case_sensitive,
867                    negated: d.negated,
868                });
869            }
870        }
871        CompiledDetection::Conditional { named, condition } => {
872            collect_array_condition_fields(
873                selection,
874                condition,
875                named,
876                member,
877                outer,
878                level,
879                member_path,
880                out,
881            );
882        }
883    }
884}
885
886#[allow(clippy::too_many_arguments)]
887fn collect_array_condition_fields<E: Event>(
888    selection: &str,
889    expr: &ConditionExpr,
890    named: &HashMap<String, CompiledDetection>,
891    member: &EventValue,
892    outer: &E,
893    level: MatchDetailLevel,
894    member_path: &str,
895    out: &mut Vec<FieldMatch>,
896) {
897    match expr {
898        ConditionExpr::Identifier(name) => {
899            if let Some(det) = named.get(name)
900                && array::eval_array_body(det, member, outer)
901            {
902                collect_array_body_fields(selection, det, member, outer, level, member_path, out);
903            }
904        }
905        ConditionExpr::And(exprs) | ConditionExpr::Or(exprs) => {
906            for e in exprs {
907                collect_array_condition_fields(
908                    selection,
909                    e,
910                    named,
911                    member,
912                    outer,
913                    level,
914                    member_path,
915                    out,
916                );
917            }
918        }
919        ConditionExpr::Not(_) => {}
920        ConditionExpr::Selector { pattern, .. } => {
921            let mut names: Vec<&String> = named
922                .keys()
923                .filter(|n| pattern.matches_detection_name(n))
924                .collect();
925            names.sort();
926            for name in names {
927                if let Some(det) = named.get(name)
928                    && array::eval_array_body(det, member, outer)
929                {
930                    collect_array_body_fields(
931                        selection,
932                        det,
933                        member,
934                        outer,
935                        level,
936                        member_path,
937                        out,
938                    );
939                }
940            }
941        }
942    }
943}
944
945/// Build a [`FieldMatch`] at the requested detail level. `Off` yields the
946/// bare `{ field, value }` shape; `Summary` adds the matcher descriptor;
947/// `Full` additionally records the pattern.
948fn make_field_match(
949    selection: &str,
950    field: &str,
951    value: serde_json::Value,
952    matcher: &CompiledMatcher,
953    level: MatchDetailLevel,
954) -> FieldMatch {
955    match level {
956        MatchDetailLevel::Off => FieldMatch::new(field, value),
957        MatchDetailLevel::Summary | MatchDetailLevel::Full => {
958            let d = matcher.describe();
959            FieldMatch {
960                field: field.to_string(),
961                value,
962                selection: Some(selection.to_string()),
963                matcher: Some(d.kind),
964                pattern: if level == MatchDetailLevel::Full {
965                    d.pattern
966                } else {
967                    None
968                },
969                case_sensitive: d.case_sensitive,
970                negated: d.negated,
971            }
972        }
973    }
974}
975
976/// Record the individual event string values that satisfied a keyword
977/// matcher, capped at [`MAX_KEYWORD_MATCHES`]. Each entry uses the sentinel
978/// field name `"keyword"`. An `AllOf` reports the values of each child, and a
979/// negation has no satisfying value to report.
980fn collect_keyword_matches(
981    selection: &str,
982    matcher: &CompiledMatcher,
983    event: &impl Event,
984    level: MatchDetailLevel,
985    out: &mut Vec<FieldMatch>,
986) {
987    match matcher {
988        CompiledMatcher::AllOf(children)
989        | CompiledMatcher::CaseInsensitiveGroup {
990            children,
991            mode: crate::matcher::GroupMode::All,
992        } => {
993            for child in children {
994                collect_keyword_matches(selection, child, event, level, out);
995            }
996            return;
997        }
998        CompiledMatcher::Not(_) => return,
999        _ => {}
1000    }
1001    let descriptor = matcher.describe();
1002    let mut count = 0;
1003    for s in event.all_string_values() {
1004        if count >= MAX_KEYWORD_MATCHES {
1005            break;
1006        }
1007        if matcher.matches_str(&s) {
1008            count += 1;
1009            out.push(FieldMatch {
1010                field: "keyword".to_string(),
1011                value: serde_json::Value::String(s.into_owned()),
1012                selection: Some(selection.to_string()),
1013                matcher: Some(MatcherKind::Keyword),
1014                pattern: if level == MatchDetailLevel::Full {
1015                    descriptor.pattern.clone()
1016                } else {
1017                    None
1018                },
1019                case_sensitive: descriptor.case_sensitive,
1020                negated: descriptor.negated,
1021            });
1022        }
1023    }
1024}