#![allow(
clippy::literal_string_with_formatting_args,
reason = "grok's %{NAME:field} reads as a format argument"
)]
use super::*;
use crate::parse::{Fields, Parsed, Parser};
#[cfg(feature = "parse-backtracking")]
use crate::{parse::ParseError, tier::MatcherTier};
type Written = Option<Vec<(String, String, Hint)>>;
fn written(parsed: &Parsed, out: &Fields<'_>) -> Written {
match parsed {
Parsed::NoMatch => None,
_ => Some(
out.as_slice()
.iter()
.map(|(n, v)| {
(
n.clone(),
String::from_utf8_lossy(&v.bytes).into_owned(),
v.hint,
)
})
.collect(),
),
}
}
fn parse(g: &Grok, input: &str) -> Written {
let mut out = Fields::new();
let parsed = g.parse(input.as_bytes(), &mut out).unwrap();
written(&parsed, &out)
}
fn parse_by_regex(g: &Grok, input: &str) -> Written {
let mut out = Fields::new();
let parsed = g.parse_regex(input.as_bytes(), &mut out).unwrap();
written(&parsed, &out)
}
fn grok(patterns: &[&str]) -> Grok {
patterns
.iter()
.fold(Grok::builder("grok:test"), |b, p| b.pattern(*p))
.build()
.unwrap()
}
#[allow(clippy::unnecessary_wraps, reason = "compared with what parse returns")]
fn text(fields: &[(&str, &str)]) -> Option<Vec<(String, String, Hint)>> {
Some(
fields
.iter()
.map(|(n, v)| ((*n).to_owned(), (*v).to_owned(), Hint::Text))
.collect(),
)
}
#[test]
fn a_reference_expands_to_a_numbered_group_with_its_field() {
let lib = Library::default();
let e = expand(
"%{WORD:verb} %{NUMBER:[http][bytes]:int} %{SPACE}",
&lib,
Dialect::Rust,
)
.unwrap();
assert!(e.regex.starts_with(r"(?P<g0>\b\w+\b) "), "{}", e.regex);
assert!(e.regex.contains("(?<![0-9.+-])") && !e.regex.contains("(?P<e"));
assert_eq!(e.edges, []);
assert_eq!(
e.captures,
[
Capture {
field: "verb".into(),
hint: Hint::Text,
filter: None
},
Capture {
field: "http.bytes".into(),
hint: Hint::Int,
filter: None
},
]
);
let e = expand(
"%{WORD:[a.b][c]} %{WORD:[x][y.z]} %{WORD:[q\"t]} %{WORD:d.e}",
&lib,
Dialect::Rust,
)
.unwrap();
let fields: Vec<&str> = e.captures.iter().map(|c| c.field.as_str()).collect();
assert_eq!(
fields,
[r#"["a.b"].c"#, r#"x["y.z"]"#, r#"["q\"t"]"#, "d.e"]
);
let e = expand("%{RCONTROLLER}", &lib, Dialect::Rust).unwrap();
let fields: Vec<&str> = e.captures.iter().map(|c| c.field.as_str()).collect();
assert_eq!(fields, ["controller", "action"]);
assert!(!e.regex.contains("(?<controller>"));
}
#[test]
fn a_bad_reference_says_why() {
let lib = Library::default();
assert_eq!(
expand("%{NOPE}", &lib, Dialect::Rust),
Err(GrokError::Unknown("NOPE".into()))
);
assert!(matches!(
expand("%{WORD:x:bytes}", &lib, Dialect::Rust),
Err(GrokError::Malformed(_))
));
assert!(matches!(
expand("%{WORD", &lib, Dialect::Rust),
Err(GrokError::Malformed(_))
));
let mut looped = Library::empty();
looped.add("A", "x%{B}");
looped.add("B", "%{A}");
assert_eq!(
expand("%{A}", &looped, Dialect::Rust),
Err(GrokError::Cycle("A".into()))
);
let e = expand("[%{]", &lib, Dialect::Rust).unwrap();
assert_eq!(e.regex, "[%{]");
}
#[test]
fn every_library_definition_expands_and_the_linear_engine_runs_all() {
let lib = Library::default();
let mut refused: Vec<&str> = lib
.defs
.keys()
.filter(|name| {
let e = expand_linear(&format!("%{{{name}}}"), &lib, Dialect::Rust).unwrap();
regex_automata::meta::Regex::new(&e.regex).is_err()
})
.map(String::as_str)
.collect();
refused.sort_unstable();
assert!(refused.is_empty(), "{refused:?}");
}
#[test]
fn the_earliest_match_wins_and_a_tie_goes_to_the_first_pattern() {
let g = grok(&["%{INT:late}", "x %{WORD:early}"]);
assert_eq!(parse(&g, "x a 23"), text(&[("early", "a")]));
let g = grok(&["%{WORD:a}", "%{WORD:b}"]);
assert_eq!(parse(&g, "hi"), text(&[("a", "hi")]));
assert_eq!(parse(&g, " "), None);
}
type Pairs = &'static [(&'static str, &'static str)];
fn whole(patterns: &[&str], aliases: Pairs) -> Result<Grok, GrokBuildError> {
let mut a = Library::empty();
for (name, def) in aliases {
a.add(*name, *def);
}
patterns
.iter()
.fold(Grok::builder("grok:w"), |b, p| b.pattern(*p))
.aliases(a)
.dialect(Dialect::Oniguruma)
.span(Span::Whole)
.drop_empty(true)
.build()
}
fn won(g: &Grok, input: &str) -> Option<(usize, Vec<(String, String)>)> {
let mut out = Fields::new();
let index = g.parse_indexed(input.as_bytes(), &mut out).unwrap()?;
let fields = out
.as_slice()
.iter()
.map(|(n, v)| (n.clone(), String::from_utf8_lossy(&v.bytes).into_owned()))
.collect();
Some((index, fields))
}
#[test]
fn a_whole_line_list_takes_the_first_pattern_that_matches_all_of_it() {
type Row = (
&'static [&'static str],
Pairs,
&'static str,
Option<(usize, Pairs)>,
);
let rows: [Row; 17] = [
(
&[".*?=%{INT:n}", "%{WORD:w}=.*"],
&[],
"k=5",
Some((0, &[("n", "5")])),
),
(
&["%{WORD:w}=.*", ".*?=%{INT:n}"],
&[],
"k=5",
Some((0, &[("w", "k")])),
),
(
&["%{WORD:a}", "%{WORD:a} %{WORD:b}"],
&[],
"x y",
Some((1, &[("a", "x"), ("b", "y")])),
),
(&["%{WORD:a}"], &[], "x y", None),
(
&["%{WORD:a} %{GREEDYDATA:r}"],
&[],
"x y\nz",
Some((0, &[("a", "x"), ("r", "y\nz")])),
),
(&["%{DATA:d}!"], &[], "a\nb!", Some((0, &[("d", "a\nb")]))),
(
&[".*?^%{INT:n}$.*"],
&[],
"a\n42\nb",
Some((0, &[("n", "42")])),
),
(&["%{WORD:w}$"], &[], "a\n", None),
(&["%{WORD:w}$"], &[], "a", Some((0, &[("w", "a")]))),
(
&["%{PORT:p}"],
&[("PORT", "x+")],
"xx",
Some((0, &[("p", "xx")])),
),
(
&["%{HOSTPORT:hp}"],
&[("PORT", "x+")],
"h:80",
Some((0, &[("hp", "h:80")])),
),
(&["%{HOSTPORT:hp}"], &[("PORT", "x+")], "h:xx", None),
(
&["%{HDR} %{WORD:w}"],
&[("HDR", "<%{PRI}>"), ("PRI", "%{INT:pri}")],
"<13> up",
Some((0, &[("pri", "13"), ("w", "up")])),
),
(
&["%{DATA:a}=%{DATA:b}"],
&[],
"=x",
Some((0, &[("b", "x")])),
),
(
&["%{WORD:a}(?: %{INT:n})?"],
&[],
"x",
Some((0, &[("a", "x")])),
),
(&["%{INT:n}", "%{WORD:w}"], &[], "a b", None),
(&["%{INT:n}"], &[], "", None),
];
for (patterns, aliases, input, want) in rows {
let g = whole(patterns, aliases).unwrap();
let want = want.map(|(i, f)| {
let f = f.iter().map(|(n, v)| ((*n).to_owned(), (*v).to_owned()));
(i, f.collect::<Vec<_>>())
});
assert_eq!(
won(&g, input),
want,
"{patterns:?} {aliases:?} on {input:?}"
);
}
let part = Grok::builder("grok:p")
.pattern("=%{INT:n}")
.pattern("%{WORD:w}=")
.build()
.unwrap();
assert_eq!(won(&part, "k=5"), Some((1, vec![("w".into(), "k".into())])));
let part = grok(&["%{WORD:a}", "%{WORD:a} %{WORD:b}"]);
assert_eq!(won(&part, "x y"), Some((0, vec![("a".into(), "x".into())])));
}
#[test]
fn an_alias_that_reaches_itself_or_nothing_says_why() {
let cycle = whole(&["%{A}"], &[("A", "x%{B}"), ("B", "%{A}")]);
assert!(
matches!(cycle, Err(GrokBuildError::Expand { index: 0, source: GrokError::Cycle(ref n) }) if n == "A"),
"{cycle:?}"
);
let unknown = whole(&["%{A}"], &[("A", "%{NOPE}")]);
assert!(
matches!(unknown, Err(GrokBuildError::Expand { source: GrokError::Unknown(ref n), .. }) if n == "NOPE"),
"{unknown:?}"
);
}
#[test]
fn aliases_load_from_json_and_a_later_definition_wins() {
let mut a = Library::empty();
a.add("A", "x");
a.add_json(r#"{"A": "%{B}y", "B": "z"}"#).unwrap();
a.add_json(r#"{"B": "q"}"#).unwrap();
let g = Grok::builder("grok:j")
.pattern("%{A:a}")
.aliases(a.clone())
.span(Span::Whole)
.build()
.unwrap();
assert_eq!(won(&g, "qy"), Some((0, vec![("a".into(), "qy".into())])));
assert_eq!(won(&g, "x"), None);
for bad in ["[]", r#"{"A": 1}"#, "{", ""] {
let mut b = a.clone();
assert!(matches!(b.add_json(bad), Err(GrokError::Json(_))), "{bad}");
assert_eq!(b.get("A"), Some("%{B}y"), "{bad} added nothing");
}
}
#[test]
fn an_unknown_name_expands_to_the_definition_asked_for() {
let lenient = |p: &str| {
Grok::builder("grok:u")
.pattern(p)
.dialect(Dialect::Oniguruma)
.unknown(".+?")
.build()
.unwrap()
};
let g = lenient("%{NOPE:f} x");
assert_eq!(parse(&g, "ab x"), text(&[("f", "ab")]));
assert_eq!(g.blocked(), [None]);
let mut lib = Library::default();
lib.add("PAIR", "%{MISSING}=%{INT:v}");
let g = Grok::builder("grok:u")
.pattern("^%{PAIR}$")
.library(lib)
.unknown(".+?")
.build()
.unwrap();
assert_eq!(parse(&g, "k=12"), text(&[("v", "12")]));
assert_eq!(parse(&g, "=12"), None);
assert!(matches!(
Grok::builder("grok:u").pattern("%{NOPE:f}").build(),
Err(GrokBuildError::Expand { source: GrokError::Unknown(ref n), .. }) if n == "NOPE"
));
}
#[test]
fn parse_indexed_names_the_pattern_that_won() {
let g = grok(&["%{INT:late}", "x %{WORD:early}"]);
assert_eq!(
won(&g, "x a 23"),
Some((1, vec![("early".into(), "a".into())]))
);
assert_eq!(won(&g, "23"), Some((0, vec![("late".into(), "23".into())])));
assert_eq!(won(&g, "x"), None);
let anchored = grok(&["^%{INT:n}", "^%{WORD:w}"]);
assert_eq!(
won(&anchored, "ab"),
Some((1, vec![("w".into(), "ab".into())]))
);
}
#[test]
fn empty_captures_are_dropped_on_the_default_span_too() {
let g = Grok::builder("grok:e")
.pattern("^%{WORD:a}(?: %{INT:b})?=%{DATA:c}$")
.drop_empty(true)
.build()
.unwrap();
assert_eq!(parse(&g, "hi="), text(&[("a", "hi")]));
assert_eq!(
parse(&g, "hi 3=x"),
text(&[("a", "hi"), ("b", "3"), ("c", "x")])
);
}
#[test]
fn ipv4_range_checks_octets_on_native_steps() {
let build = |p: &str, validate: bool| {
Grok::builder("grok:v")
.pattern(p)
.validate(validate)
.strict(true)
.build()
.unwrap()
};
let rows: &[(&str, &str, bool)] = &[
("^%{IPV4:x}$", "999.1.1.1", false),
("^%{IPV4:x}$", "256.0.0.1", false),
("^%{IPV4:x}$", "01.2.3.4", true),
("^%{IPV4:x}$", "001.002.003.004", true),
("^%{IPV4:x}$", "255.255.255.255", true),
("^%{IPV4:x}$", "0.0.0.0", true),
("^%{IPV4:x}$", "1.2.3.4x", false),
("^%{IPV4:x}$", "1.2.3", false),
("^%{IPV4:x}$", "10.0.0.7:443", false),
("^%{IPV4:x}$", "1.2.3.0001", false),
("^%{IP:x}$", "999.1.1.1", false),
("^%{IP:x}$", "fe80::1", true),
("^%{IP:x}$", "192.168.1.255", true),
("^%{IPORHOST:x}$", "999.1.1.1", true),
("%{IPV4:x}", "from 1.2.3.256 to 10.0.0.1", true),
];
for &(pattern, line, want) in rows {
for validate in [true, false] {
let got = parse(&build(pattern, validate), line);
assert_eq!(
got.is_some(),
want,
"{pattern} on {line:?}, validate {validate}"
);
}
}
assert_eq!(
parse(&build("%{IPV4:x}", false), "from 1.2.3.256 to 10.0.0.1"),
parse(&build("%{IPV4:x}", false), "to 10.0.0.1"),
"a bad address is skipped for the next"
);
}
fn x_of(g: &Grok, line: &str) -> Option<String> {
parse(g, line)?
.into_iter()
.find(|(name, ..)| name == "x")
.map(|(_, value, _)| value)
}
#[test]
fn wide_ipv6_zone_runs_a_zone_to_the_end_of_the_line() {
let rows: &[(&str, &str, Option<&str>, Option<&str>)] = &[
(
"^%{IPV6:x}$",
"fe80::1%eth0 up",
Some("fe80::1%eth0 up"),
None,
),
(
"^%{IPV6:x}$",
"fe80::1%eth0",
Some("fe80::1%eth0"),
Some("fe80::1%eth0"),
),
("^%{IPV6:x}!$", "fe80::1%a b!", Some("fe80::1%a b"), None),
(
"^%{IPV6:x} up$",
"fe80::1%eth0 up",
Some("fe80::1%eth0"),
Some("fe80::1%eth0"),
),
(
"%{IPV6:x}",
"ip fe80::1%eth0/1 up",
Some("fe80::1%eth0/1 up"),
Some("fe80::1%eth0"),
),
(
"%{IPV6:x}",
"fe80::1%a b\nc",
Some("fe80::1%a b"),
Some("fe80::1%a"),
),
("%{IPV6:x}", "fe80::1%", Some("fe80::1"), Some("fe80::1")),
("^%{IPV6:x}$", "::1", Some("::1"), Some("::1")),
(
"^%{IP:x}$",
"fe80::1%eth0 up",
Some("fe80::1%eth0 up"),
None,
),
("^%{IP:x}$", "10.0.0.1", Some("10.0.0.1"), Some("10.0.0.1")),
(
"^%{IPORHOST:x}$",
"fe80::1%eth0 up",
Some("fe80::1%eth0 up"),
None,
),
(
"^%{IPORHOST:x}$",
"db-1.example.com",
Some("db-1.example.com"),
Some("db-1.example.com"),
),
];
for dialect in [Dialect::Rust, Dialect::Oniguruma] {
let build = |p: &str, wide: bool| {
Grok::builder("grok:z")
.pattern(p)
.dialect(dialect)
.wide_ipv6_zone(wide)
.strict(true)
.build()
.unwrap()
};
for &(pattern, line, wide, bounded) in rows {
for (on, want) in [(true, wide), (false, bounded)] {
let got = x_of(&build(pattern, on), line);
let at = format!("{dialect:?} {pattern} on {line:?}, wide {on}");
assert_eq!(got.as_deref(), want, "{at}");
let by_regex = parse_by_regex(&build(pattern, on), line);
assert_eq!(
by_regex,
parse(&build(pattern, on), line),
"{at} by the regex"
);
}
}
}
}
#[test]
fn validate_and_wide_ipv6_zone_take_the_address_whole_with_a_wide_zone() {
let rows: &[(&str, &str, Option<&str>, Option<&str>)] = &[
(
"^%{IPV6:x}$",
"fe80::1%eth0 up",
Some("fe80::1%eth0 up"),
None,
),
(
"^%{IPV6:x} up$",
"fe80::1%eth0 up",
Some("fe80::1%eth0"),
Some("fe80::1%eth0"),
),
(
"%{IPV6:x}",
"::ffff:1.2.3.4%eth0 up",
Some("::ffff:1.2.3.4%eth0 up"),
Some("::ffff:1.2.3.4%eth0"),
),
("%{IPV6:x}", "fe80::1x%eth0", None, None),
(
"%{IPV6:x}",
"from 1::2::3 to 2001:db8::7%a b",
Some("2001:db8::7%a b"),
Some("2001:db8::7%a"),
),
("%{IPV6:x}", "fe80::1%", Some("fe80::1"), Some("fe80::1")),
(
"^%{IP:x}$",
"64:ff9b::1.2.3.4%a b",
Some("64:ff9b::1.2.3.4%a b"),
None,
),
("^%{IP:x}$", "999.1.1.1", None, None),
("^%{IP:x}$", "10.0.0.1", Some("10.0.0.1"), Some("10.0.0.1")),
(
"%{IP:x}",
"src=2001:db8::1x dst=10.0.0.1",
Some("10.0.0.1"),
Some("10.0.0.1"),
),
(
"^%{IPORHOST:x}$",
"fe80::1%eth0 up",
Some("fe80::1%eth0 up"),
None,
),
(
"^%{IPORHOST:x}$",
"999.1.1.1",
Some("999.1.1.1"),
Some("999.1.1.1"),
),
("%{IPORHOST:x}", "1::2::3", Some("1"), Some("1")),
(
"^%{IPV6:x}:%{INT:p}$",
"fe80::1%eth0:80",
Some("fe80::1%eth0"),
Some("fe80::1%eth0"),
),
(
"%{IPV6:x}",
"at 1::2%a:3 up",
Some("1::2%a:3 up"),
Some("1::2%a"),
),
];
for dialect in [Dialect::Rust, Dialect::Oniguruma] {
let build = |p: &str, wide: bool| {
Grok::builder("grok:vz")
.pattern(p)
.dialect(dialect)
.validate(true)
.wide_ipv6_zone(wide)
.strict(true)
.build()
.unwrap()
};
for &(pattern, line, both, validate) in rows {
for (wide, want) in [(true, both), (false, validate)] {
let g = build(pattern, wide);
let at = format!("{dialect:?} {pattern} on {line:?}, wide {wide}");
assert_eq!(x_of(&g, line).as_deref(), want, "{at}");
assert_eq!(
parse_by_regex(&g, line),
parse(&g, line),
"{at} by the regex"
);
}
}
}
}
#[test]
fn atomic_number_builds_where_no_digit_can_be_given_back() {
for dialect in [Dialect::Rust, Dialect::Oniguruma] {
let build = |p: &str, atomic: bool| {
Grok::builder("grok:a")
.pattern(p)
.dialect(dialect)
.atomic_number(atomic)
.strict(true)
.build()
};
for (pattern, line, want) in [
("^%{NUMBER:x} %{WORD:w}$", "12.5 up", Some("12.5")),
("^%{NUMBER:x}%{GREEDYDATA:g}", "12.5.7", Some("12.5")),
("^%{BASE10NUM:x}$", "-.5", Some("-.5")),
("^%{NUMBER:x}-3$", "12-3", Some("12")),
("%{NUMBER:x}ms", "took 15ms", Some("15")),
("^%{NUMBER:x}$", "1.", None),
] {
for atomic in [true, false] {
let g = build(pattern, atomic).unwrap();
let at = format!("{dialect:?} {pattern} on {line:?}, atomic {atomic}");
assert_eq!(x_of(&g, line).as_deref(), want, "{at}");
assert_eq!(
parse_by_regex(&g, line),
parse(&g, line),
"{at} by the regex"
);
}
}
let gives_back = "^%{NUMBER:a}%{INT:b}$";
let plain = build(gives_back, false).unwrap();
assert_eq!(parse(&plain, "12345"), text(&[("a", "1234"), ("b", "5")]));
assert!(
matches!(
build(gives_back, true),
Err(GrokBuildError::Atomic { index: 0, .. })
),
"{dialect:?}"
);
}
}
#[cfg(feature = "parse-backtracking")]
#[test]
fn an_atomic_number_that_could_give_back_runs_on_the_backtracking_engine() {
let build = |atomic: bool| {
Grok::builder("grok:a")
.atomic_number(atomic)
.backtracking_pattern("^%{NUMBER:a}%{INT:b}$")
.build()
.unwrap()
};
let atomic = build(true);
assert_eq!(atomic.tier(), MatcherTier::Backtracking);
assert_eq!(parse(&atomic, "12345"), None);
assert_eq!(parse(&atomic, "12"), None);
assert_eq!(parse(&atomic, "12-3"), text(&[("a", "12"), ("b", "-3")]));
let plain = build(false);
assert_eq!(parse(&plain, "12"), text(&[("a", "1"), ("b", "2")]));
}
#[test]
fn validate_takes_an_ipv6_address_whole_on_native_steps() {
let build = |p: &str, validate: bool| {
Grok::builder("grok:v6")
.pattern(p)
.validate(validate)
.strict(true)
.build()
.unwrap()
};
let rows: &[(&str, &str, Option<&str>, Option<&str>)] = &[
(
"%{IPV6:x}",
"from 2001:db8::1 ok",
Some("2001:db8::1"),
Some("2001:db8::1"),
),
("%{IPV6:x}", "2001:db8::1x", None, Some("2001:db8::1")),
("%{IPV6:x}", "abcd:ef01::1g", None, Some("abcd:ef01::1")),
("%{IPV6:x}", "from 12345::1", None, Some("2345::1")),
(
"%{IPV6:x}",
"::ffff:1.2.3.4",
Some("::ffff:1.2.3.4"),
Some("::ffff:1"),
),
(
"%{IPV6:x}",
"64:ff9b::1.2.3.4",
Some("64:ff9b::1.2.3.4"),
Some("64:ff9b::1"),
),
(
"%{IPV6:x}",
"fe80::1%eth0 up",
Some("fe80::1%eth0"),
Some("fe80::1%eth0"),
),
(
"^%{IPV6:x}$",
"2001:db8::1",
Some("2001:db8::1"),
Some("2001:db8::1"),
),
(
"^%{IPV6:x}$",
"::ffff:1.2.3.4",
Some("::ffff:1.2.3.4"),
Some("::ffff:1.2.3.4"),
),
("^%{IPV6:x}$", "1::2::3", None, None),
(
"^%{IP:x}$",
"64:ff9b::1.2.3.4",
Some("64:ff9b::1.2.3.4"),
Some("64:ff9b::1.2.3.4"),
),
("%{IP:x}", "src=2001:db8::1x", None, Some("2001:db8::1")),
(
"%{IP:x}",
"src=12345::1 dst=10.0.0.1",
Some("10.0.0.1"),
Some("2345::1"),
),
(
"^%{IPORHOST:x}$",
"64:ff9b::1.2.3.4",
Some("64:ff9b::1.2.3.4"),
Some("64:ff9b::1.2.3.4"),
),
("%{IPORHOST:x}:%{POSINT:p}", "[2001:db8::1]:443", None, None),
(
"\\[%{IPV6:x}\\]:%{POSINT:p}",
"[2001:db8::1]:443",
Some("2001:db8::1"),
Some("2001:db8::1"),
),
];
for &(pattern, line, on, off) in rows {
for (validate, want) in [(true, on), (false, off)] {
let got = parse(&build(pattern, validate), line)
.and_then(|fields| fields.into_iter().find(|f| f.0 == "x").map(|f| f.1));
assert_eq!(
got.as_deref(),
want,
"{pattern} on {line:?}, validate {validate}"
);
}
}
}
#[test]
fn validate_refuses_an_address_a_neighbour_would_extend() {
let build = |p: &str, validate: bool| {
Grok::builder("grok:v6g")
.pattern(p)
.validate(validate)
.strict(true)
.build()
.unwrap()
};
let rows: &[(&str, &str, Option<&str>, Option<&str>)] = &[
("%{IPV6:x}", "1::2::3", None, Some("1::2")),
(
"%{IPV6:x}",
"1:2:3:4:5:6:7:8:9",
None,
Some("1:2:3:4:5:6:7:8"),
),
(
"%{IPV6:x}",
"2001:db8::1.",
Some("2001:db8::1"),
Some("2001:db8::1"),
),
("%{IPV6:x}", "2001:db8::1.5", None, Some("2001:db8::1")),
(
"%{IPV6:x}",
"2001:db8::1: up",
Some("2001:db8::1"),
Some("2001:db8::1"),
),
(
"%{IPV6:x}",
"2001:db8::1:",
Some("2001:db8::1"),
Some("2001:db8::1"),
),
("%{IPV6:x}", "::ffff:1.2.3.4.5", None, Some("::ffff:1")),
(
"%{IPV6:x}",
"from 1::2::3 to 2001:db8::7",
Some("2001:db8::7"),
Some("1::2"),
),
(
"%{IPV6:x}",
"[2001:db8::1]:443",
Some("2001:db8::1"),
Some("2001:db8::1"),
),
("^%{IPV6:x}$", "1::2::3", None, None),
(
"%{IP:x}",
"1::2::3 10.0.0.1",
Some("10.0.0.1"),
Some("1::2"),
),
("%{IP:x}", "10.0.0.1:80", Some("10.0.0.1"), Some("10.0.0.1")),
("%{IPORHOST:x}", "1::2::3 web-01", Some("1"), Some("1::2")),
(
"^%{IPV6:x}:%{INT:p}$",
"fe80::1%eth0:80",
Some("fe80::1%eth0"),
Some("fe80::1%eth0"),
),
(
"%{IPV6:x}",
"at 1::2%a:3 up",
Some("1::2%a"),
Some("1::2%a"),
),
(
"%{IPORHOST:x}",
"web-01:443",
Some("web-01"),
Some("web-01"),
),
];
for &(pattern, line, on, off) in rows {
for (validate, want) in [(true, on), (false, off)] {
let g = build(pattern, validate);
let value = |fields: Option<Vec<(String, String, Hint)>>| {
fields.and_then(|f| f.into_iter().find(|f| f.0 == "x").map(|f| f.1))
};
let by_steps = value(parse(&g, line));
let mut out = Fields::new();
let regex_parsed = g.parse_regex(line.as_bytes(), &mut out).unwrap();
let by_regex = (regex_parsed != Parsed::NoMatch)
.then(|| {
out.as_slice()
.iter()
.find(|(n, _)| n == "x")
.map(|(_, v)| String::from_utf8_lossy(&v.bytes).into_owned())
})
.flatten();
assert_eq!(
by_steps.as_deref(),
want,
"{pattern} on {line:?}, validate {validate}"
);
assert_eq!(
by_regex.as_deref(),
want,
"{pattern} regex tier on {line:?}, validate {validate}"
);
}
}
}
#[test]
fn numbers_and_ipv4_start_and_end_where_upstream_does() {
type Row<'r> = (&'r str, &'r str, Option<&'r [(&'r str, &'r str)]>, bool);
let rows: &[Row<'_>] = &[
("%{NUMBER:n}", "+-1e3", Some(&[("n", "3")]), true),
("%{NUMBER:n}", "..42xhost.example", None, true),
("%{NUMBER:a}%{INT:b}", "1e310.0.0.1-10.0.0.10", None, false),
(
"%{IP:ip}",
"10.0.0.1host.example",
Some(&[("ip", "10.0.0.1")]),
true,
),
(
"%{IP:ip}",
"10.0.0.1fe80::110.0.0.1abc",
Some(&[("ip", "10.0.0.1")]),
true,
),
(
"%{IPV4:ip}",
"abc10.0.0.1 x",
Some(&[("ip", "10.0.0.1")]),
true,
),
("%{IPV4:ip}", "110.0.0.1234", None, true),
("%{WORD:w}-%{NUMBER:n}", "build-42 x", None, true),
(
"%{WORD:w} %{NUMBER:n}",
"build 42",
Some(&[("w", "build"), ("n", "42")]),
true,
),
(
"%{BASE10NUM:a}.%{INT:b}",
"v1.2.3",
Some(&[("a", "1.2"), ("b", "3")]),
true,
),
(
"%{INT:a}:%{NUMBER:b}",
"5:-3",
Some(&[("a", "5"), ("b", "-3")]),
true,
),
(
"%{IPORHOST:x}",
"1::2::3 web-01",
Some(&[("x", "1::2")]),
true,
),
("%{IPV4:ip}", "999.1.1.1", None, true),
(
"%{IP:ip}",
"999.1.1.1 10.0.0.1",
Some(&[("ip", "10.0.0.1")]),
true,
),
(
"%{IPORHOST:h} %{WORD:w}",
"999.1.1.1 up",
Some(&[("h", "999.1.1.1"), ("w", "up")]),
true,
),
(
"%{IPORHOST:h}:%{POSINT:p}",
"10.0.0.1:80",
Some(&[("h", "10.0.0.1"), ("p", "80")]),
true,
),
];
let builder = |upstream: bool| {
let b = Grok::builder("grok:edges").dialect(Dialect::Oniguruma);
if upstream {
b.wide_ipv6_zone(true).atomic_number(true)
} else {
b
}
};
for &(pattern, line, want, plain) in rows {
let want = want.and_then(text);
for upstream in [true, false].into_iter().filter(|&u| u || plain) {
let at = format!("{pattern} on {line:?}, options {upstream}");
match builder(upstream).pattern(pattern).build() {
Ok(g) => {
assert_eq!(parse(&g, line), want, "{at}");
assert_eq!(parse_by_regex(&g, line), want, "{at}, regex tier");
}
Err(GrokBuildError::Atomic { .. }) if upstream => {}
Err(e) => panic!("{at}: {e}"),
}
#[cfg(feature = "parse-backtracking")]
{
let g = builder(upstream)
.backtracking_pattern(format!("{pattern}(?=)"))
.build()
.unwrap();
assert_eq!(g.tier(), MatcherTier::Backtracking, "{at}");
assert_eq!(parse(&g, line), want, "{at}, backtracking");
}
}
}
}
#[test]
fn a_shadowed_record_spends_the_backtrack_budget_once() {
let g = Grok::builder("grok:shadow")
.pattern("%{WORD:w}-%{NUMBER:n}")
.shadow(std::num::NonZeroU32::MIN)
.build()
.unwrap();
for (line, want) in [("build-42 x", None), ("a.b-7", None), ("no dash", None)] {
let before = super::backtrack::SEARCHES.with(std::cell::Cell::get);
assert_eq!(parse(&g, line), want, "{line:?}");
let ran = super::backtrack::SEARCHES.with(std::cell::Cell::get) - before;
assert!(ran <= 1, "{line:?} ran {ran} fancy-regex searches");
}
let refused = super::backtrack::SEARCHES.with(std::cell::Cell::get);
parse(&g, "build-42 x");
assert_eq!(
super::backtrack::SEARCHES.with(std::cell::Cell::get) - refused,
1,
"an edge refusal runs fancy-regex once"
);
}
#[test]
fn shadowed_fallbacks_switch_to_the_regex_first_past_twice_its_time() {
let build = |p: &str| {
Grok::builder("grok:shadow")
.pattern(p)
.shadow(std::num::NonZeroU32::new(2).unwrap())
.build()
.unwrap()
};
let lines = [
("%{WORD:w}-%{NUMBER:n}", "build-42 x", None),
(
"%{IPORHOST:host} %{DATA:prog}: %{GREEDYDATA:msg}",
"10.1.2.3.4 p: m",
text(&[("host", "10.1.2.3.4"), ("prog", "p"), ("msg", "m")]),
),
];
for (native, regex, switches) in [(300.0, 100.0, true), (200.0, 100.0, false)] {
for &(pattern, line, ref want) in &lines {
let g = build(pattern);
for i in 0..31 {
if i % 2 == 0 {
super::shadow::script(&[regex, native]);
}
assert_eq!(&parse(&g, line), want, "{pattern} on {line:?}");
}
let at = format!("{pattern}, native {native}, regex {regex}");
assert_eq!(g.shadow_state(), Some((16, switches)), "{at}");
let before = super::parser::REGEX_FIRST.with(std::cell::Cell::get);
assert_eq!(&parse(&g, line), want, "{at}");
let ran = super::parser::REGEX_FIRST.with(std::cell::Cell::get) - before;
assert_eq!(ran, usize::from(switches), "{at}: regex-first runs");
}
}
}
#[test]
fn stock_pri_and_prog_read_narrower_than_the_lenient_engine() {
let build = |p: &str, lib: Library| {
Grok::builder("grok:s")
.pattern(p)
.library(lib)
.dialect(Dialect::Oniguruma)
.build()
.unwrap()
};
let pri = "^%{SYSLOG5424PRI}%{GREEDYDATA:rest}$";
let stock = build(pri, Library::default());
assert_eq!(parse(&stock, "<999>x"), None);
assert_eq!(
parse(&stock, "<165>x"),
text(&[("syslog5424_pri", "165"), ("rest", "x")])
);
let mut wide = Library::default();
wide.add("SYSLOG5424PRI", r"<(?P<syslog5424_pri>\d{1,5})>");
assert_eq!(
parse(&build(pri, wide), "<999>x"),
text(&[("syslog5424_pri", "999"), ("rest", "x")])
);
let prog = "^%{PROG:p}%{GREEDYDATA:r}$";
assert_eq!(
parse(&build(prog, Library::default()), "a:b c"),
text(&[("p", "a"), ("r", ":b c")])
);
let mut colon = Library::default();
colon.add("PROG", r"[\x21-\x5a\x5c\x5e-\x7e]+");
assert_eq!(
parse(&build(prog, colon), "a:b c"),
text(&[("p", "a:b"), ("r", " c")])
);
}
#[test]
fn names_collect_a_list_unless_only_one_branch_can_take_part() {
let g = grok(&["%{WORD:x} %{WORD:x}"]);
assert_eq!(parse(&g, "a b"), text(&[("x", "a"), ("x", "b")]));
let g = grok(&["(?:%{INT:v}|%{WORD:v})"]);
assert_eq!(parse(&g, "abc"), text(&[("v", "abc")]));
}
#[test]
fn a_group_that_took_no_part_writes_nothing_and_an_empty_one_writes_empty() {
let g = grok(&["^%{WORD:a}(?: %{INT:b})?=%{DATA:c}$"]);
assert_eq!(parse(&g, "hi="), text(&[("a", "hi"), ("c", "")]));
assert_eq!(
parse(&g, "hi 3=x"),
text(&[("a", "hi"), ("b", "3"), ("c", "x")])
);
}
#[test]
fn a_type_suffix_sets_the_hint() {
let g = grok(&["%{INT:n:int} %{NUMBER:f:float} %{WORD:b:boolean}"]);
assert_eq!(
parse(&g, "1 2.5 true"),
Some(vec![
("n".into(), "1".into(), Hint::Int),
("f".into(), "2.5".into(), Hint::Float),
("b".into(), "true".into(), Hint::Bool),
])
);
let g = whole(&["%{INT:n:integer} %{NUMBER:f:number} %{INT:i:int}"], &[]).unwrap();
let mut out = Fields::new();
g.parse(b"-7 2.5 3", &mut out).unwrap();
let hints: Vec<(&str, Hint)> = out
.as_slice()
.iter()
.map(|(n, v)| (n.as_str(), v.hint))
.collect();
assert_eq!(
hints,
[("n", Hint::Int), ("f", Hint::Float), ("i", Hint::Int)]
);
}
#[test]
fn a_typed_capture_reads_as_the_number_its_suffix_names() {
use crate::number::Number;
let g = grok(&[
"%{INT:n:int} %{NUMBER:f:float} %{NUMBER:t} %{NUMBER:i:int} %{NUMBER:g:float} %{INT:u:long} %{INT:x:long}",
]);
let mut out = Fields::new();
let line = b"007 3 4 2.5 2.5 18446744073709551615 18446744073709551616";
g.parse(line, &mut out).unwrap();
let number = |name: &str| out.get(name).unwrap().number();
assert_eq!(number("n"), Some(Number::Int(7)));
assert_eq!(
number("f"),
Some(Number::Float(3.0)),
"whole text, Float hint"
);
assert_eq!(number("t"), None, "no suffix is text");
assert_eq!(number("i"), None, "2.5 is no whole number");
assert_eq!(number("g"), Some(Number::Float(2.5)));
assert_eq!(number("u"), Some(Number::UInt(u64::MAX)));
assert_eq!(number("x"), None, "past u64");
}
#[test]
fn the_pcre_dialect_reads_patterns_written_for_it() {
let rows: [(&str, &str, &[(&str, &str)]); 9] = [
(r"\<%{INT:n}\>", "<7>", &[("n", "7")]),
(r"to=\<(?<to>[^\>\s]+)\>", "to=<a@b.c>", &[("to", "a@b.c")]),
(
r#"^{"time":"%{INT:t}"}"#,
r#"{"time":"12"}"#,
&[("t", "12")],
),
(r"v=({.+?})", "v={a}", &[]),
(r"a{2}b{,2}(?<n>\d)", "aab5", &[("n", "5")]),
(r"(?<p>[\w [\]]+)!", "a [b]!", &[("p", "a [b]")]),
(r"(?<k>[[:alpha:][]+)=", "a[b=", &[("k", "a[b")]),
(
r#"^(?|"(?<d>[^"]+)"|(?<d>\S+)) x"#,
r#""a b" x"#,
&[("d", "a b")],
),
(r#"^(?|"(?<d>[^"]+)"|(?<d>\S+)) x"#, "ab x", &[("d", "ab")]),
];
for (pattern, input, want) in rows {
let g = Grok::builder("grok:p")
.pattern(pattern)
.dialect(Dialect::Pcre)
.build()
.unwrap();
assert_eq!(parse(&g, input), text(want), "{pattern} on {input}");
}
let angled = |dialect| {
let g = Grok::builder("grok:a")
.pattern(r"\<%{INT:n}\>")
.dialect(dialect)
.build();
parse(&g.unwrap(), "7")
};
assert_eq!(angled(Dialect::Rust), text(&[("n", "7")]));
assert_eq!(angled(Dialect::Pcre), None);
let path = Grok::builder("grok:u")
.pattern("%{UNIXPATH:p}")
.dialect(Dialect::Pcre)
.build();
assert_eq!(
parse(&path.unwrap(), "/var/log"),
text(&[("p", "/var/log")])
);
}
#[test]
fn a_named_group_with_bracketed_keys_writes_its_field_path() {
for (pattern, name) in [
(r"(?<[a][b]>\d+)", "a.b"),
(r"(?<[a.b][c]>\d+)", r#"["a.b"].c"#),
(r"(?<x>\d+)", "x"),
] {
let g = Grok::builder("grok:named")
.pattern(pattern)
.dialect(Dialect::Oniguruma)
.build()
.unwrap();
let mut out = Fields::new();
g.parse(b"12", &mut out).unwrap();
let got = out
.get(name)
.map(|v| String::from_utf8_lossy(&v.bytes).into_owned());
assert_eq!(got.as_deref(), Some("12"), "{pattern}");
#[cfg(feature = "record")]
{
use crate::record::Record;
let keys: Vec<_> = crate::path::keys(name).collect();
let at = (&out).find(&keys[..]).unwrap();
assert_eq!((&out).text(at).unwrap(), "12", "{pattern}");
}
}
}
#[test]
fn the_oniguruma_dialect_reads_patterns_written_for_it() {
let onig = |p: &str| {
Grok::builder("grok:o")
.pattern(p)
.dialect(Dialect::Oniguruma)
.build()
.unwrap()
};
assert_eq!(
parse(&onig(r"\<%{INT:a}\.%{INT:b}\>"), "<0.222>"),
text(&[("a", "0"), ("b", "222")])
);
assert_eq!(
parse(&onig("^%{WORD:w}$"), "one two\nthree"),
text(&[("w", "three")])
);
assert_eq!(
parse(&onig("(?m)a%{GREEDYDATA:r}"), "a1\n2"),
text(&[("r", "1\n2")])
);
assert_eq!(
parse(&onig("%{RUUID:id}"), "id=0123456789abcdef0123456789ABCDEF"),
text(&[("id", "0123456789abcdef0123456789ABCDEF")])
);
assert_eq!(
parse(&onig("^{%{DATA:x}}$"), "{abc}"),
text(&[("x", "abc")])
);
assert_eq!(
parse(&onig(r"k={%{WORD:x}} a{,2}b x{2}"), "k={v} aab xx"),
text(&[("x", "v")])
);
assert_eq!(parse(&onig("a{,2}b"), "aaab"), Some(Vec::new()));
assert_eq!(parse(&onig("^a{,2}b"), "aaab"), None);
assert_eq!(
parse(&onig("(?'k.v'[0-9]+)"), "n=42"),
text(&[("k.v", "42")])
);
let typed = |p: &str, input: &str| {
let mut out = Fields::new();
onig(p).parse(input.as_bytes(), &mut out).unwrap();
out.as_slice()
.iter()
.map(|(n, v)| (n.clone(), v.hint))
.collect::<Vec<_>>()
};
for (p, field, hint) in [
(r"(?<INT:n.c:int>\d+)", "n.c", Hint::Int),
(r"(?<n:long>\d+)", "n", Hint::Int),
(r"(?<n:ip>\d+)", "n:ip", Hint::Text),
("%{INT:n:ip}", "n", Hint::Text),
("%{INT:n:}", "n", Hint::Text),
] {
assert_eq!(typed(p, "42"), vec![(field.to_owned(), hint)], "{p}");
}
assert_eq!(parse(&grok(&["^%{WORD:w}$"]), "one two\nthree"), None);
}
#[test]
fn the_oniguruma_line_break_is_one_break_whatever_the_platform() {
let onig = |p: &str| {
Grok::builder("grok:r")
.pattern(p)
.dialect(Dialect::Oniguruma)
.build()
.unwrap()
};
let between = onig(r"a\Rb");
for (input, hit) in [
("a\r\nb", true),
("a\nb", true),
("a\rb", true),
("a\x0bb", true),
("a\x0cb", true),
("a\u{85}b", true),
("a\u{2028}b", true),
("a\u{2029}b", true),
("ab", false),
("a b", false),
("aRb", false),
("a\n\nb", false),
("a\r\n\r\nb", false),
("a\n\rb", false),
] {
assert_eq!(parse(&between, input).is_some(), hit, "{input:?}");
}
assert_eq!(between.tier(), crate::tier::MatcherTier::Regex);
assert!(Grok::builder("grok:r").pattern(r"a\Rb").build().is_err());
assert!(
Grok::builder("grok:r")
.pattern(r"a[\R]b")
.dialect(Dialect::Oniguruma)
.build()
.is_err()
);
assert!(parse(&onig(r"a\R\nb"), "a\r\nb").is_some());
let (crlf, lf) = crate::shared_tests::windows_text::event_4688();
let (crlf, lf) = (
String::from_utf8(crlf).unwrap(),
String::from_utf8(lf).unwrap(),
);
let names = onig(r"Account Name:\s+%{DATA:name}\R\s+Account Domain:\s+%{DATA:domain}\R");
let want = text(&[("name", "Administrator"), ("domain", "ATTACKRANGE")]);
assert_eq!(parse(&names, &crlf), want);
assert_eq!(parse(&names, &lf), want);
let greedy = onig(r"Account Name:\s+%{GREEDYDATA:name}");
assert_eq!(parse(&greedy, &crlf), text(&[("name", "Administrator\r")]));
assert_eq!(parse(&greedy, &lf), text(&[("name", "Administrator")]));
}
#[test]
fn the_signature_comes_from_the_literals_every_match_starts_with() {
let g = grok(&["CEF:%{INT:v}", "LEEF:%{INT:v}"]);
assert!(g.signature().may_match(b"x CEF:1"));
assert!(!g.signature().may_match(b"syslog line"));
assert!(grok(&["%{IP:a}"]).signature().is_literal_free());
}
#[test]
fn lookaround_is_refused_on_the_linear_engine() {
let built = Grok::builder("grok:x").pattern("(?<=a)%{WORD:f}").build();
assert!(matches!(built, Err(GrokBuildError::Regex(_))));
assert!(matches!(
Grok::builder("grok:x").build(),
Err(GrokBuildError::Empty)
));
}
#[test]
fn a_lone_pattern_stops_trying_first_on_a_run_of_misses() {
let g = Grok::builder("grok:f")
.pattern("%{INT:n} %{WORD:w}$")
.build()
.unwrap();
let hit = text(&[("n", "7"), ("w", "up")]);
assert!(g.tries_first());
assert_eq!(parse(&g, "7 up"), hit);
for _ in 0..40 {
assert_eq!(parse(&g, "no match here"), None);
}
assert!(!g.tries_first());
assert_eq!(parse(&g, "x 7 up"), hit);
assert!(!g.tries_first());
for _ in 0..20 {
assert_eq!(parse(&g, "7 up"), hit);
}
assert!(g.tries_first());
}
#[test]
fn compiled_code_stops_trying_first_on_a_run_of_misses() {
let g = Grok::builder("grok:a")
.pattern("^%{COMBINEDAPACHELOG}$")
.build()
.unwrap();
let hit = r#"127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /a.gif HTTP/1.0" 200 2326 "-" "curl/8""#;
let late = r#"127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /a.gif HTTP/1.0" OK 2326"#;
assert!(g.explain().contains("compiled code"));
for miss in [r#"{"level":"info"}"#, late] {
for _ in 0..40 {
assert_eq!(parse(&g, miss), None);
}
assert!(!g.tries_first(), "{miss}");
for _ in 0..20 {
assert!(parse(&g, hit).is_some());
}
assert!(g.tries_first(), "{miss}");
}
}
#[test]
fn a_pcre_possessive_repeat_builds_only_where_it_is_the_greedy_one() {
let pcre = |p: &str| Grok::builder("grok:p").pattern(p).dialect(Dialect::Pcre);
let rows: [(&str, &str, &[(&str, &str)]); 3] = [
(
r#""(?<q>[^"]*+)" (?<n>\d++)!"#,
r#""a b" 42!"#,
&[("q", "a b"), ("n", "42")],
),
(r"ip=(?<ip>\d{1,3}+)", "ip=1234", &[("ip", "123")]),
(r"(?<w>\w?+)-", "a-", &[("w", "a")]),
];
for (pattern, input, want) in rows {
let g = pcre(pattern).build().unwrap();
assert_eq!(g.blocked(), [None], "{pattern}");
assert_eq!(parse(&g, input), text(want), "{pattern} on {input}");
}
let gives_back = r"(?<a>\w++)\w";
assert!(matches!(
pcre(gives_back).build(),
Err(GrokBuildError::Possessive { index: 0, .. })
));
let rust = Grok::builder("grok:r").pattern(gives_back).build().unwrap();
assert_eq!(parse(&rust, "ab"), text(&[("a", "a")]));
#[cfg(feature = "parse-backtracking")]
{
let g = Grok::builder("grok:b")
.backtracking_pattern(gives_back)
.dialect(Dialect::Pcre)
.build()
.unwrap();
assert_eq!(g.tier(), MatcherTier::Backtracking);
assert_eq!(parse(&g, "ab"), None);
}
}
#[cfg(feature = "parse-backtracking")]
#[test]
fn a_pattern_that_opts_in_runs_on_backtracking() {
let look = "(?<=id=)%{WORD:id}";
assert!(matches!(
Grok::builder("grok:b").pattern(look).build(),
Err(GrokBuildError::Regex(_))
));
let g = Grok::builder("grok:b")
.backtracking_pattern(look)
.build()
.unwrap();
assert_eq!(g.tier(), MatcherTier::Backtracking);
assert!(g.explain().starts_with("0: backtracking"));
assert_eq!(parse(&g, "x id=abc"), text(&[("id", "abc")]));
assert_eq!(parse(&g, "x ix=abc"), None);
let mut out = Fields::new();
assert!(matches!(
g.parse(b"\xff id=abc", &mut out),
Ok(Parsed::Done)
));
for dialect in [Dialect::Rust, Dialect::Oniguruma] {
let quoted = Grok::builder("grok:b")
.backtracking_pattern(r#"(?<q>['"])%{WORD:w}\k<q>"#)
.dialect(dialect)
.build()
.unwrap();
assert_eq!(
parse("ed, r#"say "hi""#),
text(&[("q", "\""), ("w", "hi")])
);
assert_eq!(parse("ed, r#"say "hi'"#), None);
}
let plain = Grok::builder("grok:b")
.backtracking_pattern("%{WORD:w}")
.build()
.unwrap();
assert_ne!(plain.tier(), MatcherTier::Backtracking);
}
#[cfg(feature = "parse-backtracking")]
#[test]
fn the_earliest_match_wins_across_both_engines() {
let list = |first: &str, second: &str, backtrack_first: bool| {
let b = Grok::builder("grok:b");
let b = if backtrack_first {
b.backtracking_pattern(first).pattern(second)
} else {
b.pattern(first).backtracking_pattern(second)
};
b.build().unwrap()
};
let look = "(?=b)b%{INT:look}";
assert_eq!(
parse(&list("a%{INT:lin}", look, false), "xa1b2"),
text(&[("lin", "1")])
);
assert_eq!(
parse(&list("c%{INT:lin}", look, false), "b1c2"),
text(&[("look", "1")])
);
assert_eq!(
parse(&list("b%{INT:lin}", look, false), "b1"),
text(&[("lin", "1")])
);
let three = Grok::builder("grok:b")
.pattern("z%{INT:first}")
.backtracking_pattern(look)
.pattern("b%{INT:third}")
.build()
.unwrap();
assert_eq!(parse(&three, "b1"), text(&[("look", "1")]));
assert_eq!(parse(&three, "z7"), text(&[("first", "7")]));
assert_eq!(
parse(&list(look, "b%{INT:lin}", true), "b1"),
text(&[("look", "1")])
);
}
#[cfg(feature = "parse-backtracking")]
#[test]
fn a_blown_backtracking_budget_is_a_limit() {
let g = Grok::builder("grok:b")
.backtracking_pattern(r"^((a|a)*)\1c")
.build()
.unwrap();
let mut out = Fields::new();
let line = "a".repeat(40);
assert!(matches!(
g.parse(line.as_bytes(), &mut out),
Err(ParseError::Limit { .. })
));
}
#[test]
fn only_named_fields_are_capture_slots() {
use regex_automata::PatternID;
use regex_automata::meta::Regex;
let lib = Library::default();
let mut checked = 0;
for name in lib.defs.keys() {
let e = expand_linear(&format!("%{{{name}:f}}"), &lib, Dialect::Rust).unwrap();
let Ok(regex) = Regex::new(&e.regex) else {
continue;
};
let slots = regex.group_info().group_len(PatternID::ZERO) - 1;
assert_eq!(
slots,
e.captures.len() + e.edges.len(),
"{name}: {}",
e.regex
);
checked += 1;
}
assert!(checked > 300, "only {checked} definitions built");
let kept = expand(r"((a|b)*)\1c", &lib, Dialect::Rust).unwrap();
assert_eq!(kept.regex, r"((a|b)*)\1c");
let plain = expand("(a|b)+c", &lib, Dialect::Rust).unwrap();
assert_eq!(plain.regex, "(?:a|b)+c");
}
#[test]
fn a_signature_never_rules_out_a_line_the_pattern_matches() {
for (pattern, line) in [
("colou?r=%{INT:n}", "color=5"),
("(?<level>warn)ing %{INT:n}", "warning 5"),
("a()b%{INT:n}", "ab5"),
("(?:x|)y%{INT:n}", "y5"),
("%{WORD:w}(?:\\.)?end", "abc.end"),
("^(?:)a%{INT:n}", "a5"),
] {
let g = grok(&[pattern]);
assert!(parse(&g, line).is_some(), "{pattern} matches {line:?}");
assert!(
g.signature().may_match(line.as_bytes()),
"{pattern}: the signature rules out {line:?}"
);
}
}
#[test]
fn grippo_definitions_read_their_formats_examples() {
let alb = concat!(
"http 2018-07-02T22:23:00.186641Z app/my-loadbalancer/50dc6c495c0c9188 ",
"192.168.131.39:2817 10.0.0.1:80 0.000 0.001 0.000 200 200 34 366 ",
"\"GET http://www.example.com:80/ HTTP/1.1\" \"curl/7.46.0\" - - ",
"arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067 ",
"\"Root=1-58337262-36d228ad5d99923122bbe354\" \"-\" \"-\" ",
"0 2018-07-02T22:22:48.364000Z \"forward\" \"-\" \"-\" \"10.0.0.1:80\" \"200\" \"-\" \"-\" ",
"TID_1234abcd5678ef90 \"-\" \"-\" \"-\"",
);
let ingress = concat!(
"10.0.0.7 - - [27/Nov/2026:13:55:36 +1100] \"GET /a HTTP/1.1\" 200 612 \"-\" \"curl/8.0\" ",
"78 0.004 [default-web-80] [] 10.1.0.5:80, 10.1.0.6:80 612, 612 0.003, 0.001 502, 200 ",
"2c5e7e1f0b2d4e9a",
);
let rows: [(&str, &str, &[(&str, &str)]); 6] = [
(
"KLOG",
"I1103 11:57:31.739339 24395 google.cc:2341] Command line: ./some_prog",
&[
("level", "I"),
("thread", "24395"),
("file", "google.cc"),
("message", "Command line: ./some_prog"),
],
),
(
"GLOG",
"W20261127 13:55:36.000012 7 main.cc:12] disk at 91%",
&[
("level", "W"),
("year", "2026"),
("line", "12"),
("message", "disk at 91%"),
],
),
(
"NGINX_ERROR",
"2026/11/27 13:55:36 [error] 1234#0: *5 open() \"/var/www/x\" failed (2: No such file or directory)",
&[("level", "error"), ("pid", "1234"), ("connection", "5")],
),
(
"INGRESS_NGINX",
ingress,
&[
("upstream_addr", "10.1.0.5:80, 10.1.0.6:80"),
("upstream_status", "502, 200"),
("req_id", "2c5e7e1f0b2d4e9a"),
],
),
(
"VPC_FLOW_V2",
"2 123456789010 eni-1235b8ca123456789 172.31.16.139 172.31.16.21 20641 22 6 20 4249 1418530010 1418530070 ACCEPT OK",
&[
("srcaddr", "172.31.16.139"),
("dstport", "22"),
("action", "ACCEPT"),
("log_status", "OK"),
],
),
(
"ALB_ACCESS_LOG",
alb,
&[
("type", "http"),
("client", "192.168.131.39:2817"),
("request", "GET http://www.example.com:80/ HTTP/1.1"),
("actions_executed", "forward"),
],
),
];
for (name, line, want) in rows {
let g = Grok::builder("grok:own")
.pattern(format!("^%{{{name}}}$"))
.build()
.unwrap();
let got = parse(&g, line).unwrap_or_else(|| panic!("{name} misses its example"));
for (field, value) in want {
assert!(
got.iter().any(|(f, v, _)| f == field && v == value),
"{name}: {field} isn't {value:?} in {got:?}"
);
}
let mut out = Fields::new();
let by_regex = g.parse_regex(line.as_bytes(), &mut out).unwrap();
assert_ne!(by_regex, Parsed::NoMatch, "{name}");
let regex: Vec<(String, String)> = out
.as_slice()
.iter()
.map(|(n, v)| (n.clone(), String::from_utf8_lossy(&v.bytes).into_owned()))
.collect();
let native: Vec<(String, String)> = got.into_iter().map(|(n, v, _)| (n, v)).collect();
assert_eq!(native, regex, "{name}");
}
}
#[cfg(feature = "parse-backtracking")]
fn oracle(names: &[&str]) -> Option<Library> {
let dir = std::env::var_os("GRIPPO_ORACLE_DIR")?;
let mut bundled = Library::default();
for name in names {
bundled.add_file(&std::fs::read_to_string(std::path::Path::new(&dir).join(name)).ok()?);
}
for f in FIELDS {
bundled.add(f.name, f.regex);
}
Some(bundled)
}
#[cfg(feature = "parse-backtracking")]
#[test]
#[allow(clippy::too_many_lines, reason = "one table of 32 definitions")]
fn base_definitions_hold_their_lines_and_report_where_the_bundled_ones_differ() {
use fancy_regex::Regex;
let bundled = oracle(&["grok-patterns"]);
let own = Library::default();
let accepts = |lib: &Library, name: &str, line: &str| {
let e = expand(&format!("^%{{{name}}}$"), lib, Dialect::Rust).unwrap();
Regex::new(&e.regex).unwrap().is_match(line).unwrap()
};
#[allow(clippy::type_complexity, reason = "a literal table")]
let rows: &[(&str, &[&str], &[&str], &[&str])] = &[
("USER", &["root", "a.b-c_d"], &["a b", ""], &[]),
(
"QS",
&[r#""a b""#, "'x'", r#""a\"b""#],
&["abc", r#""open"#],
&[],
),
("DATA", &["", "anything at all"], &[], &[]),
(
"BASE16FLOAT",
&["1A", "0x1F.8", "-.5", "+0Xff.", "3.14"],
&["", "g1", "1.2.3"],
&["1.", "x1", "1.5e3"],
),
(
"URN",
&[
"urn:isbn:0451450523",
"URN:ietf:rfc:2648",
"urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66",
"urn:example:a%20b",
"urn:example:a/b?+r=1?=q=2#frag",
],
&[
"urn:a:x",
"urn:-ab:x",
"urn:ab-:x",
"urn:example:",
"urn:example:a b",
"mailto:x",
],
&["urn:example:a?b", "urn:example:%zz"],
),
(
"CISCOMAC",
&["0011.2233.4455", "aAbB.cCdD.eEfF"],
&["00:11:22:33:44:55", "0011.2233", "0011.2233.445g"],
&[],
),
(
"WINDOWSMAC",
&["00-11-22-33-44-55", "AA-bb-CC-dd-EE-ff"],
&["00:11:22:33:44:55", "00-11-22-33-44", "00-11-22-33-44-5"],
&[],
),
(
"COMMONMAC",
&["00:11:22:33:44:55", "aa:BB:cc:DD:ee:FF"],
&["00-11-22-33-44-55", "00:11:22:33:44", "00:11:22:33:44:gg"],
&[],
),
(
"HOSTPORT",
&["example.com:80", "10.0.0.1:8080", "host:0", "host:080"],
&["example.com", "example.com:", "example.com:http"],
&[],
),
(
"PATH",
&[
"/var/log/syslog",
"/",
r"C:\Windows\System32",
r"\\srv\share\f.txt",
],
&["relative/path", "var/log", ""],
&[],
),
(
"TTY",
&[
"/dev/pts/0",
"/dev/tty1",
"/dev/ttyS0",
"/dev/ttyUSB12",
"/dev/ttyp3",
"/dev/ttys003",
],
&["/dev/tty", "/dev/pts/", "/dev/sda1", "tty1"],
&["/dev/pts0", "/dev/tty/3", "/dev/ttyp"],
),
(
"URIHOST",
&[
"example.com",
"example.com:8080",
"10.1.2.3:80",
"[::1]:443",
"[2001:db8::1]",
],
&["", "/path", "[::1"],
&[],
),
(
"URIPATHPARAM",
&["/a/b", "/a/b?x=1&y=2", "/", "/index.html?q=a%20b"],
&["a/b", "?x=1", ""],
&[],
),
(
"URI",
&[
"http://example.com",
"https://example.com:8443/a/b?x=1",
"ftp://user:pa55@host/file.txt",
"file:///etc/hosts",
"http://[::1]:80/x",
"ldap://u@h",
],
&[
"example.com/a",
"http:/example.com",
"http//example.com",
"",
],
&["ftp://u:p ss@h/", "http://u:p@ss@h/"],
),
(
"MONTHNUM",
&["1", "01", "9", "12"],
&["0", "00", "13", "x"],
&[],
),
("MONTHNUM2", &["01", "09", "12"], &["1", "00", "13"], &[]),
(
"DAY",
&[
"Mon", "Monday", "Tue", "Tuesday", "Wed", "Thu", "Fri", "Sat", "Sun", "Sunday",
],
&["mon", "Mo", "Funday", ""],
&[],
),
(
"DATE_US",
&["12/31/2023", "1-2-23", "01/02/99"],
&["13/01/2023", "12.31.2023"],
&["12/32/2023"],
),
(
"DATE_EU",
&["31/12/2023", "31.12.2023", "1-2-23"],
&["31/13/2023", "31 12 2023"],
&["32/12/2023"],
),
(
"ISO8601_SECOND",
&["00", "59", "60", "05.123", "30,5"],
&["5", "61", "70", ""],
&["59:123"],
),
(
"DATE",
&["12/31/2023", "31.12.2023"],
&["2023-12-31", "x"],
&[],
),
(
"DATESTAMP",
&[
"12/31/2023 23:59:59",
"31.12.2023-01:02:03",
"1-2-23 4:05:06",
],
&["12/31/2023", "12/31/2023T23:59:59"],
&[],
),
(
"TZ",
&[
"UTC", "UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT", "AST",
],
&["CET", "est", "ABC", ""],
&["ADT"],
),
(
"DATESTAMP_RFC822",
&[
"Sat, 21 Aug 2021 10:11:12 GMT",
"21 Aug 2021 10:11 UT",
"Sat, 21 Aug 21 10:11:12 +0000",
"Sat Aug 21 2021 10:11:12 EST",
],
&[
"Sat, 21 Aug 2021",
"Sat, 21 Aug 2021 10:11:12",
"2021-08-21 10:11:12 GMT",
],
&["Sat, 21 Aug 2021 10:11:12 +00:00"],
),
(
"DATESTAMP_RFC2822",
&[
"Fri, 21 Nov 1997 09:55:06 -0600",
"21 Nov 1997 09:55 +0000",
"Tue, 1 Jul 2003 10:52:37 +0200",
"Fri, 21 Nov 1997 09:55:06 GMT",
"Fri, 21 Nov 1997 09:55:06 Z",
],
&[
"Fri 21 Nov 1997 09:55:06 -0600",
"Fri, 21 Nov 1997 09:55:06",
"1997-11-21 09:55:06 -0600",
],
&["Fri, 21 Nov 1997 09:55:06 +06:00"],
),
(
"DATESTAMP_OTHER",
&[
"Tue Nov 28 12:00:00 UTC 2023",
"Tue Nov 5 12:00:00 UTC 2023",
"Tue Nov 5 12:00:00 EST 2023",
],
&["Tue Nov 28 2023 12:00:00 UTC", "Nov 28 12:00:00 UTC 2023"],
&[],
),
(
"DATESTAMP_EVENTLOG",
&["20231128120000", "19991231235960"],
&[
"2023112812000",
"20231328120000",
"20231128246000",
"2023-11-28 12:00:00",
],
&["2023112812000000", "231128120000"],
),
(
"PROG",
&["sshd", "systemd-logind", "CRON", "a/b.c_d"],
&["", "a b", "a:b", "a[1]"],
&["sshd:"],
),
(
"SYSLOGPROG",
&["sshd", "sshd[1234]", "kernel[0]", "dhclient[99]"],
&["", "sshd[]", "sshd[x]", "sshd [1]"],
&[],
),
(
"SYSLOGHOST",
&["host1", "host1.example.com", "10.0.0.1", "2001:db8::1"],
&["", "a b"],
&[],
),
(
"SYSLOGFACILITY",
&["<1.6>", "<16.0>"],
&["<1,6>", "<34>", "<a.b>", "1.6"],
&["<1x6>"],
),
(
"SYSLOGBASE",
&[
"Jan 5 10:11:12 host sshd[42]:",
"Nov 28 12:00:00 <4.6> host.example.com CRON:",
"Dec 31 23:59:59 10.0.0.1 kernel[0]:",
],
&[
"Jan 5 10:11:12 host sshd",
"host sshd[42]:",
"2023-11-28T12:00:00 host sshd:",
],
&[],
),
];
assert_eq!(rows.len(), 32);
let mut differences = Vec::new();
let mut wrong = Vec::new();
for (name, hits, misses, probes) in rows {
for line in *hits {
if !accepts(&own, name, line) {
wrong.push(format!("{name} misses {line:?}"));
}
}
for line in *misses {
if accepts(&own, name, line) {
wrong.push(format!("{name} matches {line:?}"));
}
}
for line in hits.iter().chain(*misses).chain(*probes) {
let Some(bundled) = &bundled else { continue };
let (new, old) = (accepts(&own, name, line), accepts(bundled, name, line));
if new != old {
differences.push(format!("{name} {line:?}: base {new}, bundled {old}"));
}
}
}
for d in &differences {
println!("DIFF {d}");
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
#[cfg(feature = "parse-backtracking")]
#[test]
#[allow(clippy::too_many_lines, reason = "one table of 82 definitions")]
fn own_file_definitions_hold_their_lines_and_report_where_the_bundled_ones_differ() {
use fancy_regex::Regex;
let bundled = oracle(&["linux-syslog", "java", "httpd", "aws", "firewalls"]);
let own = Library::default();
let accepts = |lib: &Library, name: &str, line: &str| {
let e = expand(&format!("^%{{{name}}}$"), lib, Dialect::Rust).unwrap();
Regex::new(&e.regex).is_ok_and(|re| re.is_match(line).unwrap_or(false))
};
let s3 = concat!(
"79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be DOC-EXAMPLE-BUCKET1 ",
"[06/Feb/2019:00:00:38 +0000] 192.0.2.3 ",
"79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be 3E57427F3EXAMPLE ",
"REST.GET.VERSIONING - \"GET /DOC-EXAMPLE-BUCKET1?versioning HTTP/1.1\" 200 - 113 - 7 - ",
"\"-\" \"S3Console/0.4\" -",
);
let s3_full = format!(
"{s3} s9lzHYrFp76ZVxRcpX9+5cjAnEH2ROuNkd2BHfIa6UkFVdtjf5mKR3/eTPFvsiP/XV/VLi31234= \
SigV2 ECDHE-RSA-AES128-GCM-SHA256 AuthHeader DOC-EXAMPLE-BUCKET1.s3.us-west-1.amazonaws.com TLSV1.1"
);
let s3_ap = format!("{s3_full} arn:aws:s3:us-west-1:123456789012:accesspoint/ap Yes");
let cf_short = "2019-12-04\t21:02:31\tSFO5-C1\t392\t192.0.2.100\tGET\td111111abcdef8.cloudfront.net\t/index.html\t200\t-\tMozilla/5.0%20(Windows)\tkey1=value1\t-\tHit\tSOX4xwn4XV6Q4rgb7XiVGOHms_BGlTAC4KyHmureZmBNrjGdRLiNIQ==\td111111abcdef8.cloudfront.net\thttps\t23\t0.001\t-\tTLSv1.2\tECDHE-RSA-AES128-GCM-SHA256\tHit";
let cf_full = format!("{cf_short}\tHTTP/2.0\t-\t-\t11040\t0.001\tHit\ttext/html\t78\t-\t-");
let cf_spaces = cf_short.replace('\t', " ");
let cf_cut = cf_short.rsplit_once('\t').unwrap().0.to_string();
let elb = "2015-05-13T23:39:43.945958Z my-loadbalancer 192.168.131.39:2817 10.0.0.1:80 0.000073 0.001048 0.000057 200 200 0 29 \"GET http://www.example.com:80/ HTTP/1.1\"";
let elb_full = format!("{elb} \"curl/7.38.0\" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2");
let elb_down = "2015-05-13T23:39:43.945958Z lb 192.168.131.39:2817 - -1 -1 -1 503 0 0 0 \"GET http://www.example.com:80/ HTTP/1.1\" \"curl/7.38.0\" - -";
let elb_cut = elb.rsplit_once(' ').unwrap().0.to_string();
let rfc5424_a = r"<34>1 2003-10-11T22:14:15.003Z mymachine.example.com su - ID47 - 'su root' failed for lonvick on /dev/pts/8";
let rfc5424_b = r#"<165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47 [exampleSDID@32473 iut="3" eventSource="Application" eventID="1011"] An application event log entry"#;
let rfc5424_nil = "<165>1 - - - - - -";
let rfc5424_base = r#"<165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47 [exampleSDID@32473 iut="3"]"#;
let rfc5424_nosd = "<165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47";
let rfc5424_ver0 = "<165>0 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47 -";
let rfc5424_underscore = "<165>1 2003-10-11T22:14:15.003Z my_machine evntslog - ID47 -";
let pam_open = "Oct 11 22:14:15 host sshd[1]: pam_unix(sshd:session): session opened for user root by (uid=0)";
let pam_close =
"Oct 11 22:14:15 host sshd[1]: pam_unix(sshd:session): session closed for user root";
let pam_auth =
"Oct 11 22:14:15 host sshd[1]: pam_unix(sshd:auth): authentication failure; logname= uid=0";
let cron_hour =
"Oct 11 22:15:01 host CRON[1234]: (root) CMD (cd / && run-parts --report /etc/cron.hourly)";
let cron_nested = "Oct 11 22:15:01 host CRON[1234]: (root) CMD (test -x /usr/sbin/anacron || ( cd / && run-parts))";
let cron_reload = "Nov 1 03:00:00 host cron[9]: (alice) RELOAD (crontabs/alice)";
let cron_lower = "Oct 11 22:15:01 host CRON[1234]: (root) cmd (x)";
let cron_nouser = "Oct 11 22:15:01 host CRON[1234]: root CMD (x)";
let common =
r#"127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326"#;
let common_dav = r#"10.0.0.1 - - [10/Oct/2000:13:55:36 -0700] "M-SEARCH * HTTP/1.1" 200 -"#;
let common_408 = r#"host.example.com - - [10/Oct/2000:13:55:36 +0000] "-" 408 -"#;
let common_raw = r#"10.0.0.1 - - [10/Oct/2000:13:55:36 +0000] "GARBAGE" 400 226"#;
let common_nobytes = r#"127.0.0.1 - - [10/Oct/2000:13:55:36 -0700] "GET / HTTP/1.1" 200"#;
let common_badstatus = r#"127.0.0.1 - - [10/Oct/2000:13:55:36 -0700] "GET / HTTP/1.1" ok 12"#;
let combined =
format!(r#"{common} "http://example.com/start.html" "Mozilla/4.08 [en] (Win98; I ;Nav)""#);
let combined_short = common;
let err20 = "[Fri Sep 09 10:42:29 2011] [error] [client 72.15.99.187] File does not exist: /usr/local/apache2/htdocs/favicon.ico";
let err20_notice = "[Fri Sep 09 10:42:29 2011] [notice] Apache/2.2.15 configured";
let err20_nobracket = "[Fri Sep 09 10:42:29 2011] error [client 1.2.3.4] x";
let err24 = "[Fri Sep 09 10:42:29.902022 2011] [core:error] [pid 35708:tid 4328636416] [client 72.15.99.187:50343] AH00124: Request exceeded the limit of 10 internal redirects";
let err24_authz = "[Thu Mar 10 11:12:13.123456 2016] [authz_core:error] [pid 1:tid 2] [client 10.0.0.1:5000] AH01630: client denied by server configuration: /var/www/";
let err24_os = "[Thu Mar 10 11:12:13.123456 2016] [core:error] [pid 3:tid 4] (13)Permission denied: [client 1.2.3.4:80] AH00035: access to / denied (filesystem path '/x') because search permissions are missing";
let err24_start = "[Thu Mar 10 11:12:13.123456 2016] [mpm_prefork:notice] [pid 1] AH00163: Apache/2.4.7 configured";
let err24_nomodule = "[Thu Mar 10 11:12:13.123456 2016] [:error] [pid 1] AH00001: x";
let err24_text = "[Fri Sep 09 10:42:29.902022 2011] [core:error] [pid 1:tid 2] [client 1.2.3.4:80] File does not exist: /x";
let err24_nopid = "[Fri Sep 09 10:42:29.902022 2011] [core:error] [client 1.2.3.4:80] x";
let err24_nocolon = "[Fri Sep 09 10:42:29.902022 2011] [error] [pid 1] x";
let s3_trunc = "79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be DOC-EXAMPLE-BUCKET1 [06/Feb/2019:00:00:38 +0000] 192.0.2.3";
let ns = r#"Nov 21 10:00:00 10.0.0.1 ns204: NetScreen device_id=ns204 [Root]system-notification-00257(traffic): start_time="2007-04-30 13:25:22" duration=0 policy_id=2 service=udp/port:135 proto=17 src zone=Untrust dst zone=Trust action=Deny sent=0 rcvd=0 src=1.2.3.4 dst=5.6.7.8 src_port=1034 dst_port=135 src-xlated ip=1.2.3.4 port=1034 dst-xlated ip=5.6.7.8 port=135 session_id=0 reason=Close - AGE OUT"#;
let ns_cut = ns.split(" reason=").next().unwrap().to_string();
let t302013 = "Built inbound TCP connection 12345 for outside:10.1.1.1/1234 (10.1.1.1/1234) to inside:10.2.2.2/80 (10.2.2.2/80)";
let t302014 = "Teardown TCP connection 12345 for outside:1.1.1.1/1 to inside:2.2.2.2/80 duration 0:00:05 bytes 1234 TCP FINs";
let t302014_rst = "Teardown TCP connection 1 for outside:1.1.1.1/1 to inside:2.2.2.2/80 duration 0:00:05 bytes 1234 TCP Reset-I";
let t302014_user = format!("{t302014} (bob)");
let t302015 = "Built outbound UDP connection 2 for dmz:1.1.1.1/53 (1.1.1.1/53) to inside:2.2.2.2/53 (2.2.2.2/53)";
let t302013_noid = "Built inbound TCP connection for outside:10.1.1.1/1234 (10.1.1.1/1234) to inside:10.2.2.2/80 (10.2.2.2/80)";
let t313005 = "No matching connection for ICMP error message: icmp src outside:10.1.1.1 dst inside:10.2.2.2 (type 3, code 3) on outside interface. Original IP payload: tcp src 10.2.2.2/1234 dst 10.3.3.3/80";
let t313005_one = t313005.replace(". Original", ". Original");
let t313005_noport = t313005.replace("10.2.2.2/1234", "10.2.2.2");
let t713172 = "Group = g1, IP = 1.1.1.1, Automatic NAT Detection Status: Remote end is NOT behind a NAT device This end IS behind a NAT device";
let t713172_cut = t713172.split(" This").next().unwrap().to_string();
let t733100 = "[ 10.1.1.1] drop rate-1 exceeded. Current burst rate is 1 per second, max configured rate is 10; Current average rate is 0 per second, max configured rate is 5; Cumulative total count is 20";
let t733100_cut = t733100.replace(
"Cumulative total count is 20",
"Cumulative total count is x",
);
let mac = "MAC=00:11:22:33:44:55:66:77:88:99:aa:bb:08:00";
let nf_tcp = format!(
"IN=eth0 OUT= {mac} SRC=1.2.3.4 DST=5.6.7.8 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=1234 DF PROTO=TCP SPT=1234 DPT=22 WINDOW=1 RES=0x00 SYN URGP=0"
);
let nf_icmp = format!(
"IN=eth0 OUT= {mac} SRC=1.2.3.4 DST=5.6.7.8 LEN=84 TOS=0x00 PREC=0x00 TTL=64 ID=1 DF PROTO=ICMP TYPE=8 CODE=0 ID=1 SEQ=2"
);
let nf_out = "IN= OUT=eth1 SRC=1.2.3.4 DST=5.6.7.8 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=1 PROTO=UDP SPT=53 DPT=53 LEN=40";
let shorewall = format!("Nov 27 10:00:00 fw kernel: Shorewall:net2fw:DROP:{nf_tcp}");
let shorewall_icmp = format!("Nov 27 10:00:00 fw kernel: Shorewall:net2fw:DROP:{nf_icmp}");
let shorewall_egress = format!("Nov 27 10:00:00 fw kernel: Shorewall:fw2net:ACCEPT:{nf_out}");
let shorewall_cut = "Nov 27 10:00:00 fw kernel: Shorewall:net2fw:DROP:IN=eth0 OUT= SRC=1.2.3.4";
let shorewall_noprefix = format!("Nov 27 10:00:00 fw kernel: {nf_tcp}");
let sfw2 = format!("Nov 27 10:00:00 linux kernel: SFW2-INext-DROP-DEFLT {nf_tcp}");
let sfw2_uptime =
format!("Nov 27 10:00:00 linux kernel: [1234.5678] SFW2-INext-DROP-DEFLT {nf_tcp}");
let sfw2_iso = format!("2023-11-27T10:00:00+11:00 linux kernel: SFW2-INext-ACC-TCP {nf_tcp}");
let sfw2_icmp = format!("Nov 27 10:00:00 linux kernel: SFW2-INext-DROP-DEFLT {nf_icmp}");
let sfw2_egress = format!("Nov 27 10:00:00 linux kernel: SFW2-OUT-DROP {nf_tcp}");
let sfw2_cut = "Nov 27 10:00:00 linux kernel: SFW2-INext-DROP-DEFLT IN=eth0 OUT= MAC=";
#[allow(clippy::type_complexity, reason = "a literal table")]
let rows: Vec<(&str, Vec<&str>, Vec<&str>, Vec<&str>)> = vec![
(
"SYSLOG5424PRINTASCII",
vec!["abc", "!~"],
vec!["", "a b"],
vec![],
),
(
"SYSLOG5424PRI",
vec!["<0>", "<34>", "<191>"],
vec!["<192>", "<>", "<034>", "<a>", "34"],
vec!["<999>"],
),
(
"SYSLOG5424SD",
vec![
r#"[exampleSDID@32473 iut="3" eventSource="Application"]"#,
r#"[a@1 x="1"][b@2 y="2"]"#,
"[x]",
r#"[a@1 m="say \"hi\" \] ok"]"#,
],
vec!["-", "", "[a@1 x=1]", "[a b]"],
vec!["[a@1 x=\"1\"] trailing"],
),
(
"SYSLOG5424BASE",
vec![rfc5424_base, rfc5424_nil, rfc5424_underscore],
vec![rfc5424_ver0, rfc5424_nosd, "<165>1"],
vec![],
),
(
"SYSLOG5424LINE",
vec![rfc5424_a, rfc5424_b],
vec!["<34>1 x", "no priority here"],
vec![],
),
(
"SYSLOGBASE2",
vec![
"Oct 11 22:14:15 mymachine",
"Oct 11 22:14:15 mymachine su[12]:",
"2003-10-11T22:14:15 host sshd:",
"Oct 11 22:14:15 <4.6> host sshd:",
],
vec!["mymachine su:", "Oct 11 22:14:15"],
vec!["Oct 11 22:14:15 host sshd[12]: msg"],
),
(
"SYSLOGLINE",
vec![
"Oct 11 22:14:15 mymachine su: 'su root' failed",
"Oct 11 22:14:15 host hello",
],
vec!["Oct 11 22:14:15", "hello world"],
vec![],
),
(
"SYSLOGPAMSESSION",
vec![pam_open, pam_close],
vec![
pam_auth,
"sshd[1]: pam_unix(sshd:session): session opened for user root",
],
vec![],
),
(
"CRON_ACTION",
vec!["CMD", "BEGIN EDIT", "RELOAD"],
vec!["cmd", "", " CMD"],
vec!["CMD "],
),
(
"CRONLOG",
vec![cron_hour, cron_nested, cron_reload],
vec![cron_lower, cron_nouser],
vec![],
),
(
"JAVACLASS",
vec![
"java.lang.NullPointerException",
"Foo",
"com.example.Outer$Inner",
"_a.$b",
],
vec!["", "1abc", "a..b", ".a"],
vec!["a.b."],
),
(
"JAVAFILE",
vec!["Foo.java", "Native Method", "Unknown Source", "Foo$Bar.kt"],
vec!["", "a(b)"],
vec!["Foo.java:12"],
),
(
"JAVAMETHOD",
vec!["main", "<init>", "<clinit>", "lambda$run$0"],
vec!["", "<foo>", "1x"],
vec![],
),
(
"JAVASTACKTRACEPART",
vec![
"\tat com.example.Foo.bar(Foo.java:42)",
" at java.lang.Thread.run(Thread.java:748)",
"\tat com.example.Foo.<init>(Foo.java:10)",
"\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)",
"\tat java.base/java.lang.Thread.run(Thread.java:834)",
"\tat app//com.example.Foo.bar(Foo.java:7)",
"\tat jdk.internal@17.0.1/jdk.internal.Foo.bar(Foo.java:7)",
"\tat Foo.lambda$main$0(Foo.java:5)",
],
vec![
"\tat com.example.Foo.bar(Foo.java:abc)",
"\tin com.example.Foo.bar(Foo.java:1)",
"",
],
vec![],
),
(
"JAVATHREAD",
vec!["TP-Processor12", "HP-Processor1"],
vec!["tp-Processor1", "TP-Processor", "main"],
vec![],
),
("JAVALOGMESSAGE", vec!["", "any text"], vec![], vec![]),
(
"CATALINA_DATESTAMP",
vec!["Jan 9, 2014 7:13:13 AM", "Dec 31, 2023 12:00:01 PM"],
vec![
"Jan 9, 2014 13:13:13 PM",
"Jan 9, 14 7:13:13 AM",
"Jan 9, 2014 7:13:13",
],
vec!["Jan 9, 2014 07:13:13 AM", "Jan 9, 2014 7:13:13 am"],
),
(
"TOMCAT_DATESTAMP",
vec!["2014-01-09 17:32:25,527 -0800", "2014-01-09 17:32:25 +0000"],
vec!["2014-01-09 17:32:25,527", "14-01-09 17:32:25 -0800"],
vec!["2014-1-9 17:32:25,527 -0800"],
),
(
"CATALINALOG",
vec!["Jan 9, 2014 7:13:13 AM org.apache.catalina.core.AprLifecycleListener init"],
vec!["org.apache.catalina.core.AprLifecycleListener init"],
vec![],
),
(
"TOMCATLOG",
vec![
"2014-01-09 20:03:28,269 -0800 | ERROR | com.example.service.ExampleService - something happened",
],
vec!["2014-01-09 20:03:28,269 -0800 ERROR | c - m"],
vec![],
),
(
"HTTPDUSER",
vec!["-", "alice", "alice@example.com"],
vec!["", "a b"],
vec![],
),
(
"HTTPDERROR_DATE",
vec![
"Fri Sep 09 10:42:29.902022 2011",
"Fri Sep 09 10:42:29 2011",
],
vec!["Sep 09 10:42:29 2011", "2011-09-09 10:42:29"],
vec![],
),
(
"HTTPD_COMMONLOG",
vec![common, common_dav, common_408, common_raw],
vec![common_nobytes, common_badstatus, "no brackets here"],
vec![],
),
(
"HTTPD_COMBINEDLOG",
vec![&combined],
vec![combined_short],
vec![],
),
(
"HTTPD20_ERRORLOG",
vec![err20, err20_notice],
vec![err20_nobracket],
vec![],
),
(
"HTTPD24_ERRORLOG",
vec![err24, err24_authz, err24_os, err24_start, err24_nomodule],
vec![err24_nopid, err24_nocolon],
vec![err24_text],
),
(
"HTTPD_ERRORLOG",
vec![err20, err24, err24_os],
vec![err20_nobracket],
vec![],
),
(
"COMMONAPACHELOG",
vec![common],
vec![common_nobytes],
vec![],
),
(
"COMBINEDAPACHELOG",
vec![&combined],
vec![combined_short],
vec![],
),
(
"S3_REQUEST_LINE",
vec!["GET /b/k?x=1 HTTP/1.1", "-"],
vec![],
vec!["GET /b/k"],
),
(
"S3_ACCESS_LOG",
vec![&s3, &s3_full, &s3_ap],
vec![s3_trunc, ""],
vec![],
),
(
"ELB_URIPATHPARAM",
vec!["/a/b?x=1", "/"],
vec!["a/b", "?x=1"],
vec![],
),
(
"ELB_URI",
vec![
"http://www.example.com:80/",
"https://host/p?q=1",
"http://u:p@host:8080/x",
],
vec!["www.example.com/", "/path"],
vec!["http://[::1]:80/"],
),
(
"ELB_REQUEST_LINE",
vec!["GET http://www.example.com:80/ HTTP/1.1", "- - - "],
vec![],
vec!["GET /relative HTTP/1.1"],
),
(
"ELB_ACCESS_LOG",
vec![elb, &elb_full, elb_down],
vec![&elb_cut, ""],
vec![],
),
(
"CLOUDFRONT_ACCESS_LOG",
vec![cf_short, &cf_full],
vec![&cf_spaces, &cf_cut],
vec![],
),
(
"NETSCREENSESSIONLOG",
vec![ns],
vec![&ns_cut, "NetScreen device_id=ns204"],
vec![],
),
(
"CISCO_TAGGED_SYSLOG",
vec![
"<166>Jan 05 2023 10:11:12 fw01 : %ASA-6-302013:",
"<166>Jan 5 10:11:12 : %ASA-4-106023:",
],
vec![
"<166>Jan 5 10:11:12 fw01 %ASA-6-302013:",
"<166>Jan 5 10:11:12 fw01 : %ASA-9-302013:",
"Jan 5 10:11:12 fw01 : %ASA-6-302013:",
],
vec![],
),
(
"CISCOTIMESTAMP",
vec!["Jan 05 2023 10:11:12", "Jan 5 10:11:12", "Nov 28 12:00:00"],
vec!["2023-01-05 10:11:12", "Jan 05"],
vec![],
),
(
"CISCOTAG",
vec!["ASA-6-302013", "PIX-4-106023", "FWSM-1-105005"],
vec!["ASA-9-302013", "ASA-6-", "asa-6-302013"],
vec![],
),
(
"CISCO_ACTION",
vec!["Built", "Denied", "denied by ACL", "Dropping"],
vec!["", "Allowed"],
vec![],
),
(
"CISCO_REASON",
vec![
"No matching connection",
"TCP Reset-I",
"TCP FINs",
"Duplicate TCP SYN",
],
vec!["", "TCP:"],
vec!["a b"],
),
(
"CISCO_DIRECTION",
vec!["Inbound", "outbound"],
vec!["inout", ""],
vec![],
),
(
"CISCO_INTERVAL",
vec!["first hit", "300-second interval"],
vec!["second interval", "first"],
vec![],
),
(
"CISCO_XLATE_TYPE",
vec!["static", "dynamic"],
vec!["Static", ""],
vec![],
),
(
"CISCOFW104001",
vec!["(Primary) Switching to ACTIVE - HELLO not heard from mate."],
vec!["Switching to ACTIVE - x"],
vec![],
),
(
"CISCOFW104002",
vec!["(Secondary) Switching to STANDBY - Other unit set to Active"],
vec!["(Third) Switching to STANDBY - x"],
vec![],
),
(
"CISCOFW104003",
vec!["(Primary) Switching to FAILED."],
vec!["(Primary) Switching to FAILED"],
vec![],
),
(
"CISCOFW104004",
vec!["(Secondary) Switching to OK."],
vec!["(Secondary) Switching to Ok."],
vec![],
),
(
"CISCOFW105003",
vec!["(Primary) Monitoring on interface outside waiting"],
vec!["(Primary) Monitoring on interface waiting"],
vec![],
),
(
"CISCOFW105004",
vec!["(Primary) Monitoring on Interface inside normal"],
vec!["(Primary) Monitoring on interface inside"],
vec![],
),
(
"CISCOFW105005",
vec!["(Primary) Lost Failover communications with mate on interface outside"],
vec!["(Primary) Lost communications with mate on interface outside"],
vec![],
),
(
"CISCOFW105008",
vec!["(Primary) Testing Interface inside"],
vec!["(Primary) Testing inside"],
vec![],
),
(
"CISCOFW105009",
vec!["(Primary) Testing on interface inside Passed"],
vec!["(Primary) Testing on interface inside Maybe"],
vec![],
),
(
"CISCOFW106001",
vec![
"Inbound TCP connection denied from 10.1.1.1/12345 to 10.2.2.2/80 flags SYN on interface outside",
],
vec![
"Inbound TCP connection denied from 10.1.1.1 to 10.2.2.2/80 flags SYN on interface outside",
],
vec![],
),
(
"CISCOFW106006_106007_106010",
vec![
"Deny inbound UDP from 10.1.1.1/137 to 10.2.2.2/137 on interface outside",
"Deny inbound UDP from 10.1.1.1/53 to 10.2.2.2/1024 due to DNS Response",
"Deny inbound TCP from 10.1.1.1/1(bob) to 10.2.2.2/80(alice) on interface dmz",
],
vec![
"Deny inbound UDP from 10.1.1.1/137 to 10.2.2.2/137",
"Allow inbound UDP from 10.1.1.1/137 to 10.2.2.2/137 on interface outside",
],
vec![],
),
(
"CISCOFW106014",
vec!["Deny inbound icmp src outside:10.1.1.1 dst inside:10.2.2.2 (type 8, code 0)"],
vec!["Deny inbound icmp src outside:10.1.1.1 dst inside:10.2.2.2"],
vec![],
),
(
"CISCOFW106015",
vec![
"Deny TCP (no connection) from 10.1.1.1/80 to 10.2.2.2/1234 flags RST on interface outside",
],
vec!["Deny TCP from 10.1.1.1/80 to 10.2.2.2/1234 flags RST on interface outside"],
vec![],
),
(
"CISCOFW106021",
vec!["Deny tcp reverse path check from 10.1.1.1 to 10.2.2.2 on interface outside"],
vec!["Deny tcp reverse path check from 10.1.1.1 to 10.2.2.2"],
vec![],
),
(
"CISCOFW106023",
vec![
r#"Deny tcp src outside:10.1.1.1/1234 dst inside:10.2.2.2/80 by access-group "acl_in" [0x0, 0x0]"#,
r#"Deny icmp src outside:10.1.1.1 dst inside:10.2.2.2 (type 8, code 0) by access-group "acl_in" [0x0, 0x0]"#,
],
vec![
"Deny tcp src outside:10.1.1.1/1234 dst inside:10.2.2.2/80 by access-group acl_in",
],
vec![],
),
(
"CISCOFW106100_2_3",
vec![
"access-list acl_in permitted tcp for user 'bob' outside/10.1.1.1(1234) -> inside/10.2.2.2(80) hit-cnt 1 first hit [0x1a2b, 0x0]",
],
vec![
"access-list acl_in permitted tcp outside/10.1.1.1(1234) -> inside/10.2.2.2(80) hit-cnt 1 first hit [0x1a2b, 0x0]",
],
vec![],
),
(
"CISCOFW106100",
vec![
"access-list acl_in permitted tcp outside/10.1.1.1(1234) -> inside/10.2.2.2(80) hit-cnt 1 first hit [0x1a2b3c4d, 0x0]",
"access-list acl_in denied udp outside/10.1.1.1(53)(bob) -> inside/10.2.2.2(53)(alice) hit-cnt 3 300-second interval [0x1, 0x2]",
],
vec![
"access-list acl_in permitted tcp outside/10.1.1.1(1234) inside/10.2.2.2(80) hit-cnt 1 first hit [0x1, 0x0]",
],
vec![],
),
(
"CISCOFW304001",
vec![
"10.1.1.1 Accessed URL 10.2.2.2:http://example.com/index.html",
"10.1.1.1(bob) Accessed URL 10.2.2.2:http://example.com/",
],
vec!["10.1.1.1 Visited URL 10.2.2.2:x"],
vec![],
),
(
"CISCOFW110002",
vec![
"Failed to locate egress interface for TCP from outside:10.1.1.1/1234 to 10.2.2.2/80",
],
vec!["Failed to locate egress interface for TCP from 10.1.1.1/1234 to 10.2.2.2/80"],
vec![],
),
(
"CISCOFW302010",
vec!["5 in use, 10 most used"],
vec!["five in use, 10 most used"],
vec![],
),
(
"CISCOFW302013_302014_302015_302016",
vec![t302013, t302014, t302014_rst, &t302014_user, t302015],
vec![t302013_noid],
vec![],
),
(
"CISCOFW302020_302021",
vec![
"Built inbound ICMP connection for faddr 10.1.1.1/0 gaddr 10.2.2.2/0 laddr 10.2.2.2/0",
"Teardown ICMP connection for faddr 1.1.1.1/1 gaddr 2.2.2.2/0 laddr 3.3.3.3/0 (bob)",
],
vec!["Built inbound ICMP connection for faddr 10.1.1.1/0 gaddr 10.2.2.2/0"],
vec![],
),
(
"CISCOFW305011",
vec![
"Built dynamic TCP translation from inside:10.2.2.2/1234 to outside:192.0.2.1/5678",
"Built static TCP translation from inside:10.2.2.2 to outside:192.0.2.1/0",
],
vec![
"Built random TCP translation from inside:10.2.2.2/1234 to outside:192.0.2.1/5678",
],
vec![],
),
(
"CISCOFW313001_313004_313008",
vec![
"Denied ICMP type=8, code=0 from 10.1.1.1 on interface outside",
"Denied ICMP type=3, code=3 from 1.1.1.1 on interface outside to 2.2.2.2",
],
vec!["Denied ICMP type=8 from 10.1.1.1 on interface outside"],
vec![],
),
(
"CISCOFW313005",
vec![t313005, &t313005_one],
vec![&t313005_noport],
vec![],
),
(
"CISCOFW321001",
vec!["Resource 'conns' limit of 5000 reached for system"],
vec!["Resource conns limit of 5000 reached for system"],
vec![],
),
(
"CISCOFW402117",
vec!["IPSEC: Received a non-IPSec packet (protocol= TCP) from 10.1.1.1 to 10.2.2.2"],
vec!["IPSEC: Received a non-IPSec packet from 10.1.1.1 to 10.2.2.2"],
vec![],
),
(
"CISCOFW402119",
vec![
"IPSEC: Received an ESP packet (SPI= 0x1234, sequence number= 0x5) from 10.1.1.1 (user= bob) to 10.2.2.2 that failed anti-replay checking",
],
vec![
"IPSEC: Received an ESP packet (SPI= 0x1234, sequence number= 0x5) from 10.1.1.1 (user= bob) to 10.2.2.2",
],
vec![],
),
(
"CISCOFW419001",
vec![
"Dropping TCP packet from outside:1.1.1.1/1 to inside:2.2.2.2/80, reason: MSS exceeded, MSS 1380, data 1460",
],
vec!["Dropping TCP packet from outside:1.1.1.1/1 to inside:2.2.2.2/80"],
vec![],
),
(
"CISCOFW419002",
vec![
"Duplicate TCP SYN from outside:1.1.1.1/1 to inside:2.2.2.2/80 with different initial sequence number",
],
vec!["Duplicate TCP SYN from outside:1.1.1.1/1 to inside:2.2.2.2/80"],
vec![],
),
(
"CISCOFW500004",
vec!["Invalid transport field for protocol=TCP, from 1.1.1.1/0 to 2.2.2.2/80"],
vec!["Invalid transport field for protocol=TCP from 1.1.1.1/0 to 2.2.2.2/80"],
vec![],
),
(
"CISCOFW602303_602304",
vec![
"IPSEC: An outbound LAN-to-LAN SA (SPI= 0x1234) between 1.1.1.1 and 2.2.2.2 (user= bob) has been created",
"IPSEC: An inbound remote access SA (SPI= 0x1) between 1.1.1.1 and 2.2.2.2 (user= bob) has been deleted",
],
vec![
"IPSEC: An outbound LAN-to-LAN SA (SPI= 0x1234) between 1.1.1.1 and 2.2.2.2 (user= bob) has been renamed",
],
vec![],
),
(
"CISCOFW710001_710002_710003_710005_710006",
vec![
"TCP access requested from 10.1.1.1/1234 to inside:10.2.2.2/22",
"UDP request discarded from 10.1.1.1/53 to outside:10.2.2.2/53",
],
vec!["TCP access requested from 10.1.1.1/1234 to 10.2.2.2/22"],
vec![],
),
("CISCOFW713172", vec![t713172], vec![&t713172_cut], vec![]),
("CISCOFW733100", vec![t733100], vec![&t733100_cut], vec![]),
(
"SHOREWALL",
vec![&shorewall, &shorewall_icmp, &shorewall_egress],
vec![shorewall_cut, &shorewall_noprefix],
vec![],
),
(
"SFW2",
vec![&sfw2, &sfw2_uptime, &sfw2_iso, &sfw2_icmp],
vec![&sfw2_egress, sfw2_cut],
vec![],
),
];
assert_eq!(rows.len(), 82);
let mut differences = Vec::new();
let mut wrong = Vec::new();
for (name, hits, misses, probes) in &rows {
for line in hits {
if !accepts(&own, name, line) {
wrong.push(format!("{name} misses {line:?}"));
}
}
for line in misses {
if accepts(&own, name, line) {
wrong.push(format!("{name} matches {line:?}"));
}
}
for line in hits.iter().chain(misses).chain(probes) {
let Some(bundled) = &bundled else { continue };
let (new, old) = (accepts(&own, name, line), accepts(bundled, name, line));
if new != old {
differences.push(format!("{name} {line:?}: own {new}, bundled {old}"));
}
}
}
for d in &differences {
println!("DIFF {d}");
}
assert!(wrong.is_empty(), "{wrong:#?}");
let g = Grok::builder("grok:own")
.pattern("^%{SYSLOGPAMSESSION}$")
.build()
.unwrap();
let got = parse(&g, pam_open).expect("SYSLOGPAMSESSION reads its example");
for (field, value) in [
("pam_module", "pam_unix"),
("pam_caller", "sshd:session"),
("pam_session_state", "opened"),
("username", "root"),
("pam_by", "(uid=0)"),
(
"message",
"pam_unix(sshd:session): session opened for user root by (uid=0)",
),
] {
assert!(
got.iter().any(|(f, v, _)| f == field && v == value),
"{field} isn't {value:?} in {got:?}"
);
}
}
#[cfg(feature = "parse-backtracking")]
#[test]
#[allow(clippy::too_many_lines, reason = "one table of 165 definitions")]
fn product_file_definitions_hold_their_lines_and_report_where_the_bundled_ones_differ() {
use fancy_regex::Regex;
const BUNDLED: [&str; 16] = [
"bacula",
"bind",
"bro",
"exim",
"haproxy",
"junos",
"maven",
"mcollective",
"mcollective-patterns",
"mongodb",
"nagios",
"postgresql",
"rails",
"redis",
"ruby",
"squid",
];
let bundled = oracle(&BUNDLED);
let own = Library::default();
let accepts = |lib: &Library, name: &str, line: &str| {
let e = expand(&format!("^%{{{name}}}$"), lib, Dialect::Rust).unwrap();
Regex::new(&e.regex).is_ok_and(|re| re.is_match(line).unwrap_or(false))
};
let tabs = |cols: &[&str]| cols.join("\t");
let r = |name: &str, hits: &[&str], misses: &[&str]| {
(
name.to_owned(),
hits.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>(),
misses.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>(),
)
};
let conn_head = [
"1357000000.123",
"CHhAvVGS1DHFjwGM9",
"10.0.0.1",
"51234",
"192.0.2.5",
"80",
];
let with = |head: &[&str], tail: &[&str]| tabs(&[head, tail].concat());
let http = with(
&conn_head,
&[
"1",
"GET",
"example.com",
"/",
"-",
"curl/7.38.0",
"0",
"1256",
"200",
"OK",
"-",
"-",
"-",
"(empty)",
"-",
"-",
"-",
"-",
"-",
"FRxyz",
"text/html",
],
);
let dns = with(
&conn_head,
&[
"udp",
"4242",
"example.com",
"1",
"C_INTERNET",
"1",
"A",
"0",
"NOERROR",
"F",
"F",
"T",
"T",
"0",
"93.184.216.34",
"3600.000000",
"F",
],
);
let conn = with(
&conn_head,
&[
"tcp", "http", "0.5", "100", "1256", "SF", "-", "0", "ShADadFf", "6", "400", "5",
"1500", "(empty)",
],
);
let conn_unset = with(
&conn_head,
&[
"tcp", "-", "-", "-", "-", "S0", "-", "0", "S", "1", "60", "0", "0", "(empty)",
],
);
let files = with(
&["1357000000.123", "FRxyz"],
&[
"10.0.0.1,10.0.0.2",
"192.0.2.5",
"CHhAvVGS1DHFjwGM9",
"HTTP",
"0",
"MD5,SHA1",
"text/html",
"-",
"0.0",
"-",
"F",
"1256",
"1256",
"0",
"0",
"F",
"-",
"-",
"-",
"-",
"-",
],
);
let cut = |s: &str| s.rsplit_once('\t').unwrap().0.to_owned();
let hap_http = r#"10.0.1.2:33317 [06/Feb/2009:12:14:14.655] http-in static/srv1 10/0/30/69/109 200 2750 - - ---- 1/1/1/1/0 0/0 {1wt.eu} {} "GET /index.html HTTP/1.1""#;
let hap_syslog = format!("Feb 6 12:14:14 localhost haproxy[14389]: {hap_http}");
let hap_iso = format!("2009-02-06T12:14:14+00:00 localhost haproxy[14389]: {hap_http}");
let hap_bad = hap_http.replace("\"GET /index.html HTTP/1.1\"", "\"<BADREQ>\"");
let hap_cookie = hap_http.replace(" - - ---- ", " SRV=1 - ---- ");
let hap_nostatus = hap_http.replace(" 200 2750", "");
let hap_tcp_base =
"10.0.1.2:33313 [06/Feb/2009:12:12:51.443] fnt bck/srv1 0/0/5007 212 -- 0/0/0/0/3 0/0";
let hap_tcp = format!("Feb 6 12:12:56 localhost haproxy[14387]: {hap_tcp_base}");
let hap_tcp_cut = hap_tcp.rsplit_once(' ').unwrap().0.to_owned();
let exim_head = "2002-10-31 08:57:53 16ZCW1-0005MB-00 <=";
let exim_arrival = format!(
"{exim_head} kryten@dwarf.fict.example H=mailer.fict.example (helo.example) [192.168.123.123]:25 U=exim P=smtp S=5678 id=abc@dwarf.fict.example"
);
let exim_pid = "2002-10-31 08:57:53 [1234] 16ZCW1-0005MB-00 <= ab@cd.example P=local S=10 for ef@gh.example";
let exim_bounce = format!("{exim_head} <> R=16ZCW1-0005MB-00 U=mail P=local S=1234");
let exim_long = "2002-10-31 08:57:53 1ZCW1a-0005MBabcde-0001 <= ab@cd.example P=local S=10";
let exim_delivery =
"2002-10-31 08:57:53 16ZCW1-0005MB-00 => a@b.example R=dnslookup T=remote_smtp";
let junos_close = "RT_FLOW_SESSION_CLOSE: session closed TCP FIN: 10.1.1.1/54321->192.0.2.5/80 junos-http 203.0.113.1/54321->192.0.2.5/80 source-nat-rule None 6 allow-web trust untrust 1234567 12(1234) 10(4321) 30 UNKNOWN UNKNOWN N/A(N/A) ge-0/0/1.0 UNKNOWN";
let junos_create = "RT_FLOW_SESSION_CREATE: session created 10.1.1.1/54321->192.0.2.5/80 junos-http 203.0.113.1/54321->192.0.2.5/80 source-nat-rule None 6 allow-web trust untrust 1234567 N/A(N/A) ge-0/0/1.0 UNKNOWN";
let junos_deny = "RT_FLOW_SESSION_DENY: session denied 10.1.1.1/54321->192.0.2.5/22 junos-ssh 6(0) deny-all trust untrust UNKNOWN UNKNOWN N/A(N/A) ge-0/0/1.0";
let junos_deny_icmp = junos_deny.replace("6(0)", "1(8)");
let mongo_slow = "query test.foo query: { a: 1 } ntoreturn:0 ntoskip:0 nscanned:10 keyUpdates:0 numYields: 0 locks(micros) r:1234 nreturned:1 reslen:50 5ms";
let mongo3 = "2016-01-12T10:00:00.123+0000 I NETWORK [initandlisten] waiting for connections on port 27017";
let rails_head = r#"Started GET "/users/1?x=2" for 127.0.0.1 at 2012-01-01 10:00:00 +0000"#;
let rails_full = format!(
"{rails_head}\nProcessing by UsersController#show as HTML\n Parameters: {{\"id\"=>\"1\"}}\n Rendered users/show.html.erb (1.0ms)\nCompleted 200 OK in 15ms (Views: 10.5ms | ActiveRecord: 2.0ms)"
);
let squid = "1157689312.049 5006 10.105.165.40 TCP_MISS/200 4087 GET http://www.example.com/x - DIRECT/93.184.216.34 text/html";
let squid_host = squid.replace("10.105.165.40", "proxy.example.com");
let squid_cut = squid.rsplit_once(' ').unwrap().0.to_owned();
let mut rows = vec![
r(
"BACULA_TIMESTAMP",
&["09-Jan 14:05"],
&["Jan 09 14:05", "09-Jan"],
),
r("BACULA_HOST", &["backup-dir", "bacula-fd1"], &["a b", ""]),
r("BACULA_VOLUME", &["Vol-0001", "Full.0001"], &["a b"]),
r("BACULA_DEVICE", &["FileStorage", "Drive-1"], &["a b"]),
r("BACULA_DEVICEPATH", &["/var/bacula/storage"], &["storage"]),
r(
"BACULA_CAPACITY",
&["0", "1,234,567", "12345"],
&["1,23", ",123", "a"],
),
r("BACULA_VERSION", &["5.2.13"], &["5 2"]),
r(
"BACULA_JOB",
&["BackupClient1.2013-01-09_14.05.00_03"],
&["a b"],
),
r(
"BACULA_LOG_MAX_CAPACITY",
&[
r#"User defined maximum volume capacity 1,000,000 exceeded on device "FileStorage" (/var/bacula)"#,
],
&[
r#"User defined maximum volume capacity exceeded on device "FileStorage" (/var/bacula)"#,
],
),
r(
"BACULA_LOG_END_VOLUME",
&[r#"End of medium on Volume "Vol-0001" Bytes=1,234 Blocks=5 at 09-Jan-2013 14:05."#],
&[r#"End of medium on Volume "Vol-0001" Bytes=1,234 Blocks=5 at 09-Jan 14:05."#],
),
r(
"BACULA_LOG_NEW_VOLUME",
&[r#"Created new Volume "Vol-0001" in catalog."#],
&[r"Created new Volume Vol-0001 in catalog."],
),
r(
"BACULA_LOG_NEW_LABEL",
&[r#"Labeled new Volume "Vol-0001" on device "Drive-1" (/dev/nst0)."#],
&[r#"Labeled new Volume "Vol-0001" on device "Drive-1""#],
),
r(
"BACULA_LOG_WROTE_LABEL",
&[r#"Wrote label to prelabeled Volume "Vol-0001" on device "Drive-1" (/dev/nst0)"#],
&[r#"Wrote label to Volume "Vol-0001" on device "Drive-1" (/dev/nst0)"#],
),
r(
"BACULA_LOG_NEW_MOUNT",
&[
r#"New volume "Vol-0001" mounted on device "Drive-1" (/dev/nst0) at 09-Jan-2013 14:05."#,
],
&[r#"New volume "Vol-0001" mounted on device "Drive-1" (/dev/nst0)"#],
),
r(
"BACULA_LOG_VOLUME_PREVWRITTEN",
&[r#"Volume "Vol-0001" previously written, moving to end of data."#],
&[r#"Volume "Vol-0001" written, moving to end of data."#],
),
r(
"BACULA_LOG_READYAPPEND",
&[r#"Ready to append to end of Volume "Vol-0001" size=1234"#],
&[r#"Ready to append to end of Volume "Vol-0001""#],
),
r(
"BACULA_LOG_USEDEVICE",
&[r#"Using Device "Drive-1""#],
&["Using Device Drive-1"],
),
r(
"BACULA_LOG_NOOPEN",
&[
"Cannot open /etc/shadow: ERR=Permission denied",
" Cannot open \"/x\": ERR=No such file",
],
&["Cannot open /etc/shadow"],
),
r(
"BACULA_LOG_NOOPENDIR",
&["Could not open directory /root: ERR=Permission denied"],
&["Could not open directory /root"],
),
r(
"BACULA_LOG_NOSTAT",
&["Could not stat /proc/1/fd: ERR=No such file"],
&["Could not stat /proc/1/fd"],
),
r(
"BACULA_LOG_DIFF_FS",
&[" /mnt/usb is a different filesystem. Will not descend from / into it."],
&["/mnt/usb is a different filesystem."],
),
r(
"BACULA_LOG_NOJOBS",
&[r#"There are no more Jobs associated with Volume "Vol-0001". Marking it purged."#],
&[r#"There are no more Jobs associated with Volume "Vol-0001"."#],
),
r(
"BACULA_LOG_ALL_RECORDS_PRUNED",
&[r#"All records pruned from Volume "Vol-0001"; marking it "Purged""#],
&[r#"All records pruned from Volume "Vol-0001""#],
),
r(
"BACULA_LOG_BEGIN_PRUNE_JOBS",
&[
"Begin pruning Jobs older than 6 months .",
"Begin pruning Jobs older than 1 month 5 days .",
],
&["Begin pruning Jobs older than ."],
),
r(
"BACULA_LOG_BEGIN_PRUNE_FILES",
&["Begin pruning Files."],
&["Begin pruning Jobs."],
),
r(
"BACULA_LOG_PRUNED_JOBS",
&[
"Pruned 2 Jobs for client web-fd from catalog.",
"Pruned 1 Job for client web-fd from catalog.",
],
&["Pruned Jobs for client web-fd from catalog."],
),
r(
"BACULA_LOG_PRUNED_FILES",
&["Pruned Files from 2 Jobs for client web-fd from catalog."],
&["Pruned Files from Jobs for client web-fd from catalog."],
),
r("BACULA_LOG_ENDPRUNE", &["End auto prune."], &["End prune."]),
r(
"BACULA_LOG_NOPRUNE_JOBS",
&["No Jobs found to prune."],
&["No Files found to prune."],
),
r(
"BACULA_LOG_NOPRUNE_FILES",
&["No Files found to prune."],
&["No Jobs found to prune."],
),
r(
"BACULA_LOG_STARTJOB",
&["Start Backup JobId 123, Job=BackupClient1.2013-01-09_14.05.00_03"],
&["Start Backup JobId 123"],
),
r(
"BACULA_LOG_STARTRESTORE",
&["Start Restore Job RestoreFiles.2013-01-09_14.05.00_03"],
&["Start Restore"],
),
r(
"BACULA_LOG_JOBEND",
&[
"Job write elapsed time = 00:01:02, Transfer rate = 7.35 M Bytes/second",
"Job write elapsed time = 00:00:01, Transfer rate = 0 Bytes/second",
],
&["Job write elapsed time = 00:01:02"],
),
r(
"BACULA_LOG_CANCELLING",
&["Cancelling duplicate JobId=12."],
&["Cancelling duplicate JobId=."],
),
r(
"BACULA_LOG_MARKCANCEL",
&["JobId 12, Job BackupClient1.2013-01-09_14.05.00_03 marked to be canceled."],
&["JobId 12, Job x"],
),
r(
"BACULA_LOG_CLIENT_RBJ",
&[r#"shell command: run ClientRunBeforeJob "/bin/true""#],
&["shell command: run ClientRunBeforeJob /bin/true"],
),
r(
"BACULA_LOG_VSS",
&["VSS ", "Generate VSS Writer", "VSS Writer"],
&["XVSS "],
),
r(
"BACULA_LOG_NOSUIT",
&["No prior or suitable Full backup found in catalog. Doing FULL backup."],
&["No prior Full backup found in catalog. Doing FULL backup."],
),
r(
"BACULA_LOG_NOPRIOR",
&["No prior Full backup Job record found."],
&["No Full backup Job record found."],
),
r(
"BACULA_LOG_MAXSTART",
&["Fatal error: Job canceled because max start delay time exceeded."],
&["Job canceled because max start delay time exceeded."],
),
r(
"BACULA_LOG_DUPLICATE",
&["Fatal error: JobId 12 already running. Duplicate job not allowed."],
&["Fatal error: JobId already running. Duplicate job not allowed."],
),
r(
"BACULA_LOG_NOJOBSTAT",
&["Fatal error: No Job status returned from FD."],
&["Fatal error: No Job status returned."],
),
r(
"BACULA_LOG_FATAL_CONN",
&[
"Fatal error: bsock.c:133 Unable to connect to Client: web-fd on web.example.com:9102. ERR=Connection refused",
"Fatal error: bsock.c:127 Unable to connect to Storage daemon on sd.example.com:9103. ERR=timed out",
],
&[
"Fatal error: bsock.c:133 Unable to connect to Client: web-fd on web.example.com. ERR=x",
],
),
r(
"BACULA_LOG_NO_CONNECT",
&[
"Warning: bsock.c:127 Could not connect to Client: web-fd on web.example.com:9102. ERR=Connection refused",
],
&["Warning: bsock.c:127 Could not connect to Client: web-fd. ERR=x"],
),
r(
"BACULA_LOG_NO_AUTH",
&[
"Fatal error: Unable to authenticate with File daemon at web.example.com. Possible causes:",
],
&["Fatal error: Unable to authenticate with File daemon at web.example.com."],
),
r(
"BACULA_LOG_JOB",
&[
"Bacula backup-dir 5.2.13 (19Jan13):",
"Error: Bacula backup-dir 5.2.13 (19Jan13):",
],
&["Bacula backup-dir 5.2.13"],
),
r(
"BACULA_LOGLINE",
&[
"09-Jan 14:05 backup-dir JobId 12: Start Backup JobId 12, Job=BackupClient1.2013-01-09_14.05.00_03",
"09-Jan 14:05 backup-sd: Using Device \"Drive-1\"",
"09-Jan 14:05 backup-dir JobId 12: Pruned 2 Jobs for client web-fd from catalog.",
],
&[
"09-Jan 14:05 backup-dir JobId 12: Something else entirely",
"backup-dir JobId 12: End auto prune.",
],
),
r(
"BIND9_TIMESTAMP",
&["28-Jul-2022 10:15:12.123"],
&["2022-07-28 10:15:12"],
),
r(
"BIND9",
&[
"28-Jul-2022 10:15:12.123 queries: info: client 192.0.2.1#53412 (example.com): query: example.com IN A + (192.0.2.53)",
"28-Jul-2022 10:15:12.123 queries: info: client @0x7f1234 192.0.2.1#53412 (example.com): query: example.com IN AAAA +E(0) (192.0.2.53)",
"28-Jul-2022 10:15:12.123 queries: info: client 192.0.2.1#53412 (example.com): view internal: query: example.com IN A + (192.0.2.53)",
],
&[
"28-Jul-2022 10:15:12.123 queries: info: client 192.0.2.1#53412 (example.com): query: example.com IN A +",
"28-Jul-2022 10:15:12.123 security: info: client 192.0.2.1#53412 (example.com): query: example.com IN A + (192.0.2.53)",
],
),
r(
"BRO_HTTP",
&[&http],
&[&cut(&http), &http.replace('\t', " ")],
),
r("BRO_DNS", &[&dns], &[&cut(&dns)]),
r("BRO_CONN", &[&conn, &conn_unset], &[&cut(&conn)]),
r("BRO_FILES", &[&files], &[&cut(&files)]),
r(
"EXIM_MSGID",
&["16ZCW1-0005MB-00", "1ZCW1a-0005MBabcde-0001"],
&["16ZCW1-0005MB", "16ZCW1_0005MB_00"],
),
r(
"EXIM_FLAGS",
&["<=", "=>", "->", ">>", "*>", "**", "==", "(="],
&["<>", "=", "<<"],
),
r(
"EXIM_DATE",
&["2002-10-31 08:57:53"],
&["31/10/2002 08:57:53"],
),
r("EXIM_PID", &["[1234]"], &["[abc]", "1234"]),
r("EXIM_QT", &["3s", "1h2m3s", "2w1d"], &["1x", "s3"]),
r(
"EXIM_EXCLUDE_TERMS",
&[
"Message is frozen",
"Start queue run",
"End queue run",
" Warning: ",
" retry time not reached ",
" no IP address found for host ",
"another process is handling this message",
],
&["queue running", "Message is thawed"],
),
r(
"EXIM_REMOTE_HOST",
&[
"H=[192.0.2.1]",
"H=mail.example.org [192.0.2.1]:25",
"H=mail.example.org (helo.example.org) [192.0.2.1]:25",
],
&["H=[]", "H=mail.example.org", "[192.0.2.1]"],
),
r(
"EXIM_INTERFACE",
&["I=[192.0.2.9]:25"],
&["I=[192.0.2.9]", "I=192.0.2.9:25"],
),
r("EXIM_PROTOCOL", &["P=esmtpsa"], &["P=", "esmtp"]),
r("EXIM_MSG_SIZE", &["S=5678"], &["S=", "S=big"]),
r("EXIM_HEADER_ID", &["id=abc@host.example"], &["id=", "id"]),
r("EXIM_SUBJECT", &[r#"T="hello there""#], &["T=hello"]),
r(
"EXIM_UNKNOWN_FIELD",
&["U=exim", "QT=3s", "DN=x"],
&["U=", "toolong=1"],
),
r(
"EXIM_NAMED_FIELDS",
&[" H=[192.0.2.1] P=smtp S=10", "", " U=exim QT=3s"],
&["H=[192.0.2.1]"],
),
r(
"EXIM_MESSAGE_ARRIVAL",
&[&exim_arrival, exim_pid, &exim_bounce, exim_long],
&[exim_delivery, "2002-10-31 08:57:53 16ZCW1-0005MB-00 <= "],
),
r("EXIM", &[&exim_arrival, &exim_bounce], &[exim_delivery]),
r(
"HAPROXYTIME",
&["12:14:14", "07:01:02"],
&["12:14", "12:14:99"],
),
r(
"HAPROXYDATE",
&["06/Feb/2009:12:14:14.655"],
&["06/Feb/2009:12:14:14", "06-Feb-2009:12:14:14.655"],
),
r(
"HAPROXYCAPTUREDREQUESTHEADERS",
&["1wt.eu", "Host|Agent", ""],
&["a}b"],
),
r(
"HAPROXYCAPTUREDRESPONSEHEADERS",
&["text/html|gzip", ""],
&["a}b"],
),
r(
"HAPROXYHTTPBASE",
&[hap_http, &hap_bad, &hap_cookie],
&[
&hap_nostatus,
"10.0.1.2:33317 [06/Feb/2009:12:14:14.655] http-in",
],
),
r(
"HAPROXYHTTP",
&[&hap_syslog, &hap_iso],
&[
hap_http,
&hap_syslog.replace("haproxy[14389]:", "haproxy[14389]"),
],
),
r("HAPROXYTCP", &[&hap_tcp], &[&hap_tcp_cut, hap_tcp_base]),
r(
"RT_FLOW_EVENT",
&[
"RT_FLOW_SESSION_CREATE",
"RT_FLOW_SESSION_CLOSE",
"RT_FLOW_SESSION_DENY",
],
&["RT_FLOW_SESSION_OPEN", "rt_flow_session_close"],
),
r(
"RT_FLOW1",
&[junos_close],
&[
"RT_FLOW_SESSION_CLOSE: session closed TCP FIN: 10.1.1.1/54321->192.0.2.5/80 junos-http",
junos_create,
],
),
r("RT_FLOW2", &[junos_create], &[junos_close, junos_deny]),
r(
"RT_FLOW3",
&[junos_deny, &junos_deny_icmp],
&[
junos_create,
"RT_FLOW_SESSION_DENY: session denied 10.1.1.1/54321->192.0.2.5/22 junos-ssh 6 deny-all trust untrust x",
],
),
r(
"MAVEN_VERSION",
&["1.2.3", "1.0-SNAPSHOT", "2.*", "3", "1.2.3-RELEASE"],
&["abc", "1.2.3.4", "1.0-alpha"],
),
r(
"MCOLLECTIVEAUDIT",
&["2012-01-01T10:00:00.123:", "2012-01-01 10:00:00:"],
&["2012-01-01T10:00:00.123", "audit:"],
),
r(
"MCOLLECTIVE",
&[
"I, [2012-01-01T10:00:00.123456 #1234] INFO",
"E, [2012-01-01T10:00:00.123456 #1]ERROR",
],
&[
"Q, [2012-01-01T10:00:00.123456 #1234] INFO",
"I, [2012-01-01T10:00:00 #x] INFO",
],
),
r(
"MONGO_LOG",
&[
"Jan 3 12:00:00.123 [initandlisten] db version v2.4.1",
"Mar 21 15:06:24 [conn5] end connection",
],
&[
"Thu Jan 3 12:00:00.123 [initandlisten] x",
"Jan 3 12:00:00.123 initandlisten x",
],
),
r("MONGO_WORDDASH", &["my-db_1", "users"], &["a.b", "a b", ""]),
r(
"MONGO_QUERY",
&["{ a: 1 }", "{ a: { b: 1 } }"],
&["a: 1", "{a: 1}"],
),
r(
"MONGO_SLOWQUERY",
&[mongo_slow],
&[
"query test.foo query: { a: 1 } ntoreturn:0 ntoskip:0 nscanned:10 nreturned:1 reslen:50",
"query foo query: { a: 1 } ntoreturn:0 ntoskip:0 nscanned:10 nreturned:1 reslen:50 5ms",
],
),
r("MONGO3_SEVERITY", &["I", "F", "D"], &["X", "II", "i"]),
r(
"MONGO3_COMPONENT",
&["NETWORK", "-", "STORAGE"],
&["a b", ""],
),
r(
"MONGO3_LOG",
&[
mongo3,
"2016-01-12T10:00:00.123+0000 W - [conn3] slow thing",
"2016-01-12T10:00:00.123+0000 I COMMAND msg without context",
],
&["garbage", "2016-01-12T10:00:00.123+0000 I"],
),
r(
"NAGIOSTIME",
&["[1357000000]", "[1357000000.5]"],
&["[abc]", "1357000000"],
),
r(
"NAGIOS_WARNING",
&[
"Warning: Return code of 127 for check of host 'web01' was out of bounds.",
"Warning:x",
],
&["Warn: x", "warning: x"],
),
r(
"NAGIOS_CURRENT_SERVICE_STATE",
&["CURRENT SERVICE STATE: web01;HTTP;OK;HARD;1;HTTP OK: 200"],
&[
"CURRENT SERVICE STATE: web01;HTTP;OK;HARD;1",
"CURRENT HOST STATE: web01;UP;HARD;1;ok",
],
),
r(
"NAGIOS_CURRENT_HOST_STATE",
&["CURRENT HOST STATE: web01;UP;HARD;1;PING OK"],
&["CURRENT HOST STATE: web01;UP;HARD"],
),
r(
"NAGIOS_SERVICE_NOTIFICATION",
&[
"SERVICE NOTIFICATION: ops;web01;HTTP;CRITICAL;notify-service-by-email;Connection refused",
],
&["SERVICE NOTIFICATION: ops;web01;HTTP;CRITICAL"],
),
r(
"NAGIOS_HOST_NOTIFICATION",
&["HOST NOTIFICATION: ops;web01;DOWN;notify-host-by-email;PING CRITICAL"],
&["HOST NOTIFICATION: ops;web01;DOWN"],
),
r(
"NAGIOS_SERVICE_ALERT",
&["SERVICE ALERT: web01;HTTP;CRITICAL;SOFT;1;Connection refused"],
&[
"SERVICE ALERT: web01;HTTP;CRITICAL;SOFT;x;msg",
"SERVICE ALERT: web01;HTTP;CRITICAL",
],
),
r(
"NAGIOS_HOST_ALERT",
&["HOST ALERT: web01;DOWN;HARD;3;CRITICAL - Host Unreachable"],
&["HOST ALERT: web01;DOWN;HARD;x;msg"],
),
r(
"NAGIOS_SERVICE_FLAPPING_ALERT",
&[
"SERVICE FLAPPING ALERT: web01;HTTP;STARTED; Service appears to have started flapping (21.5% change >= 20.0% threshold)",
],
&["SERVICE FLAPPING ALERT: web01;HTTP"],
),
r(
"NAGIOS_HOST_FLAPPING_ALERT",
&["HOST FLAPPING ALERT: web01;STOPPED; Host appears to have stopped flapping"],
&["HOST FLAPPING ALERT: web01"],
),
r(
"NAGIOS_SERVICE_DOWNTIME_ALERT",
&[
"SERVICE DOWNTIME ALERT: web01;HTTP;STARTED; Service has entered a period of scheduled downtime",
],
&["SERVICE DOWNTIME ALERT: web01;HTTP"],
),
r(
"NAGIOS_HOST_DOWNTIME_ALERT",
&[
"HOST DOWNTIME ALERT: web01;STARTED; Host has entered a period of scheduled downtime",
],
&["HOST DOWNTIME ALERT: web01"],
),
r(
"NAGIOS_PASSIVE_SERVICE_CHECK",
&["PASSIVE SERVICE CHECK: web01;HTTP;0;OK"],
&["PASSIVE SERVICE CHECK: web01;HTTP"],
),
r(
"NAGIOS_PASSIVE_HOST_CHECK",
&["PASSIVE HOST CHECK: web01;0;UP"],
&["PASSIVE HOST CHECK: web01"],
),
r(
"NAGIOS_SERVICE_EVENT_HANDLER",
&["SERVICE EVENT HANDLER: web01;HTTP;CRITICAL;SOFT;restart-httpd"],
&[
"SERVICE EVENT HANDLER: web01;HTTP;CRITICAL;SOFT;restart;extra",
"SERVICE EVENT HANDLER: web01;HTTP",
],
),
r(
"NAGIOS_HOST_EVENT_HANDLER",
&["HOST EVENT HANDLER: web01;DOWN;HARD;restart-host"],
&[
"HOST EVENT HANDLER: web01;DOWN;HARD;restart;extra",
"HOST EVENT HANDLER: web01;DOWN",
],
),
r(
"NAGIOS_TIMEPERIOD_TRANSITION",
&["TIMEPERIOD TRANSITION: 24x7;-1;1"],
&["TIMEPERIOD TRANSITION: 24x7;a;1"],
),
r(
"NAGIOS_EC_LINE_DISABLE_SVC_CHECK",
&["EXTERNAL COMMAND: DISABLE_SVC_CHECK;web01;HTTP"],
&[
"EXTERNAL COMMAND: DISABLE_SVC_CHECK;web01",
"EXTERNAL COMMAND: ENABLE_SVC_CHECK;web01;HTTP",
],
),
r(
"NAGIOS_EC_LINE_DISABLE_HOST_CHECK",
&["EXTERNAL COMMAND: DISABLE_HOST_CHECK;web01"],
&[
"EXTERNAL COMMAND: DISABLE_HOST_CHECK;web01;extra",
"EXTERNAL COMMAND: DISABLE_HOST_CHECK",
],
),
r(
"NAGIOS_EC_LINE_ENABLE_SVC_CHECK",
&["EXTERNAL COMMAND: ENABLE_SVC_CHECK;web01;HTTP"],
&["EXTERNAL COMMAND: ENABLE_SVC_CHECK;web01"],
),
r(
"NAGIOS_EC_LINE_ENABLE_HOST_CHECK",
&["EXTERNAL COMMAND: ENABLE_HOST_CHECK;web01"],
&["EXTERNAL COMMAND: ENABLE_HOST_CHECK;web01;extra"],
),
r(
"NAGIOS_EC_LINE_PROCESS_SERVICE_CHECK_RESULT",
&["EXTERNAL COMMAND: PROCESS_SERVICE_CHECK_RESULT;web01;HTTP;0;OK - fine"],
&["EXTERNAL COMMAND: PROCESS_SERVICE_CHECK_RESULT;web01;HTTP"],
),
r(
"NAGIOS_EC_LINE_PROCESS_HOST_CHECK_RESULT",
&["EXTERNAL COMMAND: PROCESS_HOST_CHECK_RESULT;web01;0;UP - fine"],
&["EXTERNAL COMMAND: PROCESS_HOST_CHECK_RESULT;web01"],
),
r(
"NAGIOS_EC_LINE_DISABLE_HOST_SVC_NOTIFICATIONS",
&["EXTERNAL COMMAND: DISABLE_HOST_SVC_NOTIFICATIONS;web01"],
&["EXTERNAL COMMAND: DISABLE_HOST_SVC_NOTIFICATIONS"],
),
r(
"NAGIOS_EC_LINE_DISABLE_HOST_NOTIFICATIONS",
&["EXTERNAL COMMAND: DISABLE_HOST_NOTIFICATIONS;web01"],
&["EXTERNAL COMMAND: DISABLE_HOST_NOTIFICATIONS"],
),
r(
"NAGIOS_EC_LINE_DISABLE_SVC_NOTIFICATIONS",
&["EXTERNAL COMMAND: DISABLE_SVC_NOTIFICATIONS;web01;HTTP"],
&["EXTERNAL COMMAND: DISABLE_SVC_NOTIFICATIONS;web01"],
),
r(
"NAGIOS_EC_LINE_ENABLE_HOST_SVC_NOTIFICATIONS",
&["EXTERNAL COMMAND: ENABLE_HOST_SVC_NOTIFICATIONS;web01"],
&["EXTERNAL COMMAND: ENABLE_HOST_SVC_NOTIFICATIONS"],
),
r(
"NAGIOS_EC_LINE_ENABLE_HOST_NOTIFICATIONS",
&["EXTERNAL COMMAND: ENABLE_HOST_NOTIFICATIONS;web01"],
&["EXTERNAL COMMAND: ENABLE_HOST_NOTIFICATIONS"],
),
r(
"NAGIOS_EC_LINE_ENABLE_SVC_NOTIFICATIONS",
&["EXTERNAL COMMAND: ENABLE_SVC_NOTIFICATIONS;web01;HTTP"],
&["EXTERNAL COMMAND: ENABLE_SVC_NOTIFICATIONS;web01"],
),
r(
"NAGIOS_EC_LINE_SCHEDULE_HOST_DOWNTIME",
&[
"EXTERNAL COMMAND: SCHEDULE_HOST_DOWNTIME;web01;1357000000;1357003600;1;0;3600;ops;patching",
],
&[
"EXTERNAL COMMAND: SCHEDULE_HOST_DOWNTIME;web01;1357000000;1357003600;1;0;3600;ops",
"EXTERNAL COMMAND: SCHEDULE_HOST_DOWNTIME;web01;a;b;1;0;3600;ops;x",
],
),
r(
"NAGIOSLOGLINE",
&[
"[1357000000] SERVICE ALERT: web01;HTTP;CRITICAL;SOFT;1;Connection refused",
"[1357000000] Warning: something",
"[1357000000] EXTERNAL COMMAND: ENABLE_HOST_CHECK;web01",
"[1357000000] TIMEPERIOD TRANSITION: 24x7;-1;1",
],
&[
"1357000000 SERVICE ALERT: web01;HTTP;CRITICAL;SOFT;1;msg",
"[1357000000] UNKNOWN ENTRY: a;b",
],
),
r(
"POSTGRESQL",
&[
"2013-01-09 12:00:00.123 UTC [1234]",
"2013-01-09 12:00:00 AEDT [77]",
"01/09/2013 12:00:00 UTC alice 50e0f3a2.1a2b 4321",
],
&["2013-01-09 12:00:00.123 UTC 1234", "garbage"],
),
r(
"RUUID",
&["0123456789abcdef0123456789ABCDEF"],
&[
"0123456789abcdef0123456789ABCDE",
"0123456789abcdef0123456789ABCDEG",
],
),
r(
"RCONTROLLER",
&["UsersController#show", "Admin::UsersController#index"],
&["NoHash", "#show"],
),
r(
"RAILS3HEAD",
&[
rails_head,
r#"Started POST "/login" for 10.0.0.1 at 2012-01-01 10:00:00 -0700"#,
],
&[
r#"Started "/" for 127.0.0.1 at 2012-01-01 10:00:00 +0000"#,
r#"Started GET "/" for 127.0.0.1 at 2012-01-01 10:00:00"#,
],
),
r(
"RPROCESSING",
&[
"Processing by UsersController#show as HTML",
"Processing by UsersController#show as JSON\n Parameters: {\"id\"=>\"1\"}",
],
&[
"Processing UsersController#show as HTML",
"Processing by UsersController as HTML",
],
),
r(
"RAILS3PROFILE",
&[
"(Views: 1.0ms | ActiveRecord: 2.0ms",
"(ActiveRecord: 2.0ms",
"(Views: 3.0ms",
"",
],
&["(Views", "Views: 1.0ms"],
),
r(
"RAILS3FOOT",
&[
"Completed 200 OK in 15ms (Views: 10.5ms | ActiveRecord: 2.0ms)",
"Completed 302 Found in 5ms",
"Completed 200 OK in 4ms (Views: 3.0ms)",
"Completed 200 OK in 4ms (Views: 3.0ms | ActiveRecord: 1.0ms | Allocations: 1234)",
],
&["Completed in 15ms", "Finished 200 OK in 15ms"],
),
r(
"RAILS3",
&[&rails_full, rails_head],
&["Processing by UsersController#show as HTML"],
),
r(
"REDISTIMESTAMP",
&["14 Nov 07:01:22.119", "4 Nov 07:01:22"],
&["Nov 14 07:01:22", "14 November"],
),
r(
"REDISLOG",
&[
"[4018] 14 Nov 07:01:22.119 * ",
"1234:M 14 Nov 07:01:22.119 # ",
"1234:S 14 Nov 07:01:22.119 - ",
],
&[
"[4018] 14 Nov 07:01:22.119 ? ",
"[4018] 14 Nov 07:01:22.119 *",
],
),
r(
"REDISMONLOG",
&[
r#"1339518083.107412 [0 127.0.0.1:60866] "keys" "*""#,
r#"1339518083.107412 [0 127.0.0.1:60866] "ping""#,
],
&[
r#"1339518083.107412 [0 lua] "get" "x""#,
"1339518083.107412 [0 127.0.0.1:60866] keys",
],
),
r(
"RUBY_LOGLEVEL",
&["DEBUG", "FATAL", "ERROR", "WARN", "INFO", "ANY"],
&["TRACE", "info"],
),
r(
"RUBY_LOGGER",
&[
"I, [2012-01-01T10:00:00.123456 #1234] INFO -- app: started",
"E, [2012-01-01T10:00:00.123456 #1234] ERROR -- : boom",
"A, [2012-01-01T10:00:00.123456 #1] ANY -- x: y",
],
&[
"X, [2012-01-01T10:00:00.123456 #1234] INFO -- app: started",
"I, [2012-01-01T10:00:00.123456 #1234] INFO app: started",
],
),
r(
"SQUID3",
&[
squid,
&squid_host,
"1157689312.049 5 10.0.0.1 TCP_DENIED/403 3652 GET http://x.example/ alice NONE/- text/html",
],
&[&squid_cut, "garbage"],
),
];
for t in [
"CURRENT_SERVICE_STATE",
"CURRENT_HOST_STATE",
"SERVICE_NOTIFICATION",
"HOST_NOTIFICATION",
"SERVICE_ALERT",
"HOST_ALERT",
"SERVICE_FLAPPING_ALERT",
"HOST_FLAPPING_ALERT",
"SERVICE_DOWNTIME_ALERT",
"HOST_DOWNTIME_ALERT",
"PASSIVE_SERVICE_CHECK",
"PASSIVE_HOST_CHECK",
"SERVICE_EVENT_HANDLER",
"HOST_EVENT_HANDLER",
"EXTERNAL_COMMAND",
"TIMEPERIOD_TRANSITION",
] {
let hit = t.replace('_', " ");
let miss = hit.to_lowercase();
rows.push(r(
&format!("NAGIOS_TYPE_{t}"),
&[&hit],
&[&miss, "OTHER TYPE"],
));
}
for c in [
"DISABLE_SVC_CHECK",
"ENABLE_SVC_CHECK",
"DISABLE_HOST_CHECK",
"ENABLE_HOST_CHECK",
"PROCESS_SERVICE_CHECK_RESULT",
"PROCESS_HOST_CHECK_RESULT",
"SCHEDULE_SERVICE_DOWNTIME",
"SCHEDULE_HOST_DOWNTIME",
"DISABLE_HOST_SVC_NOTIFICATIONS",
"ENABLE_HOST_SVC_NOTIFICATIONS",
"DISABLE_HOST_NOTIFICATIONS",
"ENABLE_HOST_NOTIFICATIONS",
"DISABLE_SVC_NOTIFICATIONS",
"ENABLE_SVC_NOTIFICATIONS",
] {
rows.push(r(
&format!("NAGIOS_EC_{c}"),
&[c],
&[&c.to_lowercase(), "OTHER_COMMAND"],
));
}
let own_files: Vec<String> = BUNDLED
.iter()
.map(|n| {
std::fs::read_to_string(format!(
"{}/src/grok/patterns/{n}",
env!("CARGO_MANIFEST_DIR")
))
.unwrap_or_default()
})
.collect();
let mut expected: Vec<&str> = own_files
.iter()
.flat_map(|f| f.lines())
.filter(|l| !l.trim().is_empty() && !l.trim_start().starts_with('#'))
.filter_map(|l| l.split_whitespace().next())
.collect();
expected.sort_unstable();
expected.dedup();
let mut covered: Vec<&str> = rows.iter().map(|(n, _, _)| n.as_str()).collect();
covered.sort_unstable();
assert_eq!(
covered, expected,
"a bundled name has no row, or a row is repeated"
);
let mut differences = Vec::new();
let mut wrong = Vec::new();
for (name, hits, misses) in &rows {
for line in hits {
if !accepts(&own, name, line) {
wrong.push(format!("{name} misses {line:?}"));
}
}
for line in misses {
if accepts(&own, name, line) {
wrong.push(format!("{name} matches {line:?}"));
}
}
for line in hits.iter().chain(misses) {
let Some(bundled) = &bundled else { continue };
let (new, old) = (accepts(&own, name, line), accepts(bundled, name, line));
if new != old {
differences.push(format!("{name} {line:?}: own {new}, bundled {old}"));
}
}
}
for d in &differences {
println!("DIFF {d}");
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
#[test]
fn an_inline_definition_names_its_own_regex() {
let rows: [(&str, &str, &[(&str, &str)]); 3] = [
(
r"^%{TICKET:t=[A-Z]{3}-[0-9]+} %{WORD:w}$",
"ABC-12 open",
&[("t", "ABC-12"), ("w", "open")],
),
(
r"^%{CODE=[0-9]{3}} %{TICKET:t=T[0-9]+}$",
"404 T7",
&[("t", "T7")],
),
(r"^%{INT:n:int}$", "42", &[("n", "42")]),
];
for (pattern, input, want) in rows {
let g = Grok::builder("grok:i").pattern(pattern).build().unwrap();
let got = parse(&g, input).unwrap_or_else(|| panic!("{pattern} misses {input}"));
let got: Vec<(String, String)> = got.into_iter().map(|(n, v, _)| (n, v)).collect();
let want: Vec<(String, String)> = want
.iter()
.map(|(n, v)| ((*n).to_owned(), (*v).to_owned()))
.collect();
assert_eq!(got, want, "{pattern}");
}
assert_eq!(
parse(
&Grok::builder("grok:i")
.pattern("^%{TICKET:t=[A-Z]{3}-[0-9]+}$")
.build()
.unwrap(),
"abc-12"
),
None
);
}
#[test]
fn a_filter_suffix_changes_or_drops_the_value() {
let g = Grok::builder("grok:f")
.pattern("^%{WORD:level:lowercase} %{WORD:host:uppercase} %{NOTSPACE:user:nullif(-)}$")
.build()
.unwrap();
assert_eq!(
parse(&g, "WARN web01 alice"),
text(&[("level", "warn"), ("host", "WEB01"), ("user", "alice")])
);
assert_eq!(
parse(&g, "Info Web01 -"),
text(&[("level", "info"), ("host", "WEB01")])
);
}
#[test]
fn a_date_format_matches_and_hints_a_timestamp() {
let g = Grok::builder("grok:d")
.pattern("^\\[%{:ts:date(%d/%b/%Y:%H:%M:%S %z)}\\] %{WORD:verb} %{:day:date(%F)}$")
.build()
.unwrap();
assert!(
g.explain().starts_with("0: native steps"),
"{}",
g.explain()
);
let ts = |n: &str, v: &str| (n.to_owned(), v.to_owned(), Hint::Timestamp);
assert_eq!(
parse(&g, "[27/Nov/2026:18:30:00 +1100] GET 2026-11-27"),
Some(vec![
ts("ts", "27/Nov/2026:18:30:00 +1100"),
("verb".to_owned(), "GET".to_owned(), Hint::Text),
ts("day", "2026-11-27"),
])
);
assert_eq!(
parse(&g, "[27/Nov/2026:24:30:00 +1100] GET 2026-13-27"),
None
);
let e = expand(
"%{NOTSPACE:ts:date(%s)}",
&Library::default(),
Dialect::Rust,
)
.unwrap();
assert_eq!(e.captures[0].hint, Hint::Timestamp);
assert!(matches!(
expand("%{:ts:date(%Z)}", &Library::default(), Dialect::Rust),
Err(GrokError::Date(_))
));
}
#[cfg(feature = "time")]
#[test]
fn a_chrono_date_format_matches_and_hints_a_timestamp() {
let g = Grok::builder("grok:c")
.pattern("^\\[%{:ts:chrono(%d/%b/%Y:%H:%M:%S %z)}\\] %{WORD:verb} %{:day:chrono(%F)}$")
.build()
.unwrap();
let ts = |n: &str, v: &str| (n.to_owned(), v.to_owned(), Hint::Timestamp);
assert_eq!(
parse(&g, "[27/Nov/2026:18:30:00 +11:00] GET 2026-11-27"),
Some(vec![
ts("ts", "27/Nov/2026:18:30:00 +11:00"),
("verb".to_owned(), "GET".to_owned(), Hint::Text),
ts("day", "2026-11-27"),
])
);
assert_eq!(
parse(&g, "[27/Nov/2026:24:30:00 +1100] GET 2026-13-27"),
None
);
assert!(matches!(
expand("%{:ts:chrono(%Q)}", &Library::default(), Dialect::Rust),
Err(GrokError::Date(_))
));
}
#[cfg(target_arch = "x86_64")]
#[test]
fn a_priced_grok_cost_is_within_a_band_of_the_measured_one() {
for (row, pattern) in [
(
"grok.cri",
"^%{TIMESTAMP_ISO8601:timestamp} (?<stream>stdout|stderr) (?<flag>[FP]) %{GREEDYDATA:message}$",
),
(
"grok.syslog",
"^<%{NONNEGINT:pri}>%{NONNEGINT:version} %{TIMESTAMP_ISO8601:timestamp} %{NOTSPACE:hostname} %{NOTSPACE:appname} %{NOTSPACE:procid} %{NOTSPACE:msgid} - %{GREEDYDATA:message}$",
),
("grok.access", "^%{COMBINEDAPACHELOG}$"),
] {
let g = Grok::builder("grok:c").pattern(pattern).build().unwrap();
let (priced, measured) = (g.cost().unwrap(), crate::cost::of(row).unwrap());
let ratio = priced.label() / measured.label();
assert!(
(0.5..=2.0).contains(&ratio),
"{row}: priced {priced:?}, measured {measured:?}"
);
assert!(g.explain().contains("ns a hit"), "{}", g.explain());
}
let on_regex = |p: &str| Grok::builder("grok:r").pattern(p).build().unwrap();
let (one, three) = (
on_regex("^(?:%{WORD:w} )+$"),
on_regex("^(?:%{WORD:w} )+%{INT:n} %{INT:m}$"),
);
assert!(one.blocked()[0].is_some() && three.blocked()[0].is_some());
let (a, b) = (one.cost().unwrap(), three.cost().unwrap());
assert!(b.hit.ns_per_byte > a.hit.ns_per_byte);
assert_eq!(a.miss, crate::cost::of("lazy_dfa_find").unwrap().miss);
assert!(one.explain().contains("ns a hit"), "{}", one.explain());
let two = Grok::builder("grok:c")
.pattern("^a")
.pattern("^b")
.build()
.unwrap();
assert!(two.cost().is_none());
}
#[test]
fn a_shadowed_parser_writes_the_same_fields() {
let pattern = "^%{IPV4:ip} %{WORD:verb} %{NOTSPACE:path}( %{INT:n})?$";
let plain = Grok::builder("grok:s").pattern(pattern).build().unwrap();
let shadowed = Grok::builder("grok:s")
.pattern(pattern)
.shadow(std::num::NonZeroU32::MIN)
.build()
.unwrap();
for line in [
"10.0.0.1 GET /a 7",
"10.0.0.1 GET /a",
"nope",
"10.0.0.1 GET /\u{e9}",
"",
] {
assert_eq!(parse(&shadowed, line), parse(&plain, line), "{line:?}");
}
}
#[test]
fn compiled_code_backtracks_after_a_lazy_field() {
let line = br#"Deny tcp src outside:192.0.2.10/41200 dst inside:10.1.2.3/443 by access-group "OUTSIDE_IN" [0x0, 0x0]"#;
let (_, code) = super::stock::STOCK
.iter()
.find(|(p, _)| *p == "^%{CISCOFW106023}$")
.unwrap();
let mut caps = [super::spec::UNSET; super::spec::MAX_CAPTURES];
assert_eq!(code(line, &mut caps), super::spec::Steps::Matched);
assert_eq!(caps[3], (21, 31));
}
#[test]
fn explain_names_the_macro_for_a_pattern_it_could_compile() {
let says = |g: &Grok| g.explain().contains("grok! compiles it");
let built = |ps: &[&str]| {
ps.iter()
.fold(Grok::builder("grok:m"), |b, p| b.pattern(*p))
.build()
.unwrap()
};
assert!(says(&built(&["^%{INT:n} %{WORD:w}$"])));
for ps in [
&["^%{SYSLOGLINE}$"][..],
&["%{INT:n} %{WORD:w}$"],
&["^%{INT:n} %{WORD:w}$", "^%{WORD:w}$"],
] {
assert!(!says(&built(ps)), "{ps:?}");
}
}
#[test]
fn an_anchored_pattern_has_an_anchored_signature() {
let anchored = Grok::builder("grok:a")
.pattern("^job %{WORD:name} done$")
.build()
.unwrap();
assert!(anchored.signature().may_match(b"job nightly done"));
assert!(!anchored.signature().may_match(b"a job nightly done"));
assert!(matches!(
anchored.parse(b"a job nightly done", &mut Fields::new()),
Ok(Parsed::NoMatch)
));
let floating = Grok::builder("grok:b")
.pattern("job %{WORD:name} done")
.build()
.unwrap();
assert!(floating.signature().may_match(b"a job nightly done"));
let mixed = Grok::builder("grok:c")
.pattern("^job %{WORD:name} done$")
.pattern("task %{WORD:name}")
.build()
.unwrap();
assert!(mixed.signature().may_match(b"a job nightly done"));
assert!(mixed.signature().may_match(b"x task nightly"));
}
const TIERS: [(&[&str], &str); 3] = [
(&["^%{WORD:a} %{INT:b}$"], "alpha 42"),
(&["^(?:%{WORD:w} )+%{INT:n}$"], "alpha beta 42"),
(&["x%{INT:n}", "%{WORD:a} %{INT:b}"], "alpha 42"),
];
struct Again<'g> {
grok: &'g Grok,
line: &'static str,
outer: Vec<(String, String)>,
inner: Option<Vec<(String, String, Hint)>>,
}
impl<'a> crate::parse::FieldSink<'a> for Again<'_> {
fn field(&mut self, name: &str, value: crate::parse::FieldValue<'a>) {
if self.outer.is_empty() {
self.inner = parse(self.grok, self.line);
}
let text = String::from_utf8_lossy(&value.bytes).into_owned();
self.outer.push((name.to_owned(), text));
}
fn push_prefix(&mut self, _: &str) {}
fn pop_prefix(&mut self) {}
fn mark(&self) -> crate::parse::SinkMark {
crate::parse::SinkMark(self.outer.len())
}
fn rollback(&mut self, mark: crate::parse::SinkMark) {
self.outer.truncate(mark.0);
}
}
#[test]
fn the_tiers_are_the_ones_their_tests_mean() {
assert_eq!(grok(TIERS[0].0).blocked(), [None]);
assert!(grok(TIERS[1].0).blocked()[0].is_some());
assert_eq!(grok(TIERS[2].0).blocked().len(), 2);
let plan = |p: &str| grok(&[p]).explain();
assert!(plan("%{COMBINEDAPACHELOG}").contains("native steps"));
let flow = "%{IP:src}:%{INT:sport} -> %{IP:dst}:%{INT:dport} %{WORD:proto}";
assert!(plan(flow).contains("native steps"));
assert!(plan("^(?:%{WORD:w} )+%{INT:n}$").contains("regex:"));
}
#[test]
fn a_sink_that_parses_again_reads_the_same_fields_both_times() {
for (patterns, line) in TIERS {
let g = grok(patterns);
let alone = parse(&g, line).unwrap();
assert_ne!(alone.len(), 0, "{line}");
let mut sink = Again {
grok: &g,
line,
outer: Vec::new(),
inner: None,
};
g.parse(line.as_bytes(), &mut sink).unwrap();
let outer: Vec<(String, String)> = alone
.iter()
.map(|(n, v, _)| (n.clone(), v.clone()))
.collect();
assert_eq!(sink.outer, outer, "{line}");
assert_eq!(sink.inner.as_ref(), Some(&alone), "{line}");
}
}
#[test]
fn sixteen_threads_on_one_parser_read_what_one_reads() {
for (patterns, line) in TIERS {
let g = grok(patterns);
let alone = parse(&g, line);
std::thread::scope(|scope| {
for _ in 0..16 {
scope.spawn(|| {
for _ in 0..200 {
assert_eq!(parse(&g, line), alone, "{line}");
assert_eq!(parse(&g, "no match here"), None);
}
});
}
});
}
}
#[test]
fn a_parse_after_a_sink_panicked_reads_as_before() {
struct Bang;
impl<'a> crate::parse::FieldSink<'a> for Bang {
fn field(&mut self, _: &str, _: crate::parse::FieldValue<'a>) {
panic!("the sink gave up");
}
fn push_prefix(&mut self, _: &str) {}
fn pop_prefix(&mut self) {}
fn mark(&self) -> crate::parse::SinkMark {
crate::parse::SinkMark(0)
}
fn rollback(&mut self, _: crate::parse::SinkMark) {}
}
for (patterns, line) in TIERS {
let g = grok(patterns);
let alone = parse(&g, line);
let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _ = g.parse(line.as_bytes(), &mut Bang);
}));
assert!(caught.is_err(), "{line}");
assert_eq!(parse(&g, line), alone, "{line}");
}
}
type Wanted = Option<&'static [(&'static str, &'static str)]>;
#[test]
fn a_class_reads_by_dialect() {
const WORD: Wanted = Some(&[("w", "caf\u{e9}")]);
const PATH: Wanted = Some(&[("p", "/var/log/caf\u{e9}/app.log")]);
const NONE: Wanted = None;
const EMPTY: Wanted = Some(&[]);
let rows: &[(&str, &str, Wanted, Wanted)] = &[
("%{WORD:w}", "caf\u{e9}!", WORD, NONE),
(
"^%{NOTSPACE:a} %{NOTSPACE:b}$",
"x\u{a0}y z",
NONE,
Some(&[("a", "x\u{a0}y"), ("b", "z")]),
),
("%{UNIXPATH:p}", "/var/log/caf\u{e9}/app.log", PATH, PATH),
("^%{INT:n:int}$", "\u{661}\u{662}\u{663}", NONE, NONE),
("^%{PORT:n:int}$", "\u{661}\u{662}", NONE, NONE),
("^%{NUMBER:n:float}$", "\u{661}.\u{662}", NONE, NONE),
("^%{TIME:t}$", "1\u{663}:00", NONE, NONE),
("^%{MONTHDAY:d}$", "\u{661}", NONE, NONE),
("^a%{SPACE}b$", "a\u{3000}b", EMPTY, NONE),
(
r"^(?<n>\d+)$",
"\u{661}\u{662}",
Some(&[("n", "\u{661}\u{662}")]),
NONE,
),
(r"^(?<w>\w+)$", "caf\u{e9}", WORD, NONE),
(r"^(?<w>[\w.-]+)$", "caf\u{e9}", WORD, NONE),
(r"^a\sb$", "a\u{a0}b", EMPTY, NONE),
(r"^a\Wb$", "a\u{e9}b", NONE, EMPTY),
(r"^(?<s>[^\S]+)$", "\u{a0}", Some(&[("s", "\u{a0}")]), NONE),
(r"^(?<w>\w+)\b", "caf\u{e9}", WORD, NONE),
(r"^(?<w>[[:alpha:]]+)$", "caf\u{e9}", NONE, WORD),
(
r"^(?<w>[[:upper:]]+)$",
"\u{c9}COLE",
NONE,
Some(&[("w", "\u{c9}COLE")]),
),
(
r"^(?<w>[[:^alpha:]0-9]+)$",
"12\u{e9}",
Some(&[("w", "12\u{e9}")]),
NONE,
),
(
r"^(?<w>[[:alnum:]_]+)$",
"caf\u{e9}_1",
NONE,
Some(&[("w", "caf\u{e9}_1")]),
),
(r"^(?<w>\p{L}+)$", "caf\u{e9}", WORD, WORD),
(
r"^(?i)(?<w>\w+)$",
"\u{212a}",
Some(&[("w", "\u{212a}")]),
NONE,
),
("^(?i)a\\Wb$", "a\u{212a}b", NONE, EMPTY),
(r"^caf\x{e9}$", "caf\u{e9}", EMPTY, EMPTY),
(
"^%{LOGLEVEL:l}$",
"info\u{e9}",
Some(&[("l", "info\u{e9}")]),
NONE,
),
(
"^%{NOTSPACE:a} %{NOTSPACE:b}$",
"x y",
Some(&[("a", "x"), ("b", "y")]),
Some(&[("a", "x"), ("b", "y")]),
),
(
"%{WORD:w}",
"cafe!",
Some(&[("w", "cafe")]),
Some(&[("w", "cafe")]),
),
(r"^a\sb$", "a\tb", EMPTY, EMPTY),
];
for (pattern, input, rust, onig) in rows {
for (dialect, want) in [(Dialect::Rust, rust), (Dialect::Oniguruma, onig)] {
let g = Grok::builder("grok:c")
.pattern(*pattern)
.dialect(dialect)
.build()
.unwrap();
let want = (*want).and_then(text);
let at = format!("{dialect:?} {pattern} on {input:?}");
assert_eq!(parse(&g, input), want, "{at}");
assert_eq!(parse_by_regex(&g, input), want, "{at} by the regex");
}
}
}
#[test]
fn oniguruma_steps_answer_for_a_line_where_the_classes_agree() {
use super::plan::Outcome;
let onig = |p: &str| {
Grok::builder("grok:c")
.pattern(p)
.dialect(Dialect::Oniguruma)
.build()
.unwrap()
};
let outcome = |g: &Grok, line: &str| g.native_outcome(line.as_bytes()).unwrap().0;
let classed = onig("^%{IPV4:ip} %{NOTSPACE:d}$");
assert_eq!(outcome(&classed, "10.0.0.1 cafe"), Outcome::Matched);
assert_eq!(outcome(&classed, "10.0.0.1 caf\u{e9}"), Outcome::Unsure);
let plain = onig("^%{IPV4:ip} %{DATA:d}$");
assert_eq!(outcome(&plain, "10.0.0.1 caf\u{e9}"), Outcome::Matched);
let rust = grok(&["^%{IPV4:ip} %{NOTSPACE:d}$"]);
assert_eq!(outcome(&rust, "10.0.0.1 caf\u{e9}"), Outcome::Matched);
}