use super::lex::{self, Tok};
use super::parse::{Ast, Cmp, Lit, Method, Path, parse};
fn path(p: &str) -> Path {
Path(p.split('.').map(str::to_owned).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)),
(
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()]),
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()]),
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)] = &[
("a.size() > 3", "size"),
("size(a) > 3", "size"),
("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}"
);
}
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),
]);
}
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(" && ");
for text in [
r#"host.matches("^prod-")"#,
"a < true",
"a >= null",
"has(_table)",
"!has(a.b) || has(c)",
wide.as_str(),
] {
assert!(Program::compile(text).is_err(), "{text}");
}
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"))"#
);
}