rsigma-convert 0.20.0

Sigma rule conversion engine — convert rules to backend-native query strings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
//! Reverse conversion: SIEM query strings → Sigma YAML.
//!
//! This is the mirror image of the forward [`Backend`](crate::Backend) engine.
//! Where a backend lowers a rule's HIR into a query string, a [`Frontend`]
//! parses a query string into the shared HIR ([`IrRule`]), which is then raised
//! to a [`SigmaRule`] and emitted as Sigma YAML.
//!
//! ```text
//! query -> Frontend::parse_query() -> IrRule -> raise_rule() -> SigmaRule -> emit_rule_yaml()
//! ```
//!
//! The framework owns everything that is dialect-independent: a
//! [`QueryDialect`]-driven tokenizer, a precedence-climbing boolean parser
//! (`NOT` > `AND` > `OR`), and the assembly of a boolean tree of leaves into
//! named Sigma selections plus a condition. A target dialect (e.g.
//! [`lucene`]) supplies a [`QueryDialect`] and a single
//! [`Frontend::parse_atom`] that interprets one leaf predicate; everything else
//! is shared, so a new target is a dialect table plus a leaf parser.
//!
//! Reverse conversion is best-effort: a query carries no rule metadata, so the
//! [`ReverseCtx`] supplies the title, id, logsource, level, and status, and
//! constructs a query cannot express are rejected with a structured
//! [`ConvertError`] rather than emitted as silently-wrong Sigma.

pub mod lucene;

use std::collections::HashMap;

use rsigma_ir::{
    IrCondition, IrDetection, IrDetectionItem, IrMatcher, IrPattern, IrPatternPart, IrRule,
    IrRuleMetadata, IrStrOp, RaiseOptions, raise_rule,
};
use rsigma_parser::{Level, LogSource, SigmaRule, SigmaString, Status, StringPart};

use crate::error::{ConvertError, Result};

pub use lucene::{LUCENE_DIALECT, LuceneFrontend};

// =============================================================================
// Dialect
// =============================================================================

/// Boolean-syntax configuration for a query dialect. The reverse analogue of
/// the boolean-operator half of [`TextQueryConfig`](crate::TextQueryConfig): a
/// pure data table that drives the shared tokenizer and boolean parser.
///
/// Leaf syntax (field predicates, ranges, quoting, wildcards) is dialect
/// specific and handled by [`Frontend::parse_atom`], not here.
#[derive(Debug, Clone, Copy)]
pub struct QueryDialect {
    /// Human-readable dialect name (`"lucene"`).
    pub name: &'static str,
    /// Tokens that mean logical AND (e.g. `["AND", "&&"]`).
    pub and_tokens: &'static [&'static str],
    /// Tokens that mean logical OR (e.g. `["OR", "||"]`).
    pub or_tokens: &'static [&'static str],
    /// Tokens (and prefixes) that mean logical NOT (e.g. `["NOT", "!"]`).
    pub not_tokens: &'static [&'static str],
    /// Whether adjacent terms with no explicit operator are ANDed (`true`) or
    /// ORed (`false`).
    pub implicit_and: bool,
}

// =============================================================================
// Boolean expression tree
// =============================================================================

/// A boolean expression tree over leaves of type `L`.
///
/// The tokenizer/parser produce `QueryExpr<String>` (leaves are raw atom
/// strings); [`Frontend::parse_atom`] expands each atom into a
/// `QueryExpr<QueryLeaf>` sub-tree (a range atom becomes an `And` of two
/// bounds, a value group becomes an `Or`, and so on).
#[derive(Debug, Clone, PartialEq)]
pub enum QueryExpr<L> {
    And(Vec<QueryExpr<L>>),
    Or(Vec<QueryExpr<L>>),
    Not(Box<QueryExpr<L>>),
    Leaf(L),
}

