Skip to main content

rsigma_parser/
condition.rs

1//! Condition expression parser using pest PEG grammar + Pratt parser.
2//!
3//! Parses Sigma condition strings like:
4//! - `"selection and not filter"`
5//! - `"1 of selection_* and not 1 of filter_*"`
6//! - `"all of them"`
7//! - `"selection_main and 1 of selection_dword_* and not 1 of filter_optional_*"`
8//!
9//! Reference: pySigma conditions.py (uses pyparsing infix_notation)
10
11use std::num::NonZeroU64;
12
13use pest::Parser;
14use pest::iterators::Pair;
15use pest::pratt_parser::{Assoc, Op, PrattParser};
16use pest_derive::Parser;
17
18use crate::ast::{ConditionExpr, Quantifier, SelectorPattern};
19use crate::error::{Result, SigmaParserError, SourceLocation};
20
21// ---------------------------------------------------------------------------
22// Pest parser (generated from sigma.pest grammar)
23// ---------------------------------------------------------------------------
24
25#[derive(Parser)]
26#[grammar = "src/sigma.pest"]
27struct SigmaConditionParser;
28
29// ---------------------------------------------------------------------------
30// Public API
31// ---------------------------------------------------------------------------
32
33const MAX_CONDITION_LEN: usize = 64 * 1024;
34const MAX_CONDITION_DEPTH: usize = 64;
35
36/// pest fails with "stack limit reached" when fewer than 64 KiB of stack
37/// remain, and musl reports only the already-touched part of the main
38/// thread's stack, so the reported headroom can be far below the real one.
39const CONDITION_STACK_RED_ZONE: usize = 256 * 1024;
40const CONDITION_STACK_SIZE: usize = 2 * 1024 * 1024;
41
42/// Parse a Sigma condition expression string into an AST.
43///
44/// # Examples
45///
46/// ```
47/// use rsigma_parser::condition::parse_condition;
48///
49/// let expr = parse_condition("selection and not filter").unwrap();
50/// println!("{expr}");
51/// ```
52pub fn parse_condition(input: &str) -> Result<ConditionExpr> {
53    if input.len() > MAX_CONDITION_LEN {
54        return Err(SigmaParserError::ConditionTooLong(
55            input.len(),
56            MAX_CONDITION_LEN,
57        ));
58    }
59
60    match stacker::remaining_stack() {
61        Some(remaining) if remaining < CONDITION_STACK_RED_ZONE => {
62            stacker::grow(CONDITION_STACK_SIZE, || parse_condition_inner(input))
63        }
64        _ => parse_condition_inner(input),
65    }
66}
67
68fn parse_condition_inner(input: &str) -> Result<ConditionExpr> {
69    let pairs = SigmaConditionParser::parse(Rule::condition, input).map_err(|e| {
70        let loc = extract_pest_location(&e);
71        SigmaParserError::Condition(e.to_string(), loc)
72    })?;
73
74    let pratt = PrattParser::new()
75        .op(Op::infix(Rule::or_op, Assoc::Left))
76        .op(Op::infix(Rule::and_op, Assoc::Left))
77        .op(Op::prefix(Rule::not_op));
78
79    // condition = { SOI ~ expr ~ EOI }
80    let condition_pair = pairs
81        .into_iter()
82        .next()
83        .ok_or_else(|| SigmaParserError::Condition("empty condition expression".into(), None))?;
84    let expr_pair = condition_pair
85        .into_inner()
86        .find(|p| p.as_rule() == Rule::expr)
87        .ok_or_else(|| SigmaParserError::Condition("missing expr in condition".into(), None))?;
88
89    let depth = std::cell::Cell::new(0usize);
90    parse_expr(expr_pair, &pratt, &depth)
91}
92
93fn extract_pest_location(err: &pest::error::Error<Rule>) -> Option<SourceLocation> {
94    match err.line_col {
95        pest::error::LineColLocation::Pos((line, col)) => Some(SourceLocation {
96            line: line as u32,
97            col: col as u32,
98        }),
99        pest::error::LineColLocation::Span((line, col), _) => Some(SourceLocation {
100            line: line as u32,
101            col: col as u32,
102        }),
103    }
104}
105
106// ---------------------------------------------------------------------------
107// Internal parsing helpers
108// ---------------------------------------------------------------------------
109
110/// An error collected during Pratt parsing, with optional position context.
111struct PrattError {
112    message: String,
113    location: Option<SourceLocation>,
114}
115
116impl PrattError {
117    /// Keeps only the bare message of a condition error, so the location is
118    /// rendered once by the outer error instead of being nested in the text.
119    fn from_error(err: SigmaParserError, fallback: Option<SourceLocation>) -> Self {
120        let location = err.location().or(fallback);
121        let message = match err {
122            SigmaParserError::Condition(message, _) => message,
123            other => other.to_string(),
124        };
125        PrattError { message, location }
126    }
127}
128
129fn location_from_pair(pair: &Pair<'_, Rule>) -> Option<SourceLocation> {
130    let (line, col) = pair.as_span().start_pos().line_col();
131    Some(SourceLocation {
132        line: line as u32,
133        col: col as u32,
134    })
135}
136
137fn parse_expr(
138    pair: Pair<'_, Rule>,
139    pratt: &PrattParser<Rule>,
140    depth: &std::cell::Cell<usize>,
141) -> Result<ConditionExpr> {
142    let current = depth.get();
143    if current > MAX_CONDITION_DEPTH {
144        return Err(SigmaParserError::Condition(
145            format!("condition nesting exceeds maximum depth ({MAX_CONDITION_DEPTH})"),
146            None,
147        ));
148    }
149    depth.set(current + 1);
150
151    // The Pratt parser closures cannot return Result, so we collect all
152    // errors in a shared RefCell and report them after parsing completes.
153    let errors: std::cell::RefCell<Vec<PrattError>> = std::cell::RefCell::new(Vec::new());
154
155    let result = pratt
156        .map_primary(|primary| {
157            let loc = location_from_pair(&primary);
158            match primary.as_rule() {
159                Rule::ident => ConditionExpr::Identifier(primary.as_str().to_string()),
160                Rule::selector => parse_selector(primary).unwrap_or_else(|e| {
161                    errors.borrow_mut().push(PrattError::from_error(e, loc));
162                    ConditionExpr::Identifier(String::new())
163                }),
164                Rule::expr => parse_expr(primary, pratt, depth).unwrap_or_else(|e| {
165                    errors.borrow_mut().push(PrattError::from_error(e, loc));
166                    ConditionExpr::Identifier(String::new())
167                }),
168                other => {
169                    errors.borrow_mut().push(PrattError {
170                        message: format!("unexpected primary rule: {other:?}"),
171                        location: loc,
172                    });
173                    ConditionExpr::Identifier(String::new())
174                }
175            }
176        })
177        .map_prefix(|op, rhs| {
178            let loc = location_from_pair(&op);
179            match op.as_rule() {
180                Rule::not_op => ConditionExpr::Not(Box::new(rhs)),
181                other => {
182                    errors.borrow_mut().push(PrattError {
183                        message: format!("unexpected prefix rule: {other:?}"),
184                        location: loc,
185                    });
186                    rhs
187                }
188            }
189        })
190        .map_infix(|lhs, op, rhs| {
191            let loc = location_from_pair(&op);
192            match op.as_rule() {
193                Rule::and_op => merge_binary(ConditionExpr::And, lhs, rhs),
194                Rule::or_op => merge_binary(ConditionExpr::Or, lhs, rhs),
195                other => {
196                    errors.borrow_mut().push(PrattError {
197                        message: format!("unexpected infix rule: {other:?}"),
198                        location: loc,
199                    });
200                    lhs
201                }
202            }
203        })
204        .parse(pair.into_inner());
205
206    depth.set(depth.get().saturating_sub(1));
207
208    let mut collected = errors.into_inner();
209    if collected.len() == 1 {
210        let PrattError { message, location } = collected.remove(0);
211        return Err(SigmaParserError::Condition(message, location));
212    }
213    if !collected.is_empty() {
214        let combined = collected
215            .iter()
216            .map(|e| match &e.location {
217                Some(loc) => format!("at {loc}: {}", e.message),
218                None => e.message.clone(),
219            })
220            .collect::<Vec<_>>()
221            .join("; ");
222        let first_loc = collected.iter().find_map(|e| e.location);
223        return Err(SigmaParserError::Condition(combined, first_loc));
224    }
225
226    Ok(result)
227}
228
229/// Flatten nested binary operators of the same kind.
230/// `a AND (b AND c)` → `AND(a, b, c)` instead of `AND(a, AND(b, c))`.
231fn merge_binary(
232    ctor: fn(Vec<ConditionExpr>) -> ConditionExpr,
233    lhs: ConditionExpr,
234    rhs: ConditionExpr,
235) -> ConditionExpr {
236    // Flatten same-type children to avoid unnecessary nesting: And(And(a, b), c) → And(a, b, c)
237    let is_and = matches!(ctor(vec![]), ConditionExpr::And(_));
238
239    let mut args = Vec::new();
240    for expr in [lhs, rhs] {
241        match expr {
242            ConditionExpr::And(children) if is_and => args.extend(children),
243            ConditionExpr::Or(children) if !is_and => args.extend(children),
244            other => args.push(other),
245        }
246    }
247
248    ctor(args)
249}
250
251fn parse_selector(pair: Pair<'_, Rule>) -> Result<ConditionExpr> {
252    // Iterate children, skipping the of_kw_inner pair (atomic rules can't be silent
253    // in pest, so of_kw_inner leaks into the parse tree)
254    let mut quantifier_pair = None;
255    let mut target_pair = None;
256
257    for p in pair.into_inner() {
258        match p.as_rule() {
259            Rule::quantifier => quantifier_pair = Some(p),
260            Rule::selector_target => target_pair = Some(p),
261            _ => {} // skip of_kw_inner
262        }
263    }
264
265    let quantifier =
266        parse_quantifier(quantifier_pair.ok_or_else(|| {
267            SigmaParserError::Condition("selector missing quantifier".into(), None)
268        })?)?;
269    let pattern = parse_selector_target(
270        target_pair
271            .ok_or_else(|| SigmaParserError::Condition("selector missing target".into(), None))?,
272    )?;
273
274    Ok(ConditionExpr::Selector {
275        quantifier,
276        pattern,
277    })
278}
279
280fn parse_quantifier(pair: Pair<'_, Rule>) -> Result<Quantifier> {
281    let inner = pair
282        .into_inner()
283        .next()
284        .ok_or_else(|| SigmaParserError::Condition("quantifier missing child".into(), None))?;
285    match inner.as_rule() {
286        Rule::all_kw => Ok(Quantifier::All),
287        Rule::any_kw => Ok(Quantifier::Any),
288        Rule::uint => {
289            let n: u64 = inner.as_str().parse().map_err(|e| {
290                SigmaParserError::Condition(format!("invalid quantifier number: {e}"), None)
291            })?;
292            match NonZeroU64::new(n) {
293                None => {
294                    let (line, col) = inner.as_span().start_pos().line_col();
295                    Err(SigmaParserError::Condition(
296                        "'0 of' is always true and matches every event; use 'not 1 of' to \
297                         require that none of the detections match"
298                            .into(),
299                        Some(SourceLocation {
300                            line: line as u32,
301                            col: col as u32,
302                        }),
303                    ))
304                }
305                Some(n) if n.get() == 1 => Ok(Quantifier::Any),
306                Some(n) => Ok(Quantifier::Count(n)),
307            }
308        }
309        other => Err(SigmaParserError::Condition(
310            format!("unexpected quantifier rule: {other:?}"),
311            None,
312        )),
313    }
314}
315
316fn parse_selector_target(pair: Pair<'_, Rule>) -> Result<SelectorPattern> {
317    let inner = pair
318        .into_inner()
319        .next()
320        .ok_or_else(|| SigmaParserError::Condition("selector target missing child".into(), None))?;
321    match inner.as_rule() {
322        Rule::them_kw => Ok(SelectorPattern::Them),
323        Rule::ident_pattern => Ok(SelectorPattern::Pattern(inner.as_str().to_string())),
324        other => Err(SigmaParserError::Condition(
325            format!("unexpected selector target rule: {other:?}"),
326            None,
327        )),
328    }
329}
330
331// =============================================================================
332// Tests
333// =============================================================================
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338
339    #[test]
340    fn test_simple_identifier() {
341        let expr = parse_condition("selection").unwrap();
342        assert_eq!(expr, ConditionExpr::Identifier("selection".to_string()));
343    }
344
345    #[test]
346    fn test_and() {
347        let expr = parse_condition("selection and filter").unwrap();
348        assert_eq!(
349            expr,
350            ConditionExpr::And(vec![
351                ConditionExpr::Identifier("selection".to_string()),
352                ConditionExpr::Identifier("filter".to_string()),
353            ])
354        );
355    }
356
357    #[test]
358    fn test_or() {
359        let expr = parse_condition("selection1 or selection2").unwrap();
360        assert_eq!(
361            expr,
362            ConditionExpr::Or(vec![
363                ConditionExpr::Identifier("selection1".to_string()),
364                ConditionExpr::Identifier("selection2".to_string()),
365            ])
366        );
367    }
368
369    #[test]
370    fn test_not() {
371        let expr = parse_condition("not filter").unwrap();
372        assert_eq!(
373            expr,
374            ConditionExpr::Not(Box::new(ConditionExpr::Identifier("filter".to_string())))
375        );
376    }
377
378    #[test]
379    fn test_and_not() {
380        let expr = parse_condition("selection and not filter").unwrap();
381        assert_eq!(
382            expr,
383            ConditionExpr::And(vec![
384                ConditionExpr::Identifier("selection".to_string()),
385                ConditionExpr::Not(Box::new(ConditionExpr::Identifier("filter".to_string()))),
386            ])
387        );
388    }
389
390    #[test]
391    fn test_precedence_not_and_or() {
392        // "a or not b and c" should parse as "a or ((not b) and c)"
393        let expr = parse_condition("a or not b and c").unwrap();
394        assert_eq!(
395            expr,
396            ConditionExpr::Or(vec![
397                ConditionExpr::Identifier("a".to_string()),
398                ConditionExpr::And(vec![
399                    ConditionExpr::Not(Box::new(ConditionExpr::Identifier("b".to_string()))),
400                    ConditionExpr::Identifier("c".to_string()),
401                ]),
402            ])
403        );
404    }
405
406    #[test]
407    fn test_parentheses() {
408        let expr = parse_condition("(a or b) and c").unwrap();
409        assert_eq!(
410            expr,
411            ConditionExpr::And(vec![
412                ConditionExpr::Or(vec![
413                    ConditionExpr::Identifier("a".to_string()),
414                    ConditionExpr::Identifier("b".to_string()),
415                ]),
416                ConditionExpr::Identifier("c".to_string()),
417            ])
418        );
419    }
420
421    #[test]
422    fn test_selector_1_of_pattern() {
423        let expr = parse_condition("1 of selection_*").unwrap();
424        assert_eq!(
425            expr,
426            ConditionExpr::Selector {
427                quantifier: Quantifier::Any,
428                pattern: SelectorPattern::Pattern("selection_*".to_string()),
429            }
430        );
431    }
432
433    #[test]
434    fn test_selector_all_of_them() {
435        let expr = parse_condition("all of them").unwrap();
436        assert_eq!(
437            expr,
438            ConditionExpr::Selector {
439                quantifier: Quantifier::All,
440                pattern: SelectorPattern::Them,
441            }
442        );
443    }
444
445    #[test]
446    fn test_selector_any_of() {
447        let expr = parse_condition("any of selection*").unwrap();
448        assert_eq!(
449            expr,
450            ConditionExpr::Selector {
451                quantifier: Quantifier::Any,
452                pattern: SelectorPattern::Pattern("selection*".to_string()),
453            }
454        );
455    }
456
457    #[test]
458    fn test_complex_condition() {
459        // Real-world: selection_main and 1 of selection_dword_* and not 1 of filter_optional_*
460        let expr = parse_condition(
461            "selection_main and 1 of selection_dword_* and not 1 of filter_optional_*",
462        )
463        .unwrap();
464        assert_eq!(
465            expr,
466            ConditionExpr::And(vec![
467                ConditionExpr::Identifier("selection_main".to_string()),
468                ConditionExpr::Selector {
469                    quantifier: Quantifier::Any,
470                    pattern: SelectorPattern::Pattern("selection_dword_*".to_string()),
471                },
472                ConditionExpr::Not(Box::new(ConditionExpr::Selector {
473                    quantifier: Quantifier::Any,
474                    pattern: SelectorPattern::Pattern("filter_optional_*".to_string()),
475                })),
476            ])
477        );
478    }
479
480    #[test]
481    fn test_identifier_with_keyword_substring() {
482        // "and_filter" should be parsed as an identifier, not "and" + "filter"
483        let expr = parse_condition("selection_and_filter").unwrap();
484        assert_eq!(
485            expr,
486            ConditionExpr::Identifier("selection_and_filter".to_string())
487        );
488    }
489
490    #[test]
491    fn test_identifier_with_hyphen() {
492        let expr = parse_condition("my-selection and my-filter").unwrap();
493        assert_eq!(
494            expr,
495            ConditionExpr::And(vec![
496                ConditionExpr::Identifier("my-selection".to_string()),
497                ConditionExpr::Identifier("my-filter".to_string()),
498            ])
499        );
500    }
501
502    #[test]
503    fn test_triple_and_flattened() {
504        let expr = parse_condition("a and b and c").unwrap();
505        assert_eq!(
506            expr,
507            ConditionExpr::And(vec![
508                ConditionExpr::Identifier("a".to_string()),
509                ConditionExpr::Identifier("b".to_string()),
510                ConditionExpr::Identifier("c".to_string()),
511            ])
512        );
513    }
514
515    #[test]
516    fn test_triple_or_flattened() {
517        let expr = parse_condition("a or b or c").unwrap();
518        assert_eq!(
519            expr,
520            ConditionExpr::Or(vec![
521                ConditionExpr::Identifier("a".to_string()),
522                ConditionExpr::Identifier("b".to_string()),
523                ConditionExpr::Identifier("c".to_string()),
524            ])
525        );
526    }
527
528    #[test]
529    fn test_all_of_selection_and_not_filter() {
530        let expr =
531            parse_condition("all of selection_powershell_* or all of selection_wmic_*").unwrap();
532        assert_eq!(
533            expr,
534            ConditionExpr::Or(vec![
535                ConditionExpr::Selector {
536                    quantifier: Quantifier::All,
537                    pattern: SelectorPattern::Pattern("selection_powershell_*".to_string()),
538                },
539                ConditionExpr::Selector {
540                    quantifier: Quantifier::All,
541                    pattern: SelectorPattern::Pattern("selection_wmic_*".to_string()),
542                },
543            ])
544        );
545    }
546
547    #[test]
548    fn test_real_world_complex() {
549        // From rules: selection_key and (all of selection_powershell_* or all of selection_wmic_*)
550        let expr = parse_condition(
551            "selection_key and (all of selection_powershell_* or all of selection_wmic_*)",
552        )
553        .unwrap();
554        assert_eq!(
555            expr,
556            ConditionExpr::And(vec![
557                ConditionExpr::Identifier("selection_key".to_string()),
558                ConditionExpr::Or(vec![
559                    ConditionExpr::Selector {
560                        quantifier: Quantifier::All,
561                        pattern: SelectorPattern::Pattern("selection_powershell_*".to_string()),
562                    },
563                    ConditionExpr::Selector {
564                        quantifier: Quantifier::All,
565                        pattern: SelectorPattern::Pattern("selection_wmic_*".to_string()),
566                    },
567                ]),
568            ])
569        );
570    }
571
572    #[test]
573    fn test_1_of_them() {
574        let expr = parse_condition("1 of them").unwrap();
575        assert_eq!(
576            expr,
577            ConditionExpr::Selector {
578                quantifier: Quantifier::Any,
579                pattern: SelectorPattern::Them,
580            }
581        );
582    }
583
584    #[test]
585    fn test_nested_error_reported_once() {
586        let input = format!("{}a{}", "(".repeat(70), ")".repeat(70));
587        let message = parse_condition(&input).unwrap_err().to_string();
588        assert_eq!(
589            message.matches("Condition parse error").count(),
590            1,
591            "{message}"
592        );
593        assert_eq!(message.matches("maximum depth").count(), 1, "{message}");
594    }
595
596    #[test]
597    fn test_count_of() {
598        let expr = parse_condition("3 of selection_*").unwrap();
599        assert_eq!(
600            expr,
601            ConditionExpr::Selector {
602                quantifier: Quantifier::Count(NonZeroU64::new(3).unwrap()),
603                pattern: SelectorPattern::Pattern("selection_*".to_string()),
604            }
605        );
606    }
607
608    #[test]
609    fn test_zero_of_rejected() {
610        for input in [
611            "0 of selection_*",
612            "00 of them",
613            "selection and not 0 of filter_*",
614        ] {
615            let err = parse_condition(input).unwrap_err();
616            let SigmaParserError::Condition(message, location) = &err else {
617                panic!("expected a condition error for {input:?}, got {err:?}");
618            };
619            assert!(message.starts_with("'0 of' is always true"), "{message}");
620            let col = input.find('0').unwrap() as u32 + 1;
621            assert_eq!(*location, Some(SourceLocation { line: 1, col }), "{input}");
622        }
623    }
624
625    #[test]
626    fn test_zero_count_not_deserializable() {
627        assert!(serde_json::from_str::<Quantifier>(r#"{"Count":0}"#).is_err());
628        assert_eq!(
629            serde_json::from_str::<Quantifier>(r#"{"Count":2}"#).unwrap(),
630            Quantifier::Count(NonZeroU64::new(2).unwrap())
631        );
632    }
633
634    #[test]
635    fn test_not_1_of_filter() {
636        let expr = parse_condition("selection and not 1 of filter*").unwrap();
637        assert_eq!(
638            expr,
639            ConditionExpr::And(vec![
640                ConditionExpr::Identifier("selection".to_string()),
641                ConditionExpr::Not(Box::new(ConditionExpr::Selector {
642                    quantifier: Quantifier::Any,
643                    pattern: SelectorPattern::Pattern("filter*".to_string()),
644                })),
645            ])
646        );
647    }
648
649    // ── Multi-wildcard selector pattern tests ──────────────────────────────
650
651    #[test]
652    fn test_selector_multi_wildcard_pattern() {
653        let expr = parse_condition("1 of selection_*_*").unwrap();
654        assert_eq!(
655            expr,
656            ConditionExpr::Selector {
657                quantifier: Quantifier::Any,
658                pattern: SelectorPattern::Pattern("selection_*_*".to_string()),
659            }
660        );
661    }
662
663    #[test]
664    fn test_selector_leading_wildcard_pattern() {
665        let expr = parse_condition("all of *_selection_*").unwrap();
666        assert_eq!(
667            expr,
668            ConditionExpr::Selector {
669                quantifier: Quantifier::All,
670                pattern: SelectorPattern::Pattern("*_selection_*".to_string()),
671            }
672        );
673    }
674
675    #[test]
676    fn test_selector_bare_wildcard() {
677        let expr = parse_condition("1 of *").unwrap();
678        assert_eq!(
679            expr,
680            ConditionExpr::Selector {
681                quantifier: Quantifier::Any,
682                pattern: SelectorPattern::Pattern("*".to_string()),
683            }
684        );
685    }
686
687    #[test]
688    fn test_selector_triple_wildcard_segment() {
689        let expr = parse_condition("any of sel_*_*_*").unwrap();
690        assert_eq!(
691            expr,
692            ConditionExpr::Selector {
693                quantifier: Quantifier::Any,
694                pattern: SelectorPattern::Pattern("sel_*_*_*".to_string()),
695            }
696        );
697    }
698
699    #[test]
700    fn test_multi_wildcard_in_complex_condition() {
701        let expr =
702            parse_condition("selection_main and 1 of sel_*_* and not 1 of filter_*_*").unwrap();
703        assert_eq!(
704            expr,
705            ConditionExpr::And(vec![
706                ConditionExpr::Identifier("selection_main".to_string()),
707                ConditionExpr::Selector {
708                    quantifier: Quantifier::Any,
709                    pattern: SelectorPattern::Pattern("sel_*_*".to_string()),
710                },
711                ConditionExpr::Not(Box::new(ConditionExpr::Selector {
712                    quantifier: Quantifier::Any,
713                    pattern: SelectorPattern::Pattern("filter_*_*".to_string()),
714                })),
715            ])
716        );
717    }
718
719    #[test]
720    fn test_selector_wildcard_only_prefix() {
721        let expr = parse_condition("all of *suffix").unwrap();
722        assert_eq!(
723            expr,
724            ConditionExpr::Selector {
725                quantifier: Quantifier::All,
726                pattern: SelectorPattern::Pattern("*suffix".to_string()),
727            }
728        );
729    }
730
731    // ── Malformed condition expression tests ─────────────────────────────
732
733    #[test]
734    fn test_empty_string_fails() {
735        let err = parse_condition("").unwrap_err();
736        assert!(matches!(err, SigmaParserError::Condition(_, _)));
737    }
738
739    #[test]
740    fn test_whitespace_only_fails() {
741        let err = parse_condition("   ").unwrap_err();
742        assert!(matches!(err, SigmaParserError::Condition(_, _)));
743    }
744
745    #[test]
746    fn test_trailing_operator_fails() {
747        let err = parse_condition("selection and").unwrap_err();
748        assert!(matches!(err, SigmaParserError::Condition(_, _)));
749    }
750
751    #[test]
752    fn test_leading_operator_fails() {
753        let err = parse_condition("and selection").unwrap_err();
754        assert!(matches!(err, SigmaParserError::Condition(_, _)));
755    }
756
757    #[test]
758    fn test_double_operator_fails() {
759        let err = parse_condition("selection and and filter").unwrap_err();
760        assert!(matches!(err, SigmaParserError::Condition(_, _)));
761    }
762
763    #[test]
764    fn test_unbalanced_open_paren_fails() {
765        let err = parse_condition("(selection and filter").unwrap_err();
766        assert!(matches!(err, SigmaParserError::Condition(_, _)));
767    }
768
769    #[test]
770    fn test_unbalanced_close_paren_fails() {
771        let err = parse_condition("selection and filter)").unwrap_err();
772        assert!(matches!(err, SigmaParserError::Condition(_, _)));
773    }
774
775    #[test]
776    fn test_empty_parens_fails() {
777        let err = parse_condition("()").unwrap_err();
778        assert!(matches!(err, SigmaParserError::Condition(_, _)));
779    }
780
781    #[test]
782    fn test_only_operator_fails() {
783        let err = parse_condition("and").unwrap_err();
784        assert!(matches!(err, SigmaParserError::Condition(_, _)));
785    }
786
787    #[test]
788    fn test_only_not_fails() {
789        let err = parse_condition("not").unwrap_err();
790        assert!(matches!(err, SigmaParserError::Condition(_, _)));
791    }
792
793    #[test]
794    fn test_or_alone_fails() {
795        let err = parse_condition("or").unwrap_err();
796        assert!(matches!(err, SigmaParserError::Condition(_, _)));
797    }
798
799    #[test]
800    fn test_incomplete_selector_missing_target_fails() {
801        let err = parse_condition("1 of").unwrap_err();
802        assert!(matches!(err, SigmaParserError::Condition(_, _)));
803    }
804
805    #[test]
806    fn test_of_without_quantifier_fails() {
807        let err = parse_condition("of selection_*").unwrap_err();
808        assert!(matches!(err, SigmaParserError::Condition(_, _)));
809    }
810
811    #[test]
812    fn test_pest_error_carries_location() {
813        let err = parse_condition("selection and").unwrap_err();
814        match &err {
815            SigmaParserError::Condition(_, loc) => {
816                assert!(
817                    loc.is_some(),
818                    "pest parse errors should carry source location"
819                );
820            }
821            _ => panic!("Expected Condition error"),
822        }
823    }
824
825    #[test]
826    fn test_invalid_characters_fails() {
827        let err = parse_condition("selection @ filter").unwrap_err();
828        assert!(matches!(err, SigmaParserError::Condition(_, _)));
829    }
830
831    #[test]
832    fn test_nested_empty_parens_fails() {
833        let err = parse_condition("selection and ()").unwrap_err();
834        assert!(matches!(err, SigmaParserError::Condition(_, _)));
835    }
836
837    #[test]
838    fn condition_too_long_returns_error() {
839        let big = "a".repeat(MAX_CONDITION_LEN + 1);
840        let err = parse_condition(&big).unwrap_err();
841        assert!(
842            matches!(err, SigmaParserError::ConditionTooLong(_, _)),
843            "expected ConditionTooLong, got: {err}"
844        );
845    }
846
847    #[test]
848    fn moderate_condition_still_parses() {
849        let expr = parse_condition("((((((((((a and b))))))))))").unwrap();
850        match expr {
851            ConditionExpr::And(children) => assert_eq!(children.len(), 2),
852            other => panic!("expected And, got {other:?}"),
853        }
854    }
855
856    /// Recurses until less stack than pest's 64 KiB threshold appears to
857    /// remain, then parses, which is how the musl main thread looks to pest.
858    fn parse_with_little_stack_left(input: &str) -> Result<ConditionExpr> {
859        match stacker::remaining_stack() {
860            Some(remaining) if remaining > 48 * 1024 => {
861                let pad = std::hint::black_box([0u8; 4096]);
862                let result = parse_with_little_stack_left(input);
863                std::hint::black_box(&pad);
864                result
865            }
866            _ => parse_condition(input),
867        }
868    }
869
870    #[test]
871    fn parses_when_little_stack_appears_to_remain() {
872        let nested = format!("{}a{}", "(".repeat(60), ")".repeat(60));
873        std::thread::Builder::new()
874            .stack_size(1024 * 1024)
875            .spawn(move || {
876                assert!(parse_with_little_stack_left("selection and not filter").is_ok());
877                assert!(parse_with_little_stack_left(&nested).is_ok());
878            })
879            .unwrap()
880            .join()
881            .unwrap();
882    }
883
884    #[test]
885    fn deeply_nested_condition_fails_without_overflow() {
886        let input = format!("{}a{}", "(".repeat(30_000), ")".repeat(30_000));
887        assert!(parse_condition(&input).is_err());
888    }
889}