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                    tenant_id: None,
201                    level: rule.level,
202                    tags: rule.tags.clone(),
203                    custom_attributes: rule.custom_attributes.clone(),
204                    enrichments: None,
205                    ruleset: None,
206                },
207                body: ResultBody::Detection(DetectionBody {
208                    matched_selections,
209                    matched_fields,
210                    event: event_data,
211                }),
212            });
213        }
214    }
215    None
216}
217
218// =============================================================================
219// Detection compilation
220// =============================================================================
221
222/// Compile a parsed detection tree into a [`CompiledDetection`].
223///
224/// Routes through the IR layer like [`compile_rule`]: `lower_detection` →
225/// the HIR compiler. Returns an error if the detection tree is empty or
226/// contains invalid items.
227pub fn compile_detection(detection: &Detection) -> Result<CompiledDetection> {
228    let opts = rsigma_ir::LowerOptions {
229        permissive_placeholders: true,
230    };
231    from_ir::compile_ir_detection(&rsigma_ir::lower::lower_detection(detection, &opts)?)
232}
233
234#[cfg(test)]
235fn compile_detection_item(item: &DetectionItem) -> Result<CompiledDetectionItem> {
236    let ir = rsigma_ir::lower::lower_detection_item(item, &rsigma_ir::LowerOptions::default())?;
237    from_ir::compile_ir_detection_item(&ir)
238}
239
240// =============================================================================
241// Condition evaluation
242// =============================================================================
243
244/// Evaluate a condition expression against the event using compiled detections.
245///
246/// Returns `true` if the condition is satisfied. Appends to
247/// `matched_selections`, once each, the matched detections that decide the
248/// result: for `(a and b) or c` firing on `c` alone, only `c`, and for
249/// `a and not b`, only `a`.
250pub fn eval_condition(
251    expr: &ConditionExpr,
252    detections: &HashMap<String, CompiledDetection>,
253    event: &impl Event,
254    matched_selections: &mut Vec<String>,
255) -> bool {
256    let mut detail = Vec::new();
257    let result = eval_condition_detail(
258        expr,
259        detections,
260        event,
261        &crate::engine::bloom_index::NoBloom,
262        MatchDetailLevel::Off,
263        &mut detail,
264    );
265    matched_selections.extend(flatten_detail(detail).0);
266    result
267}
268
269/// Evaluate a condition without collecting match details.
270///
271/// This is the production fast path for the common nonmatch case. Selectors
272/// can stop as soon as their quantifier is decided; matching rules run the
273/// detail-collecting evaluator once afterward.
274fn eval_condition_matches_with_bloom<E, B>(
275    expr: &ConditionExpr,
276    detections: &HashMap<String, CompiledDetection>,
277    event: &E,
278    bloom: &B,
279) -> bool
280where
281    E: Event,
282    B: crate::engine::bloom_index::BloomLookup,
283{
284    match expr {
285        ConditionExpr::Identifier(name) => detections
286            .get(name)
287            .is_some_and(|det| eval_detection_with_bloom(det, event, bloom)),
288        ConditionExpr::And(exprs) => exprs
289            .iter()
290            .all(|e| eval_condition_matches_with_bloom(e, detections, event, bloom)),
291        ConditionExpr::Or(exprs) => exprs
292            .iter()
293            .any(|e| eval_condition_matches_with_bloom(e, detections, event, bloom)),
294        ConditionExpr::Not(inner) => {
295            !eval_condition_matches_with_bloom(inner, detections, event, bloom)
296        }
297        ConditionExpr::Selector {
298            quantifier,
299            pattern,
300        } => {
301            let mut matching = detections
302                .iter()
303                .filter(|(name, _)| pattern.matches_detection_name(name));
304            match quantifier {
305                Quantifier::Any => {
306                    matching.any(|(_, det)| eval_detection_with_bloom(det, event, bloom))
307                }
308                Quantifier::All => {
309                    matching.all(|(_, det)| eval_detection_with_bloom(det, event, bloom))
310                }
311                Quantifier::Count(required) => {
312                    let mut matched = 0u64;
313                    matching.any(|(_, det)| {
314                        if eval_detection_with_bloom(det, event, bloom) {
315                            matched += 1;
316                        }
317                        matched >= required.get()
318                    })
319                }
320            }
321        }
322    }
323}
324
325/// A matched selection and the field matches it recorded.
326struct SelectionDetail {
327    name: String,
328    fields: Vec<FieldMatch>,
329}
330
331/// Selection names, once each in first-seen order, and their field matches.
332fn flatten_detail(detail: Vec<SelectionDetail>) -> (Vec<String>, Vec<FieldMatch>) {
333    let mut seen = std::collections::HashSet::new();
334    let mut names = Vec::new();
335    let mut fields = Vec::new();
336    for selection in detail {
337        if seen.insert(selection.name.clone()) {
338            names.push(selection.name);
339            fields.extend(selection.fields);
340        }
341    }
342    (names, fields)
343}
344
345/// The detail pass: evaluate `expr` and record in `out` the matched
346/// selections that decide its value, each with the field matches it produced
347/// while being evaluated.
348fn eval_condition_detail<E, B>(
349    expr: &ConditionExpr,
350    detections: &HashMap<String, CompiledDetection>,
351    event: &E,
352    bloom: &B,
353    level: MatchDetailLevel,
354    out: &mut Vec<SelectionDetail>,
355) -> bool
356where
357    E: Event,
358    B: crate::engine::bloom_index::BloomLookup,
359{
360    match expr {
361        ConditionExpr::Identifier(name) => {
362            let Some(det) = detections.get(name) else {
363                return false;
364            };
365            let mut fields = Vec::new();
366            let result = eval_detection_recording(name, det, event, bloom, level, &mut fields);
367            if result {
368                out.push(SelectionDetail {
369                    name: name.clone(),
370                    fields,
371                });
372            }
373            result
374        }
375
376        // A false `and` is explained by its failing child alone, and a true
377        // `or` by its true child alone, so drop what the other children
378        // recorded. `not` keeps its child's names unchanged: they explain the
379        // child's value, which decides the negation.
380        ConditionExpr::And(exprs) => {
381            let mark = out.len();
382            for e in exprs {
383                let child_mark = out.len();
384                if !eval_condition_detail(e, detections, event, bloom, level, out) {
385                    out.drain(mark..child_mark);
386                    return false;
387                }
388            }
389            true
390        }
391
392        ConditionExpr::Or(exprs) => {
393            let mark = out.len();
394            for e in exprs {
395                let child_mark = out.len();
396                if eval_condition_detail(e, detections, event, bloom, level, out) {
397                    out.drain(mark..child_mark);
398                    return true;
399                }
400            }
401            false
402        }
403
404        ConditionExpr::Not(inner) => {
405            !eval_condition_detail(inner, detections, event, bloom, level, out)
406        }
407
408        ConditionExpr::Selector {
409            quantifier,
410            pattern,
411        } => {
412            let mut candidates = 0usize;
413            let mut matched = Vec::new();
414            for (name, det) in detections
415                .iter()
416                .filter(|(name, _)| pattern.matches_detection_name(name))
417            {
418                candidates += 1;
419                let mut fields = Vec::new();
420                if eval_detection_recording(name, det, event, bloom, level, &mut fields) {
421                    matched.push(SelectionDetail {
422                        name: name.clone(),
423                        fields,
424                    });
425                }
426            }
427
428            let holds = match quantifier {
429                Quantifier::Any => !matched.is_empty(),
430                Quantifier::All => matched.len() == candidates,
431                Quantifier::Count(n) => matched.len() as u64 >= n.get(),
432            };
433            // Matched members explain a quantifier that holds; when it fails,
434            // only the members that did not match do, and those report nothing.
435            if holds {
436                out.extend(matched);
437            }
438            holds
439        }
440    }
441}
442
443/// Evaluate a compiled detection item against an event without bloom
444/// pre-filtering. Used only by the in-crate compiler tests; the production
445/// paths run through `eval_detection_item_with_bloom` from
446/// `evaluate_rule_with_bloom`.
447#[cfg(test)]
448fn eval_detection_item(item: &CompiledDetectionItem, event: &impl Event) -> bool {
449    eval_detection_item_with_bloom(item, event, &crate::engine::bloom_index::NoBloom)
450}
451
452/// Evaluate a single compiled detection item against an event without bloom
453/// pre-filtering. Used by the [`crate::explain`] recording evaluator so each
454/// per-item verdict matches the production engine exactly.
455pub(crate) fn eval_detection_item_no_bloom(
456    item: &CompiledDetectionItem,
457    event: &impl Event,
458) -> bool {
459    eval_detection_item_with_bloom(item, event, &crate::engine::bloom_index::NoBloom)
460}
461
462/// Evaluate a compiled detection against an event with a bloom lookup.
463fn eval_detection_with_bloom<E, B>(detection: &CompiledDetection, event: &E, bloom: &B) -> bool
464where
465    E: Event,
466    B: crate::engine::bloom_index::BloomLookup,
467{
468    match detection {
469        CompiledDetection::AllOf(items) => items
470            .iter()
471            .all(|item| eval_detection_item_with_bloom(item, event, bloom)),
472        CompiledDetection::AnyOf(dets) => dets
473            .iter()
474            .any(|d| eval_detection_with_bloom(d, event, bloom)),
475        CompiledDetection::Keywords(matcher) => matcher.matches_keyword(event),
476        CompiledDetection::ArrayMatch {
477            field,
478            quantifier,
479            body,
480        } => match event.get_field(field) {
481            Some(value) => eval_array_quantified(&value, *quantifier, body, event),
482            None => array_quantifier_matches_empty(*quantifier),
483        },
484        CompiledDetection::And(dets) => dets
485            .iter()
486            .all(|d| eval_detection_with_bloom(d, event, bloom)),
487        // Only produced as an `ArrayMatch` body (evaluated via
488        // `eval_array_condition`). At the top level it degenerates to a
489        // sub-rule over the event, which reuses the condition evaluator.
490        CompiledDetection::Conditional { named, condition } => {
491            eval_condition_matches_with_bloom(condition, named, event, bloom)
492        }
493    }
494}
495
496/// Evaluate a single detection item with bloom pre-filtering.
497///
498/// When the matcher targets a single field and is a positive substring
499/// matcher (not under negation), the bloom verdict is consulted first. A
500/// `DefinitelyNoMatch` verdict guarantees the matcher would return `false`,
501/// so we return early without invoking it.
502fn eval_detection_item_with_bloom<E, B>(item: &CompiledDetectionItem, event: &E, bloom: &B) -> bool
503where
504    E: Event,
505    B: crate::engine::bloom_index::BloomLookup,
506{
507    if let Some(expect_exists) = item.exists {
508        if let Some(field) = &item.field {
509            return event.get_field(field).is_some() == expect_exists;
510        }
511        return !expect_exists;
512    }
513
514    match &item.field {
515        Some(field_name) => {
516            if let Some(value) = event.get_field(field_name) {
517                if item.bloom_eligible
518                    && bloom.verdict_for_field(field_name)
519                        == crate::engine::bloom_index::BloomVerdict::DefinitelyNoMatch
520                {
521                    return false;
522                }
523                item.matcher.matches(&value, event)
524            } else {
525                item.matcher.matches_absent()
526            }
527        }
528        None => item.matcher.matches_keyword(event),
529    }
530}
531
532/// Cap on the number of keyword-match entries recorded per keyword detection
533/// at `Summary` / `Full`. A single high-cardinality event (many string
534/// leaves) cannot blow up the output line.
535const MAX_KEYWORD_MATCHES: usize = 16;
536
537/// Evaluate a detection, recording its field matches in `out` when it holds.
538///
539/// At [`MatchDetailLevel::Off`] the entries keep the historical shape: one
540/// `{ field, value }` per field-present `AllOf` item, with keyword and
541/// absence matches omitted. At `Summary` / `Full` they carry the matcher
542/// descriptor, and keyword and `Null`-on-absent matches are reported too. A
543/// detection that does not hold leaves `out` unchanged.
544fn eval_detection_recording<E, B>(
545    selection: &str,
546    detection: &CompiledDetection,
547    event: &E,
548    bloom: &B,
549    level: MatchDetailLevel,
550    out: &mut Vec<FieldMatch>,
551) -> bool
552where
553    E: Event,
554    B: crate::engine::bloom_index::BloomLookup,
555{
556    match detection {
557        CompiledDetection::AllOf(items) => {
558            let mark = out.len();
559            for item in items {
560                if !eval_item_recording(selection, item, event, bloom, level, out) {
561                    out.truncate(mark);
562                    return false;
563                }
564            }
565            true
566        }
567        CompiledDetection::AnyOf(dets) => {
568            // Every matching branch reports its fields, so evaluate them all.
569            let mut any = false;
570            for d in dets {
571                any |= eval_detection_recording(selection, d, event, bloom, level, out);
572            }
573            any
574        }
575        CompiledDetection::And(dets) => {
576            let mark = out.len();
577            for d in dets {
578                if !eval_detection_recording(selection, d, event, bloom, level, out) {
579                    out.truncate(mark);
580                    return false;
581                }
582            }
583            true
584        }
585        CompiledDetection::Keywords(matcher) => {
586            let matched = matcher.matches_keyword(event);
587            if matched && level != MatchDetailLevel::Off {
588                collect_keyword_matches(selection, matcher, event, level, out);
589            }
590            matched
591        }
592        CompiledDetection::ArrayMatch {
593            field,
594            quantifier,
595            body,
596        } => {
597            let value = event.get_field(field);
598            let Some(value) = value.as_ref() else {
599                return array_quantifier_matches_empty(*quantifier);
600            };
601            let (scalar, members) = array_members(value);
602            let verdicts: Vec<bool> = members
603                .iter()
604                .map(|m| array::eval_array_body(body, m, event))
605                .collect();
606            let holds = array::array_quantifier_from_member_matches(*quantifier, &verdicts);
607            if holds {
608                record_array_members(
609                    selection,
610                    field.clone(),
611                    body,
612                    value,
613                    scalar,
614                    &members,
615                    &verdicts,
616                    event,
617                    level,
618                    out,
619                );
620            }
621            holds
622        }
623        // Only produced as an array body, where members are recorded by
624        // `collect_array_body_fields`.
625        CompiledDetection::Conditional { named, condition } => {
626            eval_condition_matches_with_bloom(condition, named, event, bloom)
627        }
628    }
629}
630
631/// Evaluate one `AllOf` item, recording its field match in `out` when it holds.
632fn eval_item_recording<E, B>(
633    selection: &str,
634    item: &CompiledDetectionItem,
635    event: &E,
636    bloom: &B,
637    level: MatchDetailLevel,
638    out: &mut Vec<FieldMatch>,
639) -> bool
640where
641    E: Event,
642    B: crate::engine::bloom_index::BloomLookup,
643{
644    let Some(field_name) = &item.field else {
645        let matched = match item.exists {
646            Some(expect) => !expect,
647            None => item.matcher.matches_keyword(event),
648        };
649        if matched && level != MatchDetailLevel::Off {
650            collect_keyword_matches(selection, &item.matcher, event, level, out);
651        }
652        return matched;
653    };
654
655    match event.get_field(field_name) {
656        Some(value) => {
657            let matched = match item.exists {
658                Some(expect) => expect,
659                None => {
660                    !(item.bloom_eligible
661                        && bloom.verdict_for_field(field_name)
662                            == crate::engine::bloom_index::BloomVerdict::DefinitelyNoMatch)
663                        && item.matcher.matches(&value, event)
664                }
665            };
666            if matched {
667                out.push(make_field_match(
668                    selection,
669                    field_name,
670                    value.to_json(),
671                    &item.matcher,
672                    level,
673                ));
674            }
675            matched
676        }
677        None => {
678            let matched = match item.exists {
679                Some(expect) => !expect,
680                None => item.matcher.matches_absent(),
681            };
682            // Absent-field matches are never reported at `Off`, which keeps
683            // the historical wire shape.
684            if matched && level != MatchDetailLevel::Off {
685                out.push(make_field_match(
686                    selection,
687                    field_name,
688                    serde_json::Value::Null,
689                    &item.matcher,
690                    level,
691                ));
692            }
693            matched
694        }
695    }
696}
697
698/// The members of an array-match value and whether it is a scalar treated as
699/// one member. A null value has no members.
700fn array_members<'v>(value: &'v EventValue<'v>) -> (bool, Vec<&'v EventValue<'v>>) {
701    match value {
702        EventValue::Null => (false, Vec::new()),
703        EventValue::Array(items) => (false, items.iter().collect()),
704        single => (true, vec![single]),
705    }
706}
707
708/// Record the binding members of a nested `ArrayMatch` inside a matched
709/// array member.
710#[allow(clippy::too_many_arguments)]
711fn collect_array_match_fields<E: Event>(
712    selection: &str,
713    field: &str,
714    body: &CompiledDetection,
715    value: Option<&EventValue>,
716    outer: &E,
717    level: MatchDetailLevel,
718    path_prefix: &str,
719    out: &mut Vec<FieldMatch>,
720) {
721    let Some(value) = value else {
722        return;
723    };
724    let (scalar, members) = array_members(value);
725    let verdicts: Vec<bool> = members
726        .iter()
727        .map(|m| array::eval_array_body(body, m, outer))
728        .collect();
729    let container_path = if path_prefix.is_empty() {
730        field.to_string()
731    } else {
732        array::join_member_field(path_prefix, Some(field))
733    };
734    record_array_members(
735        selection,
736        container_path,
737        body,
738        value,
739        scalar,
740        &members,
741        &verdicts,
742        outer,
743        level,
744        out,
745    );
746}
747
748/// Record the binding members of a matched `ArrayMatch` from its per-member
749/// body verdicts.
750///
751/// Matching members are emitted with indexed paths (`field[i].leaf`) up to
752/// [`array::ARRAY_MEMBER_CAP`]. A scalar treated as one member uses the
753/// un-indexed path so it still resolves through [`Event::get_field`]. With no
754/// binding member (`[none]`, vacuous `[all_or_empty]`, or a null or empty
755/// array), the container is recorded.
756#[allow(clippy::too_many_arguments)]
757fn record_array_members<E: Event>(
758    selection: &str,
759    container_path: String,
760    body: &CompiledDetection,
761    value: &EventValue,
762    scalar: bool,
763    members: &[&EventValue],
764    verdicts: &[bool],
765    outer: &E,
766    level: MatchDetailLevel,
767    out: &mut Vec<FieldMatch>,
768) {
769    let binding: Vec<usize> = verdicts
770        .iter()
771        .enumerate()
772        .filter(|(_, matched)| **matched)
773        .map(|(i, _)| i)
774        .take(array::ARRAY_MEMBER_CAP)
775        .collect();
776
777    if binding.is_empty() {
778        out.push(FieldMatch::new(container_path, value.to_json()));
779        return;
780    }
781
782    for i in binding {
783        let member_path = array::array_member_path(&container_path, i, scalar);
784        let before = out.len();
785        collect_array_body_fields(selection, body, members[i], outer, level, &member_path, out);
786        // A binding member whose body produced no leaf entries (e.g. only
787        // `not` branches matched) is still recorded as a whole. At `Off` the
788        // only leafless cases are level-gated ones (keywords, absent-field
789        // matches), which top-level selections also suppress, so the fallback
790        // must not resurrect them.
791        if out.len() == before && level != MatchDetailLevel::Off {
792            out.push(FieldMatch::new(member_path, members[i].to_json()));
793        }
794    }
795}
796
797fn collect_array_body_fields<E: Event>(
798    selection: &str,
799    body: &CompiledDetection,
800    member: &EventValue,
801    outer: &E,
802    level: MatchDetailLevel,
803    member_path: &str,
804    out: &mut Vec<FieldMatch>,
805) {
806    match body {
807        CompiledDetection::AllOf(items) => {
808            for item in items {
809                if !array::eval_array_item(item, member, outer) {
810                    continue;
811                }
812                let relative = item.field.as_deref();
813                let absent =
814                    relative.is_some_and(|name| array::element_field(member, name).is_none());
815                if absent && level == MatchDetailLevel::Off {
816                    continue;
817                }
818                let path = array::join_member_field(member_path, relative);
819                let value = match relative {
820                    Some(name) => array::element_field(member, name)
821                        .map(|v| v.to_json())
822                        .unwrap_or(serde_json::Value::Null),
823                    None => member.to_json(),
824                };
825                out.push(make_field_match(
826                    selection,
827                    &path,
828                    value,
829                    &item.matcher,
830                    level,
831                ));
832            }
833        }
834        CompiledDetection::AnyOf(dets) | CompiledDetection::And(dets) => {
835            for d in dets {
836                if array::eval_array_body(d, member, outer) {
837                    collect_array_body_fields(selection, d, member, outer, level, member_path, out);
838                }
839            }
840        }
841        CompiledDetection::ArrayMatch {
842            field, body: inner, ..
843        } => {
844            collect_array_match_fields(
845                selection,
846                field,
847                inner,
848                array::element_field(member, field),
849                outer,
850                level,
851                member_path,
852                out,
853            );
854        }
855        CompiledDetection::Keywords(matcher) => {
856            if level != MatchDetailLevel::Off && matcher.matches(member, outer) {
857                let d = matcher.describe();
858                out.push(FieldMatch {
859                    field: member_path.to_string(),
860                    value: member.to_json(),
861                    selection: Some(selection.to_string()),
862                    matcher: Some(MatcherKind::Keyword),
863                    pattern: if level == MatchDetailLevel::Full {
864                        d.pattern
865                    } else {
866                        None
867                    },
868                    case_sensitive: d.case_sensitive,
869                    negated: d.negated,
870                });
871            }
872        }
873        CompiledDetection::Conditional { named, condition } => {
874            collect_array_condition_fields(
875                selection,
876                condition,
877                named,
878                member,
879                outer,
880                level,
881                member_path,
882                out,
883            );
884        }
885    }
886}
887
888#[allow(clippy::too_many_arguments)]
889fn collect_array_condition_fields<E: Event>(
890    selection: &str,
891    expr: &ConditionExpr,
892    named: &HashMap<String, CompiledDetection>,
893    member: &EventValue,
894    outer: &E,
895    level: MatchDetailLevel,
896    member_path: &str,
897    out: &mut Vec<FieldMatch>,
898) {
899    match expr {
900        ConditionExpr::Identifier(name) => {
901            if let Some(det) = named.get(name)
902                && array::eval_array_body(det, member, outer)
903            {
904                collect_array_body_fields(selection, det, member, outer, level, member_path, out);
905            }
906        }
907        ConditionExpr::And(exprs) | ConditionExpr::Or(exprs) => {
908            for e in exprs {
909                collect_array_condition_fields(
910                    selection,
911                    e,
912                    named,
913                    member,
914                    outer,
915                    level,
916                    member_path,
917                    out,
918                );
919            }
920        }
921        ConditionExpr::Not(_) => {}
922        ConditionExpr::Selector { pattern, .. } => {
923            let mut names: Vec<&String> = named
924                .keys()
925                .filter(|n| pattern.matches_detection_name(n))
926                .collect();
927            names.sort();
928            for name in names {
929                if let Some(det) = named.get(name)
930                    && array::eval_array_body(det, member, outer)
931                {
932                    collect_array_body_fields(
933                        selection,
934                        det,
935                        member,
936                        outer,
937                        level,
938                        member_path,
939                        out,
940                    );
941                }
942            }
943        }
944    }
945}
946
947/// Build a [`FieldMatch`] at the requested detail level. `Off` yields the
948/// bare `{ field, value }` shape; `Summary` adds the matcher descriptor;
949/// `Full` additionally records the pattern.
950fn make_field_match(
951    selection: &str,
952    field: &str,
953    value: serde_json::Value,
954    matcher: &CompiledMatcher,
955    level: MatchDetailLevel,
956) -> FieldMatch {
957    match level {
958        MatchDetailLevel::Off => FieldMatch::new(field, value),
959        MatchDetailLevel::Summary | MatchDetailLevel::Full => {
960            let d = matcher.describe();
961            FieldMatch {
962                field: field.to_string(),
963                value,
964                selection: Some(selection.to_string()),
965                matcher: Some(d.kind),
966                pattern: if level == MatchDetailLevel::Full {
967                    d.pattern
968                } else {
969                    None
970                },
971                case_sensitive: d.case_sensitive,
972                negated: d.negated,
973            }
974        }
975    }
976}
977
978/// Record the individual event string values that satisfied a keyword
979/// matcher, capped at [`MAX_KEYWORD_MATCHES`]. Each entry uses the sentinel
980/// field name `"keyword"`. An `AllOf` reports the values of each child, and a
981/// negation has no satisfying value to report.
982fn collect_keyword_matches(
983    selection: &str,
984    matcher: &CompiledMatcher,
985    event: &impl Event,
986    level: MatchDetailLevel,
987    out: &mut Vec<FieldMatch>,
988) {
989    match matcher {
990        CompiledMatcher::AllOf(children)
991        | CompiledMatcher::CaseInsensitiveGroup {
992            children,
993            mode: crate::matcher::GroupMode::All,
994        } => {
995            for child in children {
996                collect_keyword_matches(selection, child, event, level, out);
997            }
998            return;
999        }
1000        CompiledMatcher::Not(_) => return,
1001        _ => {}
1002    }
1003    let descriptor = matcher.describe();
1004    let mut count = 0;
1005    for s in event.all_string_values() {
1006        if count >= MAX_KEYWORD_MATCHES {
1007            break;
1008        }
1009        if matcher.matches_str(&s) {
1010            count += 1;
1011            out.push(FieldMatch {
1012                field: "keyword".to_string(),
1013                value: serde_json::Value::String(s.into_owned()),
1014                selection: Some(selection.to_string()),
1015                matcher: Some(MatcherKind::Keyword),
1016                pattern: if level == MatchDetailLevel::Full {
1017                    descriptor.pattern.clone()
1018                } else {
1019                    None
1020                },
1021                case_sensitive: descriptor.case_sensitive,
1022                negated: descriptor.negated,
1023            });
1024        }
1025    }
1026}