#![allow(
clippy::literal_string_with_formatting_args,
reason = "grok's %{NAME:field} reads as a format argument"
)]
use proptest::prelude::*;
use super::*;
use crate::parse::{Fields, Parsed, Parser};
use crate::tier::MatcherTier;
type Written = Option<Vec<(String, Vec<u8>, Hint)>>;
fn parse(p: &Grok, input: &[u8]) -> Written {
let mut out = Fields::new();
match p.parse(input, &mut out).unwrap() {
Parsed::NoMatch => None,
_ => Some(
out.as_slice()
.iter()
.map(|(n, v)| (n.clone(), v.bytes.to_vec(), v.hint))
.collect(),
),
}
}
fn grok(pattern: &str) -> Grok {
Grok::builder("grok:test").pattern(pattern).build().unwrap()
}
fn access_log() -> Part {
let user = || field("EMAILADDRESS").or(field("USERNAME"));
let letters = Chars::range('A', 'Z').or(&Chars::range('a', 'z'));
let verb = run(letters.clone())
.at_most(1)
.then(run(letters.or(&Chars::of("-"))).at_least(0))
.named("verb");
let request = verb
.then(literal(" "))
.then(field("NOTSPACE").named("request"))
.then(
literal(" HTTP/")
.then(field("NUMBER").named("httpversion"))
.optional(),
);
let count = |name| literal("-").or(field("NONNEGINT").named(name));
field("IPORHOST")
.named("clientip")
.then(literal(" "))
.then(user().named("ident"))
.then(literal(" "))
.then(user().named("auth"))
.then(literal(" ["))
.then(field("HTTPDATE").named("timestamp"))
.then(literal("] \""))
.then(request.or(until_next().named("rawrequest")))
.then(literal("\" "))
.then(count("response"))
.then(literal(" "))
.then(count("bytes"))
.then(literal(" "))
.then(field("QUOTEDSTRING").named("referrer"))
.then(literal(" "))
.then(field("QUOTEDSTRING").named("agent"))
}
fn syslog_line() -> Part {
let prog = Chars::range('\x21', '\x39')
.or(&Chars::range('\x3b', '\x5a'))
.or(&Chars::of("\\"))
.or(&Chars::range('\x5e', '\x7e'));
let facility = literal("<")
.then(field("NONNEGINT").named("facility"))
.then(literal("."))
.then(field("NONNEGINT").named("priority"))
.then(literal("> "));
let program = literal(" ")
.then(run(prog).named("program"))
.then(
literal("[")
.then(field("NONNEGINT").named("pid"))
.then(literal("]"))
.optional(),
)
.then(literal(":"));
field("SYSLOGTIMESTAMP")
.named("timestamp")
.or(field("TIMESTAMP_ISO8601").named("timestamp8601"))
.then(literal(" "))
.then(facility.optional())
.then(field("IPORHOST").named("logsource"))
.then(program.optional())
.then(literal(" "))
.then(field("GREEDYDATA").named("message"))
}
const ACCESS_LINES: &[&str] = &[
r#"127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326 "http://www.example.com/start.html" "Mozilla/4.08 [en] (Win98; I ;Nav)""#,
r#"10.0.0.1 - - [10/Oct/2000:13:55:36 -0700] "M-SEARCH * HTTP/1.1" 200 - "-" "-""#,
r#"host.example.com - - [10/Oct/2000:13:55:36 +0000] "-" 408 - "-" "-""#,
r#"10.0.0.1 - - [10/Oct/2000:13:55:36 +0000] "GARBAGE" 400 226 "-" "curl/8.0""#,
r#"10.0.0.1 a@b.example - [10/Oct/2000:13:55:36 +0000] "GET /x HTTP/2" 200 1 "-" "agent \"q\" é""#,
r#"::1 - - [10/Oct/2000:13:55:36 +0000] "GET /a"b HTTP/1.1" 200 1 "-" "-""#,
r#"lead 127.0.0.1 - - [10/Oct/2000:13:55:36 -0700] "GET / HTTP/1.1" 200 5 "-" "-" tail"#,
r#"10.0.0.1 - - [10/Oct/2000:13:55:36 +0000] "X /a HTTP/1.1" 200 1 "-" "-""#,
r#"10.0.0.1 - - [10/Oct/2000:13:55:36 +0000] "m-search * HTTP/1.1" 200 1 "-" "-""#,
r#"127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326"#,
r#"127.0.0.1 - - [10/Oct/2000:13:55:36 -0700] "GET / HTTP/1.1" ok 12 "-" "-""#,
r#"127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" OK 2326"#,
r#"{"ts":"2026-11-27T08:00:00Z","level":"info","msg":"cache warm","n":42}"#,
"",
];
const SYSLOG_LINES: &[&str] = &[
"Nov 27 08:00:01 host01 sshd[1234]: Accepted publickey for alice from 10.0.0.5 port 50522 ssh2",
"Oct 11 22:14:15 mymachine su: 'su root' failed",
"Oct 11 22:14:15 host hello",
"Oct 11 22:14:15 <4.6> host sshd[12]: msg",
"2003-10-11T22:14:15 host sshd: x",
"Nov 1 03:00:00 host cron[9]: (alice) RELOAD (crontabs/alice)",
"Nov 27 08:00:01 10.1.2.3 kernel: é ünïcode\nsecond line",
"Nov 27 08:00:01 host01",
"Oct 11 22:14:15",
"hello world",
"",
];
fn same_fields(composed: &Grok, grok: &Grok, lines: &[&str]) -> usize {
let mut hits = 0;
for line in lines {
let want = parse(grok, line.as_bytes());
hits += usize::from(want.is_some());
assert_eq!(parse(composed, line.as_bytes()), want, "{line:?}");
}
hits
}
fn costs_no_more(composed: &Grok, grok: &Grok, case: &str) {
let (Some(c), Some(g)) = (composed.cost(), grok.cost()) else {
assert_eq!(composed.cost(), grok.cost(), "{case}");
return;
};
assert!(
c.hit.fixed_ns <= g.hit.fixed_ns,
"{case}: {c:?} against {g:?}"
);
assert_eq!(c.hit.ns_per_byte, g.hit.ns_per_byte, "{case}");
assert_eq!(c.miss, g.miss, "{case}");
}
#[test]
fn a_composed_access_log_parses_as_the_library_pattern() {
let composed = access_log().build("compose:access").unwrap();
let grok = grok("%{COMBINEDAPACHELOG}");
assert_eq!(same_fields(&composed, &grok, ACCESS_LINES), 8);
assert_eq!(composed.tier(), MatcherTier::Field);
assert_eq!(composed.tier(), grok.tier());
costs_no_more(&composed, &grok, "access log");
}
#[test]
fn a_composed_syslog_line_parses_as_the_library_pattern() {
let composed = syslog_line().build("compose:syslog").unwrap();
let grok = grok("%{SYSLOGLINE}");
assert_eq!(same_fields(&composed, &grok, SYSLOG_LINES), 7);
assert_eq!(composed.tier(), MatcherTier::Field);
assert_eq!(composed.tier(), grok.tier());
costs_no_more(&composed, &grok, "syslog line");
}
fn mutated(lines: &'static [&'static str]) -> impl Strategy<Value = Vec<u8>> {
const BYTES: &[&[u8]] = &[
b" ",
b"\"",
b"-",
b"[",
b"]",
b"<",
b">",
b":",
b".",
b"/",
b"0",
b"7",
b"a",
b"Z",
b"\n",
b"\t",
"é".as_bytes(),
b"\xff",
];
let edit = (
any::<prop::sample::Index>(),
0_u8..3,
prop::sample::select(BYTES),
);
(
prop::sample::select(lines),
prop::collection::vec(edit, 0..5),
)
.prop_map(|(line, edits)| {
let mut bytes = line.as_bytes().to_vec();
for (at, op, with) in edits {
let at = at.index(bytes.len() + 1);
match op {
0 => {
bytes.splice(at..at, with.iter().copied());
}
_ if at == bytes.len() => {}
1 => {
bytes.remove(at);
}
_ => {
bytes.splice(at..=at, with.iter().copied());
}
}
}
bytes
})
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(1024))]
#[test]
fn composed_and_library_access_logs_agree_on_edited_lines(line in mutated(ACCESS_LINES)) {
thread_local! {
static PAIR: (Grok, Grok) = (
access_log().build("compose:access").unwrap(),
grok("%{COMBINEDAPACHELOG}"),
);
}
PAIR.with(|(composed, grok)| {
prop_assert_eq!(parse(composed, &line), parse(grok, &line));
Ok(())
})?;
}
#[test]
fn composed_and_library_syslog_lines_agree_on_edited_lines(line in mutated(SYSLOG_LINES)) {
thread_local! {
static PAIR: (Grok, Grok) = (
syslog_line().build("compose:syslog").unwrap(),
grok("%{SYSLOGLINE}"),
);
}
PAIR.with(|(composed, grok)| {
prop_assert_eq!(parse(composed, &line), parse(grok, &line));
Ok(())
})?;
}
}
#[allow(clippy::too_many_lines, reason = "one table of 20 parts")]
fn primitives() -> Vec<(&'static str, Part, &'static str, &'static [&'static str])> {
let digits = || run(Chars::range('0', '9'));
vec![
(
"a literal with every metacharacter",
literal("a.b[c]{d}%{e}|^$*+?()\\-#&~<>"),
r"a\.b\[c\]\{d\}%\{e\}\|\^\$\*\+\?\(\)\\\-\#\&\~<>",
&[
r"a.b[c]{d}%{e}|^$*+?()\-#&~<>",
r"xa.b[c]{d}%{e}|^$*+?()\-#&~<>y",
r"aXb[c]{d}%{e}|^$*+?()\-#&~<>",
"",
],
),
(
"a named field scanner",
field("IPV4").named("ip"),
"%{IPV4:ip}",
&["10.0.0.1", "x 1.2.3.4 y", "1.2.3", "999.1.1.1", ""],
),
(
"a typed field scanner",
field("INT").named("n").typed(Hint::Int),
"%{INT:n:int}",
&["-12", "a 7 b", "a", ""],
),
(
"a nested field name",
field("WORD").named("a.b"),
"%{WORD:[a][b]}",
&["hello", " ", ""],
),
(
"a run of everything but a quote",
literal("\"")
.then(run(Chars::but("\"")).named("q"))
.then(literal("\"")),
r#""(?<q>[^"]+)""#,
&[
r#""abc""#,
r#""""#,
"\"\u{e9}\nx\"",
r#""unclosed"#,
"\"\u{ff}\"",
],
),
(
"a counted run of a union",
run(Chars::range('a', 'z').or(&Chars::of("-")))
.at_least(2)
.at_most(4)
.named("w"),
"(?<w>[a-z-]{2,4})",
&["abcdef", "a", "-x-", "AB", ""],
),
(
"an exact count",
digits().at_least(3).at_most(3).named("d"),
"(?<d>[0-9]{3})",
&["12345", "12", "a123", ""],
),
(
"an open count",
digits().at_least(2).named("d"),
"(?<d>[0-9]{2,})",
&["12345", "1", ""],
),
(
"a run that may be empty",
literal("<")
.then(digits().at_least(0).named("d"))
.then(literal(">")),
"<(?<d>[0-9]*)>",
&["<>", "<12>", "<1a>", ""],
),
(
"a run of zero or one",
literal("v")
.then(digits().at_least(0).at_most(1).named("d"))
.then(end()),
"v(?<d>[0-9]?)$",
&["v", "v1", "v12", ""],
),
(
"a typed float on a run",
digits().named("d").typed(Hint::Float),
"%{D:d:float=[0-9]+}",
&["42", "x", ""],
),
(
"until a literal",
until(" ").named("a").then(field("INT").named("n")),
"%{DATA:a} %{INT:n}",
&["x y 12", "abc 5", "no int", "a\nb 1", " 1", ""],
),
(
"until the next part",
literal("(")
.then(until_next().named("a"))
.then(literal(")").or(literal("]"))),
"\\(%{DATA:a}(?:\\)|\\])",
&["(x)", "(x]", "(x", "(a)b]", ""],
),
(
"a choice of literals",
one_of(["GET", "POST", "PUT"])
.named("verb")
.then(literal(" ")),
"(?<verb>GET|POST|PUT) ",
&["POST /", "PATCH /", "GET ", "PUTS ", ""],
),
(
"an optional field",
literal("a")
.then(field("INT").named("n").optional())
.then(literal("b")),
"a(?:%{INT:n})?b",
&["a12b", "ab", "a12", "xa1b", ""],
),
(
"both anchors",
start().then(field("WORD").named("w")).then(end()),
"^%{WORD:w}$",
&["abc", "abc ", " abc", ""],
),
(
"a field or a literal",
field("IPV4").named("ip").or(literal("-")),
"(?:%{IPV4:ip}|-)",
&["-", "1.2.3.4", "x", ""],
),
(
"a named choice of fields",
field("EMAILADDRESS").or(field("USERNAME")).named("u"),
"%{HTTPDUSER:u}",
&["a@b.example", "bob", "-", ""],
),
(
"a named sequence joined to more",
literal("a")
.then(field("INT"))
.named("x")
.then(literal("b")),
"(?<x>a%{INT})b",
&["a12b", "a12", "xa-3b", ""],
),
(
"names inside a name",
literal("a")
.then(field("INT").named("n"))
.then(digits().at_least(0).named("d"))
.named("x")
.then(literal("b").or(until_next().named("rest")))
.then(end()),
"(?<x>a%{INT:n}(?<d>[0-9]*))(?:b|%{DATA:rest})$",
&["a-12b", "a7zz", "a1", "b", ""],
),
]
}
#[test]
fn each_primitive_parses_as_the_grok_it_mirrors() {
for (case, part, pattern, lines) in primitives() {
let composed = part.build("compose:case").unwrap();
let grok = grok(pattern);
assert_eq!(composed.tier(), grok.tier(), "{case}");
costs_no_more(&composed, &grok, case);
for line in lines {
assert_eq!(
parse(&composed, line.as_bytes()),
parse(&grok, line.as_bytes()),
"{case}: {line:?}"
);
}
}
}
#[test]
fn parts_that_cant_make_a_parser_say_why() {
let cases: Vec<(Part, &str)> = vec![
(field("NOPE"), r#"no field scanner is named "NOPE""#),
(field("INT").named("a:b"), r#""a:b" can't be a field name"#),
(field("INT").named(""), r#""" can't be a field name"#),
(field("INT").named("a}"), r#""a}" can't be a field name"#),
(field("INT").named("a=b"), r#""a=b" can't be a field name"#),
(
field("INT").named("a\u{1}"),
r#""a\u{1}" can't be a field name"#,
),
(field("INT").typed(Hint::Int), "a hint with no name"),
(
field("INT").named("n").typed(Hint::Ip),
"a hint grok can't write: only Text, Int, Float and Bool",
),
(
literal("x").at_least(2),
"at_least on a part that isn't a run",
),
(
field("INT").at_most(1),
"at_most on a part that isn't a run",
),
(
literal("a").then(literal("b").at_least(1)),
"at_least on a part that isn't a run",
),
(run(Chars::of("")), "a run of an empty set"),
(run(Chars::of("a")).at_most(0), "a run of at most 0"),
(
run(Chars::of("a")).at_least(3).at_most(2),
"a run whose at_most is below its at_least",
),
(until(""), "an until with an empty literal"),
(one_of(Vec::<String>::new()), "one_of with no literals"),
(start().named("s"), "a name on an anchor"),
(literal(""), "a part that matches nothing"),
(
literal("a").or(field("BAD").named("x")).optional(),
r#"no field scanner is named "BAD""#,
),
];
for (part, want) in cases {
let err = part.build("compose:bad").unwrap_err();
assert_eq!(err.to_string(), want, "{part:?}");
}
}
#[test]
fn a_part_builds_more_than_once_and_each_parser_stands_alone() {
let part = until(" ").named("a").then(run(Chars::of("x")).named("b"));
let one = part.build("compose:one").unwrap();
let two = part.build("compose:two").unwrap();
for p in [&one, &two] {
assert_eq!(
parse(p, b"k xx"),
Some(vec![
("a".to_owned(), b"k".to_vec(), Hint::Text),
("b".to_owned(), b"xx".to_vec(), Hint::Text),
])
);
}
assert_eq!(one.name(), "compose:one");
assert!(one.explain().contains("native steps"), "{}", one.explain());
}
#[test]
fn a_part_that_cant_lower_says_so_and_still_answers_as_the_regex() {
let part = run(Chars::range('0', '9'))
.at_most(20)
.named("n")
.then(literal("x"));
let composed = part.build("compose:leading").unwrap();
assert_eq!(composed.tier(), MatcherTier::Regex);
let explained = composed.explain();
assert!(explained.contains("starts with a run"), "{explained}");
assert_eq!(
parse(&composed, b"ab123x"),
Some(vec![("n".to_owned(), b"123".to_vec(), Hint::Text)])
);
assert_eq!(parse(&composed, b"ab123"), None);
}
#[test]
fn the_page_example_parses_a_syslog_line() {
let parser = field("SYSLOGTIMESTAMP")
.named("timestamp")
.then(literal(" "))
.then(field("IPORHOST").named("host"))
.then(literal(" "))
.then(run(Chars::but(":[ ")).named("program"))
.then(
literal("[")
.then(field("NONNEGINT").named("pid").typed(Hint::Int))
.then(literal("]"))
.optional(),
)
.then(literal(": "))
.then(field("GREEDYDATA").named("message"))
.build("compose:syslog")
.unwrap();
assert_eq!(parser.tier(), MatcherTier::Field);
let field = |n: &str, v: &str, h| (n.to_owned(), v.as_bytes().to_vec(), h);
assert_eq!(
parse(&parser, b"Nov 27 08:00:01 host01 sshd[1234]: Accepted"),
Some(vec![
field("timestamp", "Nov 27 08:00:01", Hint::Text),
field("host", "host01", Hint::Text),
field("program", "sshd", Hint::Text),
field("pid", "1234", Hint::Int),
field("message", "Accepted", Hint::Text),
])
);
assert_eq!(
parse(&parser, b"Nov 27 08:00:01 host01 cron: x").map(|f| f.len()),
Some(4)
);
assert_eq!(parse(&parser, b"Nov 27 08:00:01 host01 cron x"), None);
}