Skip to main content

rsigma_eval/matcher/
matching.rs

1use regex::RegexSet;
2use rsigma_ir::IrStrOp;
3
4use super::helpers::{
5    NumericOp, ascii_lowercase_cow, expand_template, extract_timestamp_part, match_cidr,
6    match_numeric_value, match_str_value,
7};
8use super::{CompiledMatcher, GroupMode};
9use crate::event::{Event, EventValue};
10
11/// Reduce a [`RegexSet`] match against `s` according to `mode`.
12///
13/// `Any` short-circuits via [`RegexSet::is_match`]; `All` requires every
14/// pattern in the set to fire, so we materialize the matched-pattern bitset
15/// and check its population against the set length.
16#[inline]
17fn regex_set_matches(set: &RegexSet, mode: GroupMode, s: &str) -> bool {
18    match mode {
19        GroupMode::Any => set.is_match(s),
20        GroupMode::All => {
21            let hits = set.matches(s);
22            hits.iter().count() == set.len()
23        }
24    }
25}
26
27/// Compare two runtime strings with `op`.
28fn runtime_str_match(op: IrStrOp, haystack: &str, needle: &str, case_insensitive: bool) -> bool {
29    if case_insensitive {
30        let haystack = haystack.to_lowercase();
31        let needle = needle.to_lowercase();
32        runtime_str_cmp(op, &haystack, &needle)
33    } else {
34        runtime_str_cmp(op, haystack, needle)
35    }
36}
37
38fn runtime_str_cmp(op: IrStrOp, haystack: &str, needle: &str) -> bool {
39    match op {
40        IrStrOp::Contains => haystack.contains(needle),
41        IrStrOp::StartsWith => haystack.starts_with(needle),
42        IrStrOp::EndsWith => haystack.ends_with(needle),
43        IrStrOp::Exact => haystack == needle,
44    }
45}
46
47impl CompiledMatcher {
48    /// Whether this matcher holds for a field that is absent from the event.
49    ///
50    /// Only `null` matches an absent field; negation inverts that, so a
51    /// negated item such as `|neq` matches when the field is missing.
52    pub fn matches_absent(&self) -> bool {
53        match self {
54            CompiledMatcher::Null => true,
55            CompiledMatcher::Exists(expect) => !expect,
56            CompiledMatcher::Not(inner) => !inner.matches_absent(),
57            CompiledMatcher::AnyOf(matchers) => matchers.iter().any(Self::matches_absent),
58            CompiledMatcher::AllOf(matchers) => matchers.iter().all(Self::matches_absent),
59            _ => false,
60        }
61    }
62
63    /// Check if this matcher matches an [`EventValue`] from an event.
64    ///
65    /// The `event` parameter is needed for `FieldRef` to access other fields.
66    #[inline]
67    pub fn matches(&self, value: &EventValue, event: &impl Event) -> bool {
68        match self {
69            // -- String matchers --
70            CompiledMatcher::Exact {
71                value: expected,
72                case_insensitive,
73            } => match_str_value(value, |s| {
74                if *case_insensitive {
75                    s.to_lowercase() == *expected
76                } else {
77                    s == expected
78                }
79            }),
80
81            CompiledMatcher::Contains {
82                value: needle,
83                case_insensitive,
84            } => match_str_value(value, |s| {
85                if *case_insensitive {
86                    s.to_lowercase().contains(needle.as_str())
87                } else {
88                    s.contains(needle.as_str())
89                }
90            }),
91
92            CompiledMatcher::StartsWith {
93                value: prefix,
94                case_insensitive,
95            } => match_str_value(value, |s| {
96                if *case_insensitive {
97                    s.to_lowercase().starts_with(prefix.as_str())
98                } else {
99                    s.starts_with(prefix.as_str())
100                }
101            }),
102
103            CompiledMatcher::EndsWith {
104                value: suffix,
105                case_insensitive,
106            } => match_str_value(value, |s| {
107                if *case_insensitive {
108                    s.to_lowercase().ends_with(suffix.as_str())
109                } else {
110                    s.ends_with(suffix.as_str())
111                }
112            }),
113
114            CompiledMatcher::Regex(re) => match_str_value(value, |s| re.is_match(s)),
115
116            CompiledMatcher::AhoCorasickSet {
117                automaton,
118                case_insensitive,
119                ..
120            } => match_str_value(value, |s| {
121                if *case_insensitive {
122                    automaton.is_match(ascii_lowercase_cow(s).as_ref())
123                } else {
124                    automaton.is_match(s)
125                }
126            }),
127
128            CompiledMatcher::RegexSetMatch { set, mode } => {
129                match_str_value(value, |s| regex_set_matches(set, *mode, s))
130            }
131
132            // -- Network --
133            CompiledMatcher::Cidr(net) => match_cidr(value, net),
134
135            // -- Numeric --
136            CompiledMatcher::NumericEq(n) => match_numeric_value(value, NumericOp::Eq, *n),
137            CompiledMatcher::NumericGt(n) => match_numeric_value(value, NumericOp::Gt, *n),
138            CompiledMatcher::NumericGte(n) => match_numeric_value(value, NumericOp::Gte, *n),
139            CompiledMatcher::NumericLt(n) => match_numeric_value(value, NumericOp::Lt, *n),
140            CompiledMatcher::NumericLte(n) => match_numeric_value(value, NumericOp::Lte, *n),
141
142            // -- Special --
143            // A value is present even when it is null.
144            CompiledMatcher::Exists(expect) => *expect,
145
146            CompiledMatcher::FieldRef {
147                field: ref_field,
148                op,
149                case_insensitive,
150            } => {
151                let Some(ref_value) = event.get_field(ref_field) else {
152                    return false;
153                };
154                match op {
155                    IrStrOp::Exact => {
156                        if *case_insensitive {
157                            match (value.as_str(), ref_value.as_str()) {
158                                (Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(),
159                                _ => value == &ref_value,
160                            }
161                        } else {
162                            value == &ref_value
163                        }
164                    }
165                    IrStrOp::Contains | IrStrOp::StartsWith | IrStrOp::EndsWith => {
166                        let Some(needle) = ref_value.as_str() else {
167                            return false;
168                        };
169                        match_str_value(value, |s| {
170                            runtime_str_match(*op, s, needle.as_ref(), *case_insensitive)
171                        })
172                    }
173                }
174            }
175
176            CompiledMatcher::Null => value.is_null(),
177
178            CompiledMatcher::BoolEq(expected) => match value {
179                EventValue::Bool(b) => b == expected,
180                EventValue::Str(s) => match s.to_lowercase().as_str() {
181                    "true" | "1" | "yes" => *expected,
182                    "false" | "0" | "no" => !*expected,
183                    _ => false,
184                },
185                EventValue::Int(1) => *expected,
186                EventValue::Int(0) => !*expected,
187                EventValue::Float(f) if *f == 1.0 => *expected,
188                EventValue::Float(f) if *f == 0.0 => !*expected,
189                EventValue::Array(arr) => arr.iter().any(|v| self.matches(v, event)),
190                _ => false,
191            },
192
193            // -- Expand --
194            CompiledMatcher::Expand {
195                template,
196                op,
197                case_insensitive,
198            } => {
199                let expanded = expand_template(template, event);
200                match_str_value(value, |s| {
201                    runtime_str_match(*op, s, &expanded, *case_insensitive)
202                })
203            }
204
205            // -- Timestamp --
206            CompiledMatcher::TimestampPart { part, inner } => {
207                if let EventValue::Array(arr) = value {
208                    return arr.iter().any(|v| self.matches(v, event));
209                }
210                match extract_timestamp_part(value, *part) {
211                    Some(n) => {
212                        let num_val = EventValue::Int(n);
213                        inner.matches(&num_val, event)
214                    }
215                    None => false,
216                }
217            }
218
219            // -- Negation --
220            CompiledMatcher::Not(inner) => !inner.matches(value, event),
221
222            // -- Composite --
223            CompiledMatcher::AnyOf(matchers) => matchers.iter().any(|m| m.matches(value, event)),
224            CompiledMatcher::AllOf(matchers) => matchers.iter().all(|m| m.matches(value, event)),
225
226            CompiledMatcher::CaseInsensitiveGroup { children, mode } => {
227                match_str_value(value, |s| {
228                    let lowered = ascii_lowercase_cow(s);
229                    match mode {
230                        GroupMode::Any => children
231                            .iter()
232                            .any(|c| c.matches_pre_lowered(lowered.as_ref())),
233                        GroupMode::All => children
234                            .iter()
235                            .all(|c| c.matches_pre_lowered(lowered.as_ref())),
236                    }
237                })
238            }
239        }
240    }
241
242    /// Match a haystack that has already been Unicode-lowercased.
243    ///
244    /// **Precondition**: `lowered_str` was produced by `ascii_lowercase_cow`
245    /// (or an equivalent full-Unicode lowercaser) AND every child of the
246    /// surrounding [`CompiledMatcher::CaseInsensitiveGroup`] is pre-lowerable
247    /// (see `compiler::optimizer::is_pre_lowerable`).
248    ///
249    /// This method is internal to the crate. Optimizer bugs that violate the
250    /// precondition trip a `debug_assert!`; in release the conservative
251    /// fallback (`false`) avoids producing a false positive but may miss a
252    /// match.
253    ///
254    /// No `event` parameter: pre-lowerable matchers are pure string predicates
255    /// that never reference cross-event state. If a future event-aware matcher
256    /// becomes pre-lowerable, the signature gains `event` then.
257    pub(crate) fn matches_pre_lowered(&self, lowered_str: &str) -> bool {
258        match self {
259            CompiledMatcher::Contains {
260                value,
261                case_insensitive: true,
262            } => lowered_str.contains(value.as_str()),
263            CompiledMatcher::StartsWith {
264                value,
265                case_insensitive: true,
266            } => lowered_str.starts_with(value.as_str()),
267            CompiledMatcher::EndsWith {
268                value,
269                case_insensitive: true,
270            } => lowered_str.ends_with(value.as_str()),
271            CompiledMatcher::Exact {
272                value,
273                case_insensitive: true,
274            } => lowered_str == value,
275            CompiledMatcher::Regex(re) => re.is_match(lowered_str),
276            CompiledMatcher::AhoCorasickSet {
277                automaton,
278                case_insensitive: true,
279                ..
280            } => automaton.is_match(lowered_str),
281            CompiledMatcher::RegexSetMatch { set, mode } => {
282                regex_set_matches(set, *mode, lowered_str)
283            }
284
285            CompiledMatcher::Not(inner) => !inner.matches_pre_lowered(lowered_str),
286            CompiledMatcher::AnyOf(ms) => ms.iter().any(|m| m.matches_pre_lowered(lowered_str)),
287            CompiledMatcher::AllOf(ms) => ms.iter().all(|m| m.matches_pre_lowered(lowered_str)),
288            CompiledMatcher::CaseInsensitiveGroup { children, mode } => match mode {
289                GroupMode::Any => children.iter().any(|c| c.matches_pre_lowered(lowered_str)),
290                GroupMode::All => children.iter().all(|c| c.matches_pre_lowered(lowered_str)),
291            },
292
293            other => {
294                debug_assert!(
295                    false,
296                    "matches_pre_lowered called with non-pre-lowerable matcher: {other:?}"
297                );
298                false
299            }
300        }
301    }
302
303    /// Check if this matcher matches a plain `&str` value.
304    ///
305    /// Handles the string-matching subset of `CompiledMatcher`. Matchers that
306    /// require a full `EventValue` (numeric comparisons, field refs, etc.)
307    /// return `false` — those are never used in keyword detection.
308    pub(crate) fn matches_str(&self, s: &str) -> bool {
309        match self {
310            CompiledMatcher::Exact {
311                value: expected,
312                case_insensitive,
313            } => {
314                if *case_insensitive {
315                    s.to_lowercase() == *expected
316                } else {
317                    s == expected
318                }
319            }
320            CompiledMatcher::Contains {
321                value: needle,
322                case_insensitive,
323            } => {
324                if *case_insensitive {
325                    s.to_lowercase().contains(needle.as_str())
326                } else {
327                    s.contains(needle.as_str())
328                }
329            }
330            CompiledMatcher::StartsWith {
331                value: prefix,
332                case_insensitive,
333            } => {
334                if *case_insensitive {
335                    s.to_lowercase().starts_with(prefix.as_str())
336                } else {
337                    s.starts_with(prefix.as_str())
338                }
339            }
340            CompiledMatcher::EndsWith {
341                value: suffix,
342                case_insensitive,
343            } => {
344                if *case_insensitive {
345                    s.to_lowercase().ends_with(suffix.as_str())
346                } else {
347                    s.ends_with(suffix.as_str())
348                }
349            }
350            CompiledMatcher::Regex(re) => re.is_match(s),
351            CompiledMatcher::AhoCorasickSet {
352                automaton,
353                case_insensitive,
354                ..
355            } => {
356                if *case_insensitive {
357                    automaton.is_match(ascii_lowercase_cow(s).as_ref())
358                } else {
359                    automaton.is_match(s)
360                }
361            }
362            CompiledMatcher::RegexSetMatch { set, mode } => regex_set_matches(set, *mode, s),
363            CompiledMatcher::Not(inner) => !inner.matches_str(s),
364            CompiledMatcher::AnyOf(matchers) => matchers.iter().any(|m| m.matches_str(s)),
365            CompiledMatcher::AllOf(matchers) => matchers.iter().all(|m| m.matches_str(s)),
366            CompiledMatcher::CaseInsensitiveGroup { children, mode } => {
367                let lowered = ascii_lowercase_cow(s);
368                match mode {
369                    GroupMode::Any => children
370                        .iter()
371                        .any(|c| c.matches_pre_lowered(lowered.as_ref())),
372                    GroupMode::All => children
373                        .iter()
374                        .all(|c| c.matches_pre_lowered(lowered.as_ref())),
375                }
376            }
377            _ => false,
378        }
379    }
380}
381
382#[cfg(test)]
383mod tests {
384    use super::*;
385    use crate::event::JsonEvent;
386    use crate::matcher::helpers::parse_expand_template;
387    use crate::matcher::{ExpandPart, TimePart};
388    use ipnet::IpNet;
389    use regex::Regex;
390    use serde_json::json;
391
392    fn empty_event() -> serde_json::Value {
393        json!({})
394    }
395
396    #[test]
397    fn test_exact_case_insensitive() {
398        let m = CompiledMatcher::Exact {
399            value: "whoami".into(),
400            case_insensitive: true,
401        };
402        let e = empty_event();
403        let event = JsonEvent::borrow(&e);
404        assert!(m.matches(&EventValue::Str("whoami".into()), &event));
405        assert!(m.matches(&EventValue::Str("WHOAMI".into()), &event));
406        assert!(m.matches(&EventValue::Str("Whoami".into()), &event));
407        assert!(!m.matches(&EventValue::Str("other".into()), &event));
408    }
409
410    #[test]
411    fn test_exact_case_sensitive() {
412        let m = CompiledMatcher::Exact {
413            value: "whoami".into(),
414            case_insensitive: false,
415        };
416        let e = empty_event();
417        let event = JsonEvent::borrow(&e);
418        assert!(m.matches(&EventValue::Str("whoami".into()), &event));
419        assert!(!m.matches(&EventValue::Str("WHOAMI".into()), &event));
420    }
421
422    #[test]
423    fn test_contains() {
424        let m = CompiledMatcher::Contains {
425            value: "admin".to_lowercase(),
426            case_insensitive: true,
427        };
428        let e = empty_event();
429        let event = JsonEvent::borrow(&e);
430        assert!(m.matches(&EventValue::Str("superadminuser".into()), &event));
431        assert!(m.matches(&EventValue::Str("ADMIN".into()), &event));
432        assert!(!m.matches(&EventValue::Str("user".into()), &event));
433    }
434
435    #[test]
436    fn test_starts_with() {
437        let m = CompiledMatcher::StartsWith {
438            value: "cmd".into(),
439            case_insensitive: true,
440        };
441        let e = empty_event();
442        let event = JsonEvent::borrow(&e);
443        assert!(m.matches(&EventValue::Str("cmd.exe".into()), &event));
444        assert!(m.matches(&EventValue::Str("CMD.EXE".into()), &event));
445        assert!(!m.matches(&EventValue::Str("xcmd".into()), &event));
446    }
447
448    #[test]
449    fn test_ends_with() {
450        let m = CompiledMatcher::EndsWith {
451            value: ".exe".into(),
452            case_insensitive: true,
453        };
454        let e = empty_event();
455        let event = JsonEvent::borrow(&e);
456        assert!(m.matches(&EventValue::Str("cmd.exe".into()), &event));
457        assert!(m.matches(&EventValue::Str("CMD.EXE".into()), &event));
458        assert!(!m.matches(&EventValue::Str("cmd.bat".into()), &event));
459    }
460
461    #[test]
462    fn test_regex() {
463        let re = Regex::new("(?i)^test.*value$").unwrap();
464        let m = CompiledMatcher::Regex(re);
465        let e = empty_event();
466        let event = JsonEvent::borrow(&e);
467        assert!(m.matches(&EventValue::Str("testXYZvalue".into()), &event));
468        assert!(m.matches(&EventValue::Str("TESTvalue".into()), &event));
469        assert!(!m.matches(&EventValue::Str("notamatch".into()), &event));
470    }
471
472    #[test]
473    fn test_cidr() {
474        let net: IpNet = "10.0.0.0/8".parse().unwrap();
475        let m = CompiledMatcher::Cidr(net);
476        let e = empty_event();
477        let event = JsonEvent::borrow(&e);
478        assert!(m.matches(&EventValue::Str("10.1.2.3".into()), &event));
479        assert!(!m.matches(&EventValue::Str("192.168.1.1".into()), &event));
480    }
481
482    #[test]
483    fn test_numeric() {
484        let m = CompiledMatcher::NumericGte(100.into());
485        let e = empty_event();
486        let event = JsonEvent::borrow(&e);
487        assert!(m.matches(&EventValue::Int(100), &event));
488        assert!(m.matches(&EventValue::Int(200), &event));
489        assert!(!m.matches(&EventValue::Int(50), &event));
490        assert!(m.matches(&EventValue::Str("150".into()), &event));
491    }
492
493    #[test]
494    fn test_null() {
495        let m = CompiledMatcher::Null;
496        let e = empty_event();
497        let event = JsonEvent::borrow(&e);
498        assert!(m.matches(&EventValue::Null, &event));
499        assert!(!m.matches(&EventValue::Str("".into()), &event));
500    }
501
502    #[test]
503    fn test_bool() {
504        let m = CompiledMatcher::BoolEq(true);
505        let e = empty_event();
506        let event = JsonEvent::borrow(&e);
507        assert!(m.matches(&EventValue::Bool(true), &event));
508        assert!(!m.matches(&EventValue::Bool(false), &event));
509        assert!(m.matches(&EventValue::Str("true".into()), &event));
510    }
511
512    #[test]
513    fn test_bool_accepts_numeric_one_and_zero() {
514        let e = empty_event();
515        let event = JsonEvent::borrow(&e);
516        let is_true = CompiledMatcher::BoolEq(true);
517        let is_false = CompiledMatcher::BoolEq(false);
518
519        for (value, truthy) in [
520            (EventValue::Int(1), true),
521            (EventValue::Float(1.0), true),
522            (EventValue::Str("1".into()), true),
523            (EventValue::Int(0), false),
524            (EventValue::Float(0.0), false),
525            (EventValue::Float(-0.0), false),
526            (EventValue::Str("0".into()), false),
527        ] {
528            assert_eq!(is_true.matches(&value, &event), truthy, "{value:?}");
529            assert_eq!(is_false.matches(&value, &event), !truthy, "{value:?}");
530        }
531
532        for value in [
533            EventValue::Int(2),
534            EventValue::Int(-1),
535            EventValue::Float(0.5),
536            EventValue::Float(f64::NAN),
537        ] {
538            assert!(!is_true.matches(&value, &event), "{value:?}");
539            assert!(!is_false.matches(&value, &event), "{value:?}");
540        }
541
542        let arr = EventValue::Array(vec![EventValue::Int(7), EventValue::Int(1)]);
543        assert!(is_true.matches(&arr, &event));
544    }
545
546    #[test]
547    fn test_field_ref() {
548        let e = json!({"src": "10.0.0.1", "dst": "10.0.0.1"});
549        let event = JsonEvent::borrow(&e);
550        let m = CompiledMatcher::FieldRef {
551            field: "dst".into(),
552            op: IrStrOp::Exact,
553            case_insensitive: true,
554        };
555        assert!(m.matches(&EventValue::Str("10.0.0.1".into()), &event));
556    }
557
558    #[test]
559    fn test_field_ref_contains() {
560        let e = json!({"user": "Alice", "arn": "arn:aws:iam::123:user/alice"});
561        let event = JsonEvent::borrow(&e);
562        let m = CompiledMatcher::FieldRef {
563            field: "user".into(),
564            op: IrStrOp::Contains,
565            case_insensitive: true,
566        };
567        assert!(m.matches(
568            &EventValue::Str("arn:aws:iam::123:user/alice".into()),
569            &event
570        ));
571        let cased = CompiledMatcher::FieldRef {
572            field: "user".into(),
573            op: IrStrOp::Contains,
574            case_insensitive: false,
575        };
576        assert!(!cased.matches(
577            &EventValue::Str("arn:aws:iam::123:user/alice".into()),
578            &event
579        ));
580        let missing_type = CompiledMatcher::FieldRef {
581            field: "missing".into(),
582            op: IrStrOp::StartsWith,
583            case_insensitive: true,
584        };
585        assert!(!missing_type.matches(&EventValue::Str("alice".into()), &event));
586    }
587
588    #[test]
589    fn test_any_of() {
590        let m = CompiledMatcher::AnyOf(vec![
591            CompiledMatcher::Exact {
592                value: "a".into(),
593                case_insensitive: false,
594            },
595            CompiledMatcher::Exact {
596                value: "b".into(),
597                case_insensitive: false,
598            },
599        ]);
600        let e = empty_event();
601        let event = JsonEvent::borrow(&e);
602        assert!(m.matches(&EventValue::Str("a".into()), &event));
603        assert!(m.matches(&EventValue::Str("b".into()), &event));
604        assert!(!m.matches(&EventValue::Str("c".into()), &event));
605    }
606
607    #[test]
608    fn test_all_of() {
609        let m = CompiledMatcher::AllOf(vec![
610            CompiledMatcher::Contains {
611                value: "admin".into(),
612                case_insensitive: false,
613            },
614            CompiledMatcher::Contains {
615                value: "user".into(),
616                case_insensitive: false,
617            },
618        ]);
619        let e = empty_event();
620        let event = JsonEvent::borrow(&e);
621        assert!(m.matches(&EventValue::Str("adminuser".into()), &event));
622        assert!(!m.matches(&EventValue::Str("admin".into()), &event));
623    }
624
625    #[test]
626    fn test_array_value_matching() {
627        let m = CompiledMatcher::Exact {
628            value: "target".into(),
629            case_insensitive: true,
630        };
631        let e = empty_event();
632        let event = JsonEvent::borrow(&e);
633        let arr = EventValue::Array(vec![
634            EventValue::Str("other".into()),
635            EventValue::Str("target".into()),
636            EventValue::Str("more".into()),
637        ]);
638        assert!(m.matches(&arr, &event));
639        let arr2 = EventValue::Array(vec![
640            EventValue::Str("other".into()),
641            EventValue::Str("nope".into()),
642        ]);
643        assert!(!m.matches(&arr2, &event));
644    }
645
646    #[test]
647    fn test_number_coercion_to_string() {
648        let m = CompiledMatcher::Exact {
649            value: "42".into(),
650            case_insensitive: false,
651        };
652        let e = empty_event();
653        let event = JsonEvent::borrow(&e);
654        assert!(m.matches(&EventValue::Int(42), &event));
655    }
656
657    // =========================================================================
658    // Unicode case folding tests
659    // =========================================================================
660
661    #[test]
662    fn test_exact_unicode_case_insensitive() {
663        let m = CompiledMatcher::Exact {
664            value: "ärzte".to_lowercase(),
665            case_insensitive: true,
666        };
667        let e = empty_event();
668        let event = JsonEvent::borrow(&e);
669        assert!(m.matches(&EventValue::Str("ÄRZTE".into()), &event));
670        assert!(m.matches(&EventValue::Str("Ärzte".into()), &event));
671        assert!(m.matches(&EventValue::Str("ärzte".into()), &event));
672    }
673
674    #[test]
675    fn test_contains_unicode_case_insensitive() {
676        let m = CompiledMatcher::Contains {
677            value: "ñ".to_lowercase(),
678            case_insensitive: true,
679        };
680        let e = empty_event();
681        let event = JsonEvent::borrow(&e);
682        assert!(m.matches(&EventValue::Str("España".into()), &event));
683        assert!(m.matches(&EventValue::Str("ESPAÑA".into()), &event));
684    }
685
686    #[test]
687    fn test_startswith_unicode_case_insensitive() {
688        let m = CompiledMatcher::StartsWith {
689            value: "über".to_lowercase(),
690            case_insensitive: true,
691        };
692        let e = empty_event();
693        let event = JsonEvent::borrow(&e);
694        assert!(m.matches(&EventValue::Str("Übersicht".into()), &event));
695        assert!(m.matches(&EventValue::Str("ÜBERSICHT".into()), &event));
696        assert!(!m.matches(&EventValue::Str("not-uber".into()), &event));
697    }
698
699    #[test]
700    fn test_endswith_unicode_case_insensitive() {
701        let m = CompiledMatcher::EndsWith {
702            value: "ção".to_lowercase(),
703            case_insensitive: true,
704        };
705        let e = empty_event();
706        let event = JsonEvent::borrow(&e);
707        assert!(m.matches(&EventValue::Str("Aplicação".into()), &event));
708        assert!(m.matches(&EventValue::Str("APLICAÇÃO".into()), &event));
709        assert!(!m.matches(&EventValue::Str("Aplicacao".into()), &event));
710    }
711
712    #[test]
713    fn test_greek_case_insensitive() {
714        let m = CompiledMatcher::Exact {
715            value: "σίγμα".to_lowercase(),
716            case_insensitive: true,
717        };
718        let e = empty_event();
719        let event = JsonEvent::borrow(&e);
720        assert!(m.matches(&EventValue::Str("ΣΊΓΜΑ".into()), &event));
721        assert!(m.matches(&EventValue::Str("σίγμα".into()), &event));
722    }
723
724    // =========================================================================
725    // Expand modifier tests
726    // =========================================================================
727
728    #[test]
729    fn test_parse_expand_template() {
730        let parts = parse_expand_template("C:\\Users\\\\%user%\\AppData");
731        assert_eq!(parts.len(), 3);
732        assert!(matches!(&parts[0], ExpandPart::Literal(s) if s == "C:\\Users\\"));
733        assert!(matches!(&parts[1], ExpandPart::Placeholder(s) if s == "user"));
734        assert!(matches!(&parts[2], ExpandPart::Literal(s) if s == "\\AppData"));
735    }
736
737    #[test]
738    fn test_parse_expand_template_no_placeholders() {
739        let parts = parse_expand_template("just a literal");
740        assert_eq!(parts.len(), 1);
741        assert!(matches!(&parts[0], ExpandPart::Literal(s) if s == "just a literal"));
742    }
743
744    #[test]
745    fn test_parse_expand_template_escaped_percent() {
746        let parts = parse_expand_template("100\\%: %a%\\%b%");
747        assert_eq!(parts.len(), 3);
748        assert!(matches!(&parts[0], ExpandPart::Literal(s) if s == "100%: "));
749        assert!(matches!(&parts[1], ExpandPart::Placeholder(s) if s == "a"));
750        assert!(matches!(&parts[2], ExpandPart::Literal(s) if s == "%b%"));
751
752        let parts = parse_expand_template("\\%plain%name%");
753        assert_eq!(parts.len(), 2);
754        assert!(matches!(&parts[0], ExpandPart::Literal(s) if s == "%plain"));
755        assert!(matches!(&parts[1], ExpandPart::Placeholder(s) if s == "name"));
756
757        let parts = parse_expand_template("%%x%");
758        assert_eq!(parts.len(), 2);
759        assert!(matches!(&parts[0], ExpandPart::Literal(s) if s == "%"));
760        assert!(matches!(&parts[1], ExpandPart::Placeholder(s) if s == "x"));
761    }
762
763    #[test]
764    fn test_parse_expand_template_multiple_placeholders() {
765        let parts = parse_expand_template("%a%:%b%");
766        assert_eq!(parts.len(), 3);
767        assert!(matches!(&parts[0], ExpandPart::Placeholder(s) if s == "a"));
768        assert!(matches!(&parts[1], ExpandPart::Literal(s) if s == ":"));
769        assert!(matches!(&parts[2], ExpandPart::Placeholder(s) if s == "b"));
770    }
771
772    #[test]
773    fn test_expand_matcher() {
774        let template = parse_expand_template("C:\\Users\\\\%user%\\Downloads");
775        let m = CompiledMatcher::Expand {
776            template,
777            op: IrStrOp::Exact,
778            case_insensitive: true,
779        };
780        let e = json!({"user": "admin", "path": "C:\\Users\\admin\\Downloads"});
781        let event = JsonEvent::borrow(&e);
782        assert!(m.matches(
783            &EventValue::Str("C:\\Users\\admin\\Downloads".into()),
784            &event
785        ));
786        assert!(!m.matches(
787            &EventValue::Str("C:\\Users\\other\\Downloads".into()),
788            &event
789        ));
790    }
791
792    #[test]
793    fn test_expand_matcher_missing_field() {
794        let template = parse_expand_template("%user%@%domain%");
795        let m = CompiledMatcher::Expand {
796            template,
797            op: IrStrOp::Exact,
798            case_insensitive: false,
799        };
800        let e = json!({"user": "admin"});
801        let event = JsonEvent::borrow(&e);
802        assert!(m.matches(&EventValue::Str("admin@".into()), &event));
803    }
804
805    // =========================================================================
806    // Timestamp part tests
807    // =========================================================================
808
809    #[test]
810    fn test_timestamp_part_hour() {
811        let m = CompiledMatcher::TimestampPart {
812            part: TimePart::Hour,
813            inner: Box::new(CompiledMatcher::NumericEq(12.into())),
814        };
815        let e = json!({});
816        let event = JsonEvent::borrow(&e);
817        assert!(m.matches(&EventValue::Str("2024-07-10T12:30:00Z".into()), &event));
818        assert!(!m.matches(&EventValue::Str("2024-07-10T15:30:00Z".into()), &event));
819    }
820
821    #[test]
822    fn test_timestamp_part_month() {
823        let m = CompiledMatcher::TimestampPart {
824            part: TimePart::Month,
825            inner: Box::new(CompiledMatcher::NumericEq(7.into())),
826        };
827        let e = json!({});
828        let event = JsonEvent::borrow(&e);
829        assert!(m.matches(&EventValue::Str("2024-07-10T12:30:00Z".into()), &event));
830        assert!(!m.matches(&EventValue::Str("2024-08-10T12:30:00Z".into()), &event));
831    }
832
833    #[test]
834    fn test_timestamp_part_day() {
835        let m = CompiledMatcher::TimestampPart {
836            part: TimePart::Day,
837            inner: Box::new(CompiledMatcher::NumericEq(10.into())),
838        };
839        let e = json!({});
840        let event = JsonEvent::borrow(&e);
841        assert!(m.matches(&EventValue::Str("2024-07-10T12:30:00Z".into()), &event));
842        assert!(!m.matches(&EventValue::Str("2024-07-15T12:30:00Z".into()), &event));
843    }
844
845    #[test]
846    fn test_timestamp_part_year() {
847        let m = CompiledMatcher::TimestampPart {
848            part: TimePart::Year,
849            inner: Box::new(CompiledMatcher::NumericEq(2024.into())),
850        };
851        let e = json!({});
852        let event = JsonEvent::borrow(&e);
853        assert!(m.matches(&EventValue::Str("2024-07-10T12:30:00Z".into()), &event));
854        assert!(!m.matches(&EventValue::Str("2023-07-10T12:30:00Z".into()), &event));
855    }
856
857    #[test]
858    fn test_timestamp_part_from_epoch() {
859        let m = CompiledMatcher::TimestampPart {
860            part: TimePart::Hour,
861            inner: Box::new(CompiledMatcher::NumericEq(12.into())),
862        };
863        let e = json!({});
864        let event = JsonEvent::borrow(&e);
865        // 2024-07-10T12:30:00Z = 1720614600
866        assert!(m.matches(&EventValue::Int(1720614600), &event));
867    }
868}