use std::borrow::Cow;
use super::lex::{self, Tok};
use super::parse::{Ast, Cmp, Func, Lit, Method, Path, parse};
fn path(p: &str) -> Path {
let segs: Vec<String> = p.split('.').map(str::to_owned).collect();
let named = segs.len();
Path(segs, named)
}
fn kinds(text: &str) -> Vec<Tok<'_>> {
lex::tokens(text)
.expect(text)
.into_iter()
.map(|t| t.tok)
.collect()
}
fn eq(p: &str, v: &str) -> Ast {
Ast::Cmp(path(p), Cmp::Eq, Lit::Str(v.to_owned()))
}
#[test]
fn the_subset_parses_to_its_tree() {
let cases: Vec<(&str, Ast)> = vec![
("has(r._table)", Ast::Has(path("r._table"), 0..3)),
("has(_table)", Ast::Has(path("_table"), 0..3)),
(
"!has(_table)",
Ast::Not(Box::new(Ast::Has(path("_table"), 1..4))),
),
("!has(a.b)", Ast::Not(Box::new(Ast::Has(path("a.b"), 1..4)))),
(r#"status == "poison""#, eq("status", "poison")),
(r#""poison" == status"#, eq("status", "poison")),
(
"3 < severity",
Ast::Cmp(path("severity"), Cmp::Gt, Lit::Int(3)),
),
(
"event.system.event_id == 5158",
Ast::Cmp(path("event.system.event_id"), Cmp::Eq, Lit::Int(5158)),
),
(
"x >= -1.5e2",
Ast::Cmp(path("x"), Cmp::Ge, Lit::Double(-150.0)),
),
("x != 7u", Ast::Cmp(path("x"), Cmp::Ne, Lit::Uint(7))),
("x == null", Ast::Cmp(path("x"), Cmp::Eq, Lit::Null)),
("x == true", Ast::Cmp(path("x"), Cmp::Eq, Lit::Bool(true))),
("true", Ast::Const(true)),
(
"size(a) > 3",
Ast::Call(Func::Size, path("a"), Cmp::Gt, Lit::Int(3)),
),
(
"a.b.size() == 0u",
Ast::Call(Func::Size, path("a.b"), Cmp::Eq, Lit::Uint(0)),
),
(
"2 == x.size()",
Ast::Call(Func::Size, path("x"), Cmp::Eq, Lit::Int(2)),
),
(
"3 <= int(a)",
Ast::Call(Func::Int, path("a"), Cmp::Ge, Lit::Int(3)),
),
("size == 1", Ast::Cmp(path("size"), Cmp::Eq, Lit::Int(1))),
(
r#"event.network.direction == "outbound" && event.dns.type == "query""#,
Ast::And(vec![
eq("event.network.direction", "outbound"),
eq("event.dns.type", "query"),
]),
),
(
r#"event.dns.type == "query" || event.dns.type == "answer""#,
Ast::Or(vec![
eq("event.dns.type", "query"),
eq("event.dns.type", "answer"),
]),
),
(
r#"!(a == "x" && b == "y") || c == "z""#,
Ast::Or(vec![
Ast::Not(Box::new(Ast::And(vec![eq("a", "x"), eq("b", "y")]))),
eq("c", "z"),
]),
),
(
r#"host.matches("^prod-.*$")"#,
Ast::Method(path("host"), Method::Matches, "^prod-.*$".to_owned()),
),
(
r#"a["b-c"].contains('x')"#,
Ast::Method(
Path(vec!["a".to_owned(), "b-c".to_owned()], 1),
Method::Contains,
"x".to_owned(),
),
),
(
r#"t in ["query", "answer",]"#,
Ast::In(
path("t"),
vec![Lit::Str("query".to_owned()), Lit::Str("answer".to_owned())],
),
),
(
"a.`b-c` == 'x' // trailing comment",
Ast::Cmp(
Path(vec!["a".to_owned(), "b-c".to_owned()], 2),
Cmp::Eq,
Lit::Str("x".to_owned()),
),
),
(
r#"m.startsWith(r"\d")"#,
Ast::Method(path("m"), Method::StartsWith, r"\d".to_owned()),
),
(
r#"m.endsWith("a\x41é\101\n")"#,
Ast::Method(path("m"), Method::EndsWith, "aA\u{e9}A\n".to_owned()),
),
(
"m == '''two\nlines'''",
Ast::Cmp(path("m"), Cmp::Eq, Lit::Str("two\nlines".to_owned())),
),
];
for (text, want) in cases {
assert_eq!(parse(text).as_ref(), Ok(&want), "{text}");
}
}
#[test]
fn forms_outside_the_subset_are_refused_where_they_start() {
let cases: &[(&str, &str)] = &[
("size(a) + 1 > 3", "size"),
("a.size() + 1 > 3", "a"),
("size('x') == 1", "'x'"),
("size(a, b) == 1", ","),
("a.size(1) == 1", "size"),
("int(a) == b", "b"),
("int(a) in [1]", "int"),
("uint(a) > 1", "uint"),
("a + 1 == 3", "+"),
("a == b", "b"),
("a ? b : c", "?"),
("a.exists(x, x == 1)", "exists"),
("a == b'x'", "b'x'"),
("a", "a"),
("(a == 'x'", ""),
(r#""x".contains(a)"#, "\"x\""),
("a.contains(b)", "b"),
("a == 'x' b", "b"),
("in == 'x'", "in"),
("has(a[\"b\"])", "has"),
];
for &(text, at) in cases {
let refusal = parse(text).expect_err(text);
assert_eq!(&text[refusal.span.clone()], at, "{text}: {refusal}");
}
}
#[test]
fn text_cel_rejects_is_a_lexing_refusal() {
for text in [
"a == 'open",
"a == 'line\nbreak'",
r"a == '\q'",
"a == `",
"a == 99999999999999999999",
] {
assert!(lex::tokens(text).is_err(), "{text}");
}
for (text, escape) in [(r"a == '\q'", r"\q"), ("a == 'x\\\u{e9}'", "\\\u{e9}")] {
let refusal = parse(text).expect_err(text);
assert_eq!(
text.get(refusal.span.clone()),
Some(escape),
"{text}: {refusal}"
);
}
assert_eq!(
kinds("a\x0b==\x0c1"),
[Tok::Ident("a"), Tok::EqEq, Tok::Int(1)]
);
assert_eq!(
kinds(r#"rb"x""#),
[Tok::Ident("rb"), Tok::Str(Cow::Borrowed("x"))]
);
assert_eq!(kinds(r#"br"x""#), [Tok::Bytes]);
assert_eq!(
kinds(r#""""a""#),
[Tok::Str(Cow::Borrowed("")), Tok::Str(Cow::Borrowed("a"))]
);
let toks: Vec<Tok<'_>> = lex::tokens("1 0x1F 2u 0x2u .5 1e3 1.5")
.expect("numbers")
.into_iter()
.map(|t| t.tok)
.collect();
assert_eq!(
toks,
[
Tok::Int(1),
Tok::Int(31),
Tok::Uint(2),
Tok::Uint(2),
Tok::Double(0.5),
Tok::Double(1000.0),
Tok::Double(1.5)
]
);
}
#[test]
fn an_absent_parent_reads_as_false_only_when_asked() {
use super::{ErrorKind, Options, Outcome, Program};
let lenient = Options {
missing_parent_false: true,
..Options::default()
};
let cases: &[(&str, &[u8], Outcome, Outcome)] = &[
(
"has(event.message)",
br#"{"x":1}"#,
Outcome::Error(ErrorKind::MissingRoot),
Outcome::False,
),
(
"!has(event.message)",
br#"{"x":1}"#,
Outcome::Error(ErrorKind::MissingRoot),
Outcome::True,
),
(
"has(a.b.c)",
br#"{"a":{}}"#,
Outcome::Error(ErrorKind::MissingField),
Outcome::False,
),
(
"has(a.b)",
br#"{"a":{"b":1}}"#,
Outcome::True,
Outcome::True,
),
("has(a.b)", br#"{"a":{}}"#, Outcome::False, Outcome::False),
(
"has(a.b)",
br#"{"a":"#,
Outcome::Error(ErrorKind::Malformed),
Outcome::Error(ErrorKind::Malformed),
),
];
for &(text, record, strict, loose) in cases {
let p = Program::compile(text).expect(text);
assert_eq!(p.eval(record), strict, "{text} on {record:?}");
let p = Program::compile_with(text, &lenient).expect(text);
assert_eq!(p.eval(record), loose, "{text} on {record:?}, lenient");
}
}
#[test]
fn raw_json_spellings_read_as_their_values() {
use super::{ErrorKind, Outcome};
raw_json_cases(&[
(r#"f == "aa""#, br#"{"f":"aa"}"#, Outcome::True),
(r#"f == "aa""#, br#"{"f":"\u0061a"}"#, Outcome::True),
(r#"f == "x""#, br#"{"\u0066":"x"}"#, Outcome::True),
(r#"a.b == "x""#, br#"{"a":{"\u0062":"x"}}"#, Outcome::True),
(r#"f == "a\"b""#, br#"{"f":"a\"b"}"#, Outcome::True),
(
r#"f.startsWith("a")"#,
br#"{ "f" : "abc" , "g" : 1 }"#,
Outcome::True,
),
("has(a.b)", br#"{"a" : { "b" : null } }"#, Outcome::True),
("has(_table)", br#"{"_table":null}"#, Outcome::True),
("has(_table)", br#"{"_tables":1}"#, Outcome::False),
("!has(_table)", br#"{"a":1}"#, Outcome::True),
(
"has(_table) && t == 1",
br#"{"_table":"x","t":1}"#,
Outcome::True,
),
("has(_table)", b"[1]", Outcome::False),
(
"has(_table)",
br#"{"_table":}"#,
Outcome::Error(ErrorKind::Malformed),
),
("f == 1", b"[1]", Outcome::Error(ErrorKind::MissingRoot)),
("f == 1", b"", Outcome::Error(ErrorKind::MissingRoot)),
("f == 1", br#"{"f":}"#, Outcome::Error(ErrorKind::Malformed)),
(
"a.b == 1",
br#"{"a":{"c":1}}"#,
Outcome::Error(ErrorKind::MissingField),
),
(
r#"a.startsWith("x")"#,
br#"{"a":1}"#,
Outcome::Error(ErrorKind::TypeMismatch),
),
("f == 1 || g == 2", br#"{"g":2}"#, Outcome::True),
("f == 1 && g == 2", br#"{"g":3}"#, Outcome::False),
]);
}
#[test]
fn raw_json_faults_read_the_same_either_way() {
use super::{ErrorKind, Outcome};
raw_json_cases(&[
(r#"f == "a""#, br#"{"f":"a","f":"b"}"#, Outcome::True),
(
r#"a.b == "x""#,
br#"{"a":{"b":"x","b":"y"},"a":{"b":"z"}}"#,
Outcome::True,
),
(
r#"h == "1" && e.t == "q" && e.n > 3"#,
br#"{"x":"y","z":[1,{"h":"0"}],"w":{"h":2},"h":"1","e":{"n":4,"t":"q"}}"#,
Outcome::True,
),
(
r#"has(e.t) && e.t.endsWith("q")"#,
br#"{"x":1,"e":{"t":"q"}}"#,
Outcome::True,
),
(r#"f == "x""#, br#"{"f":"x","g":"#, Outcome::True),
(
r#"f == "x""#,
br#"{"g":,"f":"x"}"#,
Outcome::Error(ErrorKind::Malformed),
),
(
r#"f == "x""#,
br#"{"f":"x\q"}"#,
Outcome::Error(ErrorKind::Malformed),
),
(
"f == 1",
br#"{"f":tru}"#,
Outcome::Error(ErrorKind::Malformed),
),
("f == 1", br#"{"f":1,"g":1"#, Outcome::True),
("f == 1", br#"{"g":1,"f":1"#, Outcome::True),
(
"f == 1 && g == 1",
br#"{"g":1,"f":1"#,
Outcome::Error(ErrorKind::Malformed),
),
(
"f == 1",
br#"{"g":1"#,
Outcome::Error(ErrorKind::MissingRoot),
),
(
"f == 1",
br#"{"g":"f","h":1}"#,
Outcome::Error(ErrorKind::MissingRoot),
),
(
"f == 1",
br#"{"g":"\u0041","h":1}"#,
Outcome::Error(ErrorKind::MissingRoot),
),
(
"f == 1",
br#"{"g":"\u0041","h":"#,
Outcome::Error(ErrorKind::Malformed),
),
(
"f == 1",
b"{\"g\":\"\xff\",\"f\":1}",
Outcome::Error(ErrorKind::Malformed),
),
("f == 1", b"{\"f\":1,\"g\":\"\xff\"}", Outcome::True),
(
"f == 1",
b"{\"\xff\":1}",
Outcome::Error(ErrorKind::MissingRoot),
),
(
"f == 1",
b"{\"f\":\"\xff\"}",
Outcome::Error(ErrorKind::Malformed),
),
(
"has(_table)",
b"{\"g\":\"\xff\",\"_table\":1}",
Outcome::Error(ErrorKind::Malformed),
),
("has(_table) || f == 1", br#"{"g":1,"f":1}"#, Outcome::True),
(
"f == 1",
br#"{"g":1}"#,
Outcome::Error(ErrorKind::MissingRoot),
),
("f == 1", b"x", Outcome::Error(ErrorKind::MissingRoot)),
("f == 1", b" ", Outcome::Error(ErrorKind::MissingRoot)),
(
"a.b.c == 1",
br#"{"a":{"b":"s"}}"#,
Outcome::Error(ErrorKind::MissingField),
),
(
"a.b == 1",
br#"{"a":[{"b":1}]}"#,
Outcome::Error(ErrorKind::MissingField),
),
(
"a.b.c == 1 || a.b == null",
br#"{"a":{"b":null}}"#,
Outcome::True,
),
(
"e.n == 9007199254740993",
br#"{"e":{"n":9007199254740993}}"#,
Outcome::True,
),
("e.n == 1.5", br#"{"e":{"n":15e-1}}"#, Outcome::True),
]);
}
#[test]
fn a_lone_root_key_is_read_by_its_root_members() {
use super::{ErrorKind, Outcome};
let late = format!(r#"{{"a":"{}","b":1,"s":"p"}}"#, "x".repeat(300));
raw_json_cases(&[
(r#"s == "p""#, late.as_bytes(), Outcome::True),
(r#"s == "p""#, br#"{"a":"s","s":"p"}"#, Outcome::True),
(
r#"s == "p""#,
br#"{"a":"x \"s\" y","s":"p"}"#,
Outcome::True,
),
(r#"s == "p""#, br#"{"a":{"s":"x"},"s":"p"}"#, Outcome::True),
(r#"s == "a""#, br#"{"s":"a","s":"b"}"#, Outcome::True),
(
r#"s == "p""#,
br#" { "a" : 1.5e3 , "b" : true , "s" : "p" } "#,
Outcome::True,
),
(
"s == 1",
"{\"a\":\"\u{e9}\",\"s\":1}".as_bytes(),
Outcome::True,
),
("s == 1", br#"{"a":"\q","s":1}"#, Outcome::True),
(
"s == 1",
br#"{"a":"\"s\"","b":1}"#,
Outcome::Error(ErrorKind::MissingRoot),
),
(
"s == 1",
br#"{"a":"\u0041"}"#,
Outcome::Error(ErrorKind::MissingRoot),
),
(
"s == 1",
br#"{"a":1 "s":1}"#,
Outcome::Error(ErrorKind::Malformed),
),
(
"s == 1",
br#"{"a":01,"s":1}"#,
Outcome::Error(ErrorKind::Malformed),
),
("s == 1", br#"{"s":1x}"#, Outcome::True),
("s == 1", br#"{"s":"#, Outcome::Error(ErrorKind::Malformed)),
("has(s)", br#"{"a":[1],"s":{"b":2}}"#, Outcome::True),
("has(s)", br#"{"s" :null}"#, Outcome::True),
(
"has(s)",
br#"{"s":nul}"#,
Outcome::Error(ErrorKind::Malformed),
),
(
"has(s)",
b"{\"s\":\"\xff\"}",
Outcome::Error(ErrorKind::Malformed),
),
(
"has(s)",
b"{\"s\":\"a\x01\"}",
Outcome::Error(ErrorKind::Malformed),
),
(
r#"s == "p""#,
br#"{"a":"0123456789012345678901234567890123456789 \"s\" \q","s":"p"}"#,
Outcome::True,
),
(
r#"s.endsWith("9\"")"#,
br#"{"s":"0123456789012345678901234567890123456789\""}"#,
Outcome::True,
),
(
"has(s)",
b"{\"s\":\"0123456789012345678901234567890123456789\x01\"}",
Outcome::Error(ErrorKind::Malformed),
),
]);
}
fn raw_json_cases(cases: &[(&str, &[u8], super::Outcome)]) {
use super::{Options, Program, ProgramSet};
use crate::record::Json;
let presence = Options {
root_presence: true,
..Options::default()
};
for (text, json, want) in cases {
let p = Program::compile_with(text, &presence).expect(text);
let on = String::from_utf8_lossy(json);
assert_eq!(p.eval(json), *want, "{text} on {on}");
assert_eq!(
p.eval_record(Json::new(json)),
*want,
"{text} lazily on {on}"
);
}
let texts: Vec<&str> = cases.iter().map(|&(t, _, _)| t).collect();
let set = ProgramSet::compile(&texts, &presence).expect("the set compiles");
let (mut one_pass, mut lazy) = (Vec::new(), Vec::new());
for (_, json, _) in cases {
set.matching(json, &mut one_pass);
set.matching_record(Json::new(json), &mut lazy);
assert_eq!(one_pass, lazy, "{}", String::from_utf8_lossy(json));
}
}
#[test]
fn lowering_refuses_what_it_cant_run() {
use super::{MAX_FIELDS, Program};
let wide = (0..=MAX_FIELDS)
.map(|i| format!("f{i} == 1"))
.collect::<Vec<_>>()
.join(" && ");
let long = format!("a{} == 1", ".b".repeat(30_000));
let long_has = format!("has(a{})", ".b".repeat(30_000));
for text in [
r#"host.matches("^prod-")"#,
"a < true",
"a >= null",
"size(a) < true",
"int(a) >= null",
"has(_table)",
"!has(a.b) || has(c)",
wide.as_str(),
long.as_str(),
long_has.as_str(),
] {
assert!(Program::compile(text).is_err(), "{text}");
}
#[cfg(not(feature = "expr-cel"))]
{
use super::{Fallback, Options, ProgramSet, ValueProgram};
let options = Options {
fallback: Fallback::Cel,
..Options::default()
};
let why = "Fallback::Cel, which runs only with the expr-cel feature";
let refused = Program::compile_with("a == b", &options).expect_err("needs cel");
assert_eq!(refused.why, why);
let refused = ValueProgram::compile_with("a * b", &options).expect_err("needs cel");
assert_eq!(refused.why, why);
let set = ProgramSet::compile(&["a == b"], &options).expect("compiles");
assert_eq!(set.refused()[0].1.why, why);
assert!(Program::compile_with(r#"a == "x""#, &options).is_ok());
}
for text in ["has(_table)", "! has( _table )", "!has(a.b) || has(c)"] {
let refusal = Program::compile(text).expect_err(text);
assert_eq!(&text[refusal.span.clone()], "has", "{text}: {refusal:?}");
}
let p = Program::compile(r#"!(a.b == "x" && c.contains("yz")) || d.startsWith("q")"#)
.expect("compiles");
assert_eq!(
p.to_string(),
r#"or(not(and(Eq(a.b, Str("x")), memmem(c, "yz"))), prefix(d, "q"))"#
);
let p = Program::compile("size(a.x) > 3 || 1 == int(b)").expect("compiles");
assert_eq!(
p.to_string(),
"or(Gt(size(a.x), Int(3)), Eq(int(b), Int(1)))"
);
}