impl<L> QueryExpr<L> {
    /// Replace every leaf with a sub-tree, splicing the results in place.
    fn expand<T, F>(self, f: &mut F) -> Result<QueryExpr<T>>
    where
        F: FnMut(L) -> Result<QueryExpr<T>>,
    {
        match self {
            QueryExpr::And(items) => Ok(QueryExpr::And(
                items
                    .into_iter()
                    .map(|e| e.expand(f))
                    .collect::<Result<_>>()?,
            )),
            QueryExpr::Or(items) => Ok(QueryExpr::Or(
                items
                    .into_iter()
                    .map(|e| e.expand(f))
                    .collect::<Result<_>>()?,
            )),
            QueryExpr::Not(inner) => Ok(QueryExpr::Not(Box::new(inner.expand(f)?))),
            QueryExpr::Leaf(leaf) => f(leaf),
        }
    }
}

/// One resolved leaf predicate.
#[derive(Debug, Clone, PartialEq)]
pub enum QueryLeaf {
    /// A field-bound match (`field: matcher`).
    Field { field: String, matcher: IrMatcher },
    /// A field-less keyword / free-text match.
    Keyword(IrMatcher),
}

// =============================================================================
// Context and output
// =============================================================================

/// Metadata and options the query string cannot supply. Owns the
/// selection-naming scheme through [`assemble_rule`].
#[derive(Debug, Clone, Default)]
pub struct ReverseCtx {
    pub title: Option<String>,
    pub id: Option<String>,
    pub status: Option<Status>,
    pub level: Option<Level>,
    pub product: Option<String>,
    pub category: Option<String>,
    pub service: Option<String>,
    /// Reserved for strict mode (reject best-effort fallbacks). Currently the
    /// framework already rejects inexpressible constructs unconditionally.
    pub strict: bool,
}

impl ReverseCtx {
    fn metadata(&self) -> IrRuleMetadata {
        IrRuleMetadata {
            title: self
                .title
                .clone()
                .unwrap_or_else(|| "Converted query".to_string()),
            id: self.id.clone(),
            level: self.level,
            status: self.status,
            ..Default::default()
        }
    }

    fn logsource(&self) -> LogSource {
        LogSource {
            category: self.category.clone(),
            product: self.product.clone(),
            service: self.service.clone(),
            definition: None,
            custom: HashMap::new(),
        }
    }
}

/// One successful reverse conversion.
#[derive(Debug, Clone)]
pub struct ReverseResult {
    /// The source query.
    pub query: String,
    /// The raised Sigma rule.
    pub rule: SigmaRule,
    /// The emitted Sigma YAML.
    pub yaml: String,
}

/// The result of converting a batch of queries: successes plus per-query errors
/// (the batch never aborts on a single failure), mirroring
/// [`convert_collection`](crate::convert_collection).
#[derive(Debug, Default)]
pub struct ReverseOutput {
    pub rules: Vec<ReverseResult>,
    pub errors: Vec<(String, ConvertError)>,
}

// =============================================================================
// Frontend trait
// =============================================================================

/// A reverse-conversion target: parses one query dialect into the HIR.
///
/// The inverse of [`Backend`](crate::Backend). Implementors provide a
/// [`QueryDialect`] and a leaf parser; the default [`Frontend::parse_query`]
/// tokenizes, builds the boolean tree, expands each atom via
/// [`Frontend::parse_atom`], and assembles the [`IrRule`].
pub trait Frontend {
    /// The dialect name (`"lucene"`).
    fn name(&self) -> &str;

    /// The boolean-syntax configuration.
    fn dialect(&self) -> &QueryDialect;

    /// Parse a single leaf atom (a `field:value`, range, value group, or bare
    /// term) into a boolean sub-tree of resolved leaves.
    fn parse_atom(&self, atom: &str, ctx: &ReverseCtx) -> Result<QueryExpr<QueryLeaf>>;

    /// Parse a full query into an [`IrRule`].
    fn parse_query(&self, query: &str, ctx: &ReverseCtx) -> Result<IrRule> {
        let dialect = self.dialect();
        let tokens = tokenize(dialect, query)?;
        let tree = parse_boolean(dialect, tokens)?;
        let mut expand = |atom: String| self.parse_atom(&atom, ctx);
        let resolved = tree.expand(&mut expand)?;
        assemble_rule(resolved, ctx)
    }
}

/// Convert a batch of queries, collecting per-query errors instead of aborting.
pub fn reverse_collection(
    frontend: &dyn Frontend,
    queries: &[String],
    ctx: &ReverseCtx,
) -> ReverseOutput {
    let mut output = ReverseOutput::default();
    for query in queries {
        match convert_one(frontend, query, ctx) {
            Ok(result) => output.rules.push(result),
            Err(e) => output.errors.push((query.clone(), e)),
        }
    }
    output
}

fn convert_one(frontend: &dyn Frontend, query: &str, ctx: &ReverseCtx) -> Result<ReverseResult> {
    let ir = frontend.parse_query(query, ctx)?;
    let rule = raise_rule(&ir, &RaiseOptions::default())
        .map_err(|e| ConvertError::RuleConversion(e.to_string()))?;
    let yaml = rsigma_parser::emit_rule_yaml(&rule);
    Ok(ReverseResult {
        query: query.to_string(),
        rule,
        yaml,
    })
}

// =============================================================================
// Tokenizer
// =============================================================================

#[derive(Debug, Clone, PartialEq)]
enum Token {
    LParen,
    RParen,
    And,
    Or,
    Not,
    Atom(String),
}

/// Split a query into boolean tokens. Quoted strings, `/regex/`, `[range]`,
/// `{range}`, and `field:(value group)` spans are kept atomic (including their
/// internal whitespace); `+`/`-` term prefixes become required/NOT.
fn tokenize(dialect: &QueryDialect, query: &str) -> Result<Vec<Token>> {
    let chars: Vec<char> = query.chars().collect();
    let mut tokens = Vec::new();
    let mut i = 0;
    // True at the start of a term slot (start of input, after `(`, or after an
    // operator), where `+`/`-` act as prefixes.
    let mut at_term_start = true;

    while i < chars.len() {
        if chars[i].is_whitespace() {
            i += 1;
            continue;
        }
        match chars[i] {
            '(' => {
                tokens.push(Token::LParen);
                i += 1;
                at_term_start = true;
                continue;
            }
            ')' => {
                tokens.push(Token::RParen);
                i += 1;
                at_term_start = false;
                continue;
            }
            _ => {}
        }

        if let Some((token, consumed)) = match_operator(dialect, &chars, i) {
            tokens.push(token);
            i += consumed;
            at_term_start = true;
            continue;
        }

        if at_term_start && (chars[i] == '+' || chars[i] == '-') {
            if chars[i] == '-' {
                tokens.push(Token::Not);
            }
            i += 1;
            continue;
        }

        let (atom, consumed) = read_atom(&chars, i)?;
        if consumed == 0 {
            return Err(ConvertError::QueryParse(format!(
                "unexpected character '{}' at position {i}",
                chars[i]
            )));
        }
        tokens.push(Token::Atom(atom));
        i += consumed;
        at_term_start = false;
    }

    if tokens.is_empty() {
        return Err(ConvertError::QueryParse("empty query".into()));
    }
    Ok(tokens)
}

fn match_operator(dialect: &QueryDialect, chars: &[char], i: usize) -> Option<(Token, usize)> {
    for (token, list) in [
        (Token::And, dialect.and_tokens),
        (Token::Or, dialect.or_tokens),
        (Token::Not, dialect.not_tokens),
    ] {
        for &candidate in list {
            if token_matches(chars, i, candidate) {
                return Some((token.clone(), candidate.chars().count()));
            }
        }
    }
    None
}

/// Match a literal operator token at `i`. Alphabetic operators (`AND`) require a
/// trailing word boundary so `ANDROID` is not read as `AND`.
fn token_matches(chars: &[char], i: usize, token: &str) -> bool {
    let token_chars: Vec<char> = token.chars().collect();
    if i + token_chars.len() > chars.len() {
        return false;
    }
    if chars[i..i + token_chars.len()] != token_chars[..] {
        return false;
    }
    if token_chars.iter().all(|c| c.is_ascii_alphabetic()) {
        match chars.get(i + token_chars.len()) {
            None => true,
            Some(c) => c.is_whitespace() || *c == '(' || *c == ')',
        }
    } else {
        true
    }
}

/// Read one atom, keeping quotes/regex/ranges/value-groups (and their internal
/// whitespace) together.
fn read_atom(chars: &[char], start: usize) -> Result<(String, usize)> {
    let mut out = String::new();
    let mut i = start;
    while i < chars.len() {
        let c = chars[i];
        if c.is_whitespace() || c == ')' {
            break;
        }
        match c {
            '(' if out.ends_with(':') => {
                let (group, consumed) = read_balanced(chars, i, '(', ')')?;
                out.push_str(&group);
                i += consumed;
            }
            '(' => break,
            '"' | '\'' => {
                let (quoted, consumed) = read_quoted(chars, i, c)?;
                out.push_str(&quoted);
                i += consumed;
            }
            '/' if out.ends_with(':') => {
                let (regex, consumed) = read_quoted(chars, i, '/')?;
                out.push_str(&regex);
                i += consumed;
            }
            '[' => {
                let (range, consumed) = read_balanced(chars, i, '[', ']')?;
                out.push_str(&range);
                i += consumed;
            }
            '{' => {
                let (range, consumed) = read_balanced(chars, i, '{', '}')?;
                out.push_str(&range);
                i += consumed;
            }
            '\\' => {
                out.push('\\');
                i += 1;
                if i < chars.len() {
                    out.push(chars[i]);
                    i += 1;
                }
            }
            other => {
                out.push(other);
                i += 1;
            }
        }
    }
    Ok((out, i - start))
}

/// Read a `delim ... delim` span (quotes or regex), preserving escapes.
fn read_quoted(chars: &[char], start: usize, delim: char) -> Result<(String, usize)> {
    let mut out = String::new();
    out.push(chars[start]);
    let mut i = start + 1;
    while i < chars.len() {
        let c = chars[i];
        out.push(c);
        i += 1;
        if c == '\\' && i < chars.len() {
            out.push(chars[i]);
            i += 1;
            continue;
        }
        if c == delim {
            return Ok((out, i - start));
        }
    }
    Err(ConvertError::QueryParse(format!(
        "unterminated {delim}-delimited value"
    )))
}

/// Read a balanced `open ... close` span (ranges, value groups).
fn read_balanced(chars: &[char], start: usize, open: char, close: char) -> Result<(String, usize)> {
    let mut out = String::new();
    let mut depth = 0usize;
    let mut i = start;
    while i < chars.len() {
        let c = chars[i];
        if c == '"' || c == '\'' {
            let (quoted, consumed) = read_quoted(chars, i, c)?;
            out.push_str(&quoted);
            i += consumed;
            continue;
        }
        out.push(c);
        i += 1;
        if c == open {
            depth += 1;
        } else if c == close {
            depth -= 1;
            if depth == 0 {
                return Ok((out, i - start));
            }
        }
    }
    Err(ConvertError::QueryParse(format!(
        "unbalanced '{open}{close}' group"
    )))
}

// =============================================================================
// Boolean parser (precedence: NOT > AND > OR)
// =============================================================================

struct Parser<'a> {
    tokens: Vec<Token>,
    pos: usize,
    dialect: &'a QueryDialect,
}

fn parse_boolean(dialect: &QueryDialect, tokens: Vec<Token>) -> Result<QueryExpr<String>> {
    let mut parser = Parser {
        tokens,
        pos: 0,
        dialect,
    };
    let expr = parser.parse_or()?;
    if parser.pos != parser.tokens.len() {
        return Err(ConvertError::QueryParse(
            "unexpected trailing tokens (check parentheses)".into(),
        ));
    }
    Ok(expr)
}

impl Parser<'_> {
    fn peek(&self) -> Option<&Token> {
        self.tokens.get(self.pos)
    }

    fn starts_term(&self) -> bool {
        matches!(
            self.peek(),
            Some(Token::Atom(_)) | Some(Token::LParen) | Some(Token::Not)
        )
    }

    fn parse_or(&mut self) -> Result<QueryExpr<String>> {
        let mut nodes = vec![self.parse_and()?];
        loop {
            if matches!(self.peek(), Some(Token::Or)) {
                self.pos += 1;
                nodes.push(self.parse_and()?);
            } else if !self.dialect.implicit_and && self.starts_term() {
                nodes.push(self.parse_and()?);
            } else {
                break;
            }
        }
        Ok(collapse(QueryExpr::Or, nodes))
    }

    fn parse_and(&mut self) -> Result<QueryExpr<String>> {
        let mut nodes = vec![self.parse_not()?];
        loop {
            if matches!(self.peek(), Some(Token::And)) {
                self.pos += 1;
                nodes.push(self.parse_not()?);
            } else if self.dialect.implicit_and && self.starts_term() {
                nodes.push(self.parse_not()?);
            } else {
                break;
            }
        }
        Ok(collapse(QueryExpr::And, nodes))
    }

    fn parse_not(&mut self) -> Result<QueryExpr<String>> {
        if matches!(self.peek(), Some(Token::Not)) {
            self.pos += 1;
            Ok(QueryExpr::Not(Box::new(self.parse_not()?)))
        } else {
            self.parse_primary()
        }
    }

    fn parse_primary(&mut self) -> Result<QueryExpr<String>> {
        match self.peek() {
            Some(Token::LParen) => {
                self.pos += 1;
                let inner = self.parse_or()?;
                match self.peek() {
                    Some(Token::RParen) => {
                        self.pos += 1;
                        Ok(inner)
                    }
                    _ => Err(ConvertError::QueryParse("missing closing ')'".into())),
                }
            }
            Some(Token::Atom(_)) => {
                let Some(Token::Atom(atom)) = self.tokens.get(self.pos).cloned() else {
                    unreachable!()
                };
                self.pos += 1;
                Ok(QueryExpr::Leaf(atom))
            }
            Some(other) => Err(ConvertError::QueryParse(format!(
                "unexpected token: {other:?}"
            ))),
            None => Err(ConvertError::QueryParse("unexpected end of query".into())),
        }
    }
}

fn collapse<L>(
    ctor: fn(Vec<QueryExpr<L>>) -> QueryExpr<L>,
    mut nodes: Vec<QueryExpr<L>>,
) -> QueryExpr<L> {
    if nodes.len() == 1 {
        nodes.pop().unwrap()
    } else {
        ctor(nodes)
    }
}

// =============================================================================
// Assembly: boolean tree of leaves -> IrRule
// =============================================================================

/// Turn a resolved boolean tree into an [`IrRule`] with named selections and a
/// condition. Positive field leaves that share an AND are merged into one
/// selection; same-field OR leaves collapse into a value list; negated branches
/// become `filter` selections.
pub fn assemble_rule(expr: QueryExpr<QueryLeaf>, ctx: &ReverseCtx) -> Result<IrRule> {
    let mut asm = Assembler::default();
    let condition = asm.build(expr, "selection");
    Ok(IrRule {
        metadata: ctx.metadata(),
        logsource: ctx.logsource(),
        sigma_version: None,
        detections: asm.detections,
        conditions: vec![condition],
    })
}

#[derive(Default)]
struct Assembler {
    detections: HashMap<String, IrDetection>,
    counters: HashMap<&'static str, usize>,
}

impl Assembler {
    fn name(&mut self, prefix: &'static str) -> String {
        let counter = self.counters.entry(prefix).or_insert(0);
        let name = if *counter == 0 {
            prefix.to_string()
        } else {
            format!("{prefix}_{counter}")
        };
        *counter += 1;
        name
    }

    fn add(&mut self, prefix: &'static str, detection: IrDetection) -> IrCondition {
        let name = self.name(prefix);
        self.detections.insert(name.clone(), detection);
        IrCondition::Detection(name)
    }

    fn build(&mut self, expr: QueryExpr<QueryLeaf>, prefix: &'static str) -> IrCondition {
        match expr {
            QueryExpr::Leaf(QueryLeaf::Field { field, matcher }) => {
                self.add(prefix, IrDetection::AllOf(vec![field_item(field, matcher)]))
            }
            QueryExpr::Leaf(QueryLeaf::Keyword(matcher)) => {
                self.add("keywords", IrDetection::Keywords(matcher))
            }
            QueryExpr::And(children) => self.build_and(children, prefix),
            QueryExpr::Or(children) => self.build_or(children, prefix),
            QueryExpr::Not(inner) => IrCondition::Not(Box::new(self.build(*inner, "filter"))),
        }
    }

    fn build_and(
        &mut self,
        children: Vec<QueryExpr<QueryLeaf>>,
        prefix: &'static str,
    ) -> IrCondition {
        let mut field_items = Vec::new();
        let mut others = Vec::new();
        for child in children {
            match child {
                QueryExpr::Leaf(QueryLeaf::Field { field, matcher }) => {
                    field_items.push(field_item(field, matcher));
                }
                other => others.push(other),
            }
        }

        let mut conditions = Vec::new();
        if !field_items.is_empty() {
            conditions.push(self.add(prefix, IrDetection::AllOf(field_items)));
        }
        for other in others {
            conditions.push(self.build(other, prefix));
        }
        collapse_cond(IrCondition::And, conditions)
    }

    fn build_or(
        &mut self,
        children: Vec<QueryExpr<QueryLeaf>>,
        prefix: &'static str,
    ) -> IrCondition {
        if let Some(item) = same_field_value_list(&children) {
            return self.add(prefix, IrDetection::AllOf(vec![item]));
        }
        let conditions = children
            .into_iter()
            .map(|c| self.build(c, prefix))
            .collect();
        collapse_cond(IrCondition::Or, conditions)
    }
}

fn field_item(field: String, matcher: IrMatcher) -> IrDetectionItem {
    let exists = match &matcher {
        IrMatcher::Exists(b) => Some(*b),
        _ => None,
    };
    IrDetectionItem {
        field: Some(field),
        matcher,
        exists,
    }
}

fn collapse_cond(
    ctor: fn(Vec<IrCondition>) -> IrCondition,
    mut nodes: Vec<IrCondition>,
) -> IrCondition {
    match nodes.len() {
        0 => IrCondition::And(Vec::new()),
        1 => nodes.pop().unwrap(),
        _ => ctor(nodes),
    }
}

/// If every OR child is a field leaf on the same field with the same string
/// operator and case sensitivity, collapse them into one value-list item.
fn same_field_value_list(children: &[QueryExpr<QueryLeaf>]) -> Option<IrDetectionItem> {
    let mut field_name: Option<&str> = None;
    let mut op_ci: Option<(IrStrOp, bool)> = None;
    let mut matchers = Vec::with_capacity(children.len());

    for child in children {
        let QueryExpr::Leaf(QueryLeaf::Field { field, matcher }) = child else {
            return None;
        };
        let IrMatcher::Str {
            op,
            case_insensitive,
            ..
        } = matcher
        else {
            return None;
        };
        match field_name {
            None => field_name = Some(field),
            Some(prev) if prev == field => {}
            Some(_) => return None,
        }
        match op_ci {
            None => op_ci = Some((*op, *case_insensitive)),
            Some(prev) if prev == (*op, *case_insensitive) => {}
            Some(_) => return None,
        }
        matchers.push(matcher.clone());
    }

    let field = field_name?.to_string();
    Some(IrDetectionItem {
        field: Some(field),
        matcher: IrMatcher::AnyOf(matchers),
        exists: None,
    })
}

// =============================================================================
// Shared leaf helpers (used by frontends)
// =============================================================================

/// Build an [`IrPattern`] from a raw value, interpreting `*`/`?` as wildcards
/// and `\` as an escape (matching Sigma value semantics).
pub fn parse_pattern(raw: &str) -> IrPattern {
    let sigma = SigmaString::new(raw);
    IrPattern {
        parts: sigma
            .parts
            .iter()
            .map(|p| match p {
                StringPart::Plain(t) => IrPatternPart::Literal(t.clone()),
                StringPart::Special(rsigma_parser::SpecialChar::WildcardMulti) => {
                    IrPatternPart::WildcardMulti
                }
                StringPart::Special(rsigma_parser::SpecialChar::WildcardSingle) => {
                    IrPatternPart::WildcardSingle
                }
            })
            .collect(),
    }
}

/// Infer an idiomatic string matcher from a raw value: surrounding `*`
/// wildcards select `contains`/`startswith`/`endswith`; anything else stays an
/// exact match (with inner wildcards preserved inline).
pub fn infer_str_matcher(raw: &str, case_insensitive: bool) -> IrMatcher {
    let pattern = parse_pattern(raw);
    let parts = &pattern.parts;
    let lead = matches!(parts.first(), Some(IrPatternPart::WildcardMulti));
    let trail = parts.len() > 1 && matches!(parts.last(), Some(IrPatternPart::WildcardMulti));

    let inner = &parts[lead as usize..parts.len() - trail as usize];
    let inner_has_wildcard = inner.iter().any(|p| {
        matches!(
            p,
            IrPatternPart::WildcardMulti | IrPatternPart::WildcardSingle
        )
    });

    if !inner.is_empty() && !inner_has_wildcard {
        let pattern = IrPattern {
            parts: inner.to_vec(),
        };
        let op = match (lead, trail) {
            (true, true) => Some(IrStrOp::Contains),
            (false, true) => Some(IrStrOp::StartsWith),
            (true, false) => Some(IrStrOp::EndsWith),
            (false, false) => None,
        };
        if let Some(op) = op {
            return IrMatcher::Str {
                op,
                pattern,
                case_insensitive,
            };
        }
    }

    IrMatcher::Str {
        op: IrStrOp::Exact,
        pattern,
        case_insensitive,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn ctx() -> ReverseCtx {
        ReverseCtx {
            title: Some("T".into()),
            product: Some("windows".into()),
            ..Default::default()
        }
    }

    fn yaml(query: &str) -> String {
        let frontend = LuceneFrontend;
        convert_one(&frontend, query, &ctx())
            .expect("converts")
            .yaml
    }

    #[test]
    fn infers_string_operators_from_wildcards() {
        assert!(matches!(
            infer_str_matcher("*foo*", true),
            IrMatcher::Str {
                op: IrStrOp::Contains,
                ..
            }
        ));
        assert!(matches!(
            infer_str_matcher("foo*", true),
            IrMatcher::Str {
                op: IrStrOp::StartsWith,
                ..
            }
        ));
        assert!(matches!(
            infer_str_matcher("*foo", true),
            IrMatcher::Str {
                op: IrStrOp::EndsWith,
                ..
            }
        ));
        assert!(matches!(
            infer_str_matcher("foo", true),
            IrMatcher::Str {
                op: IrStrOp::Exact,
                ..
            }
        ));
    }

    #[test]
    fn and_of_fields_merges_into_one_selection() {
        let out = yaml("Image:*\\\\cmd.exe AND CommandLine:*whoami*");
        assert!(out.contains("selection:"), "{out}");
        assert!(out.contains("Image|endswith:"), "{out}");
        assert!(out.contains("CommandLine|contains:"), "{out}");
        assert!(out.contains("condition: selection"), "{out}");
    }

    #[test]
    fn not_becomes_filter_selection() {
        let out = yaml("EventID:1 AND NOT User:SYSTEM");
        assert!(out.contains("filter:"), "{out}");
        assert!(out.contains("condition: selection and not filter"), "{out}");
    }

    #[test]
    fn same_field_or_collapses_to_value_list() {
        let out = yaml("Image:*\\\\a.exe OR Image:*\\\\b.exe");
        assert!(out.contains("Image|endswith:"), "{out}");
        // A value list, not two selections.
        assert!(
            out.contains("- '\\a.exe'") || out.contains("- '\\\\a.exe'"),
            "{out}"
        );
        assert!(out.contains("condition: selection"), "{out}");
    }
}