use std::borrow::Cow;
use std::collections::HashMap;
use proptest::prelude::*;
use serde_json::{Map, Number, Value as Json, json};
use super::{Options, Outcome, Program, ProgramSet, Value, ValueProgram};
use crate::record::{Miss, Record, Typed};
fn json_to_cel(json: &Json) -> cel::Value {
match json {
Json::Null => cel::Value::Null,
Json::Bool(b) => cel::Value::Bool(*b),
Json::Number(n) => n.as_i64().map_or_else(
|| {
n.as_u64().map_or_else(
|| cel::Value::Float(n.as_f64().unwrap_or(0.0)),
cel::Value::UInt,
)
},
cel::Value::Int,
),
Json::String(s) => cel::Value::String(s.clone().into()),
Json::Array(a) => cel::Value::List(a.iter().map(json_to_cel).collect::<Vec<_>>().into()),
Json::Object(o) => {
let map: HashMap<cel::objects::Key, cel::Value> = o
.iter()
.map(|(k, v)| (k.clone().into(), json_to_cel(v)))
.collect();
cel::Value::Map(map.into())
}
}
}
#[derive(Debug, Clone, Copy)]
struct Lazy<'a>(crate::record::Json<'a>);
impl<'a> Record<'a> for Lazy<'a> {
type At = &'a str;
fn find<K: AsRef<str>>(self, path: &[K]) -> Result<&'a str, Miss> {
self.0.find(path)
}
fn find_below<K: AsRef<str>>(self, at: &'a str, path: &[K]) -> Result<&'a str, Miss> {
self.0.find_below(at, path)
}
fn typed(self, at: &'a str) -> Result<Typed<'a>, Miss> {
self.0.typed(at)
}
fn typed_exact(self, at: &'a str) -> Result<Typed<'a>, Miss> {
self.0.typed_exact(at)
}
fn text(self, at: &'a str) -> Result<Cow<'a, str>, Miss> {
self.0.text(at)
}
}
fn cel_says(text: &str, record: &Json) -> Option<bool> {
let program = cel::Program::compile(text).unwrap_or_else(|e| panic!("cel rejects {text}: {e}"));
let mut ctx = cel::Context::default();
if let Json::Object(roots) = record {
for (k, v) in roots {
ctx.add_variable_from_value(k.clone(), json_to_cel(v));
}
}
match program.execute(&ctx) {
Ok(cel::Value::Bool(b)) => Some(b),
Ok(other) => panic!("{text} gave {other:?}, not a bool"),
Err(_) => None,
}
}
fn agree(text: &str, record: &Json) -> Result<(), TestCaseError> {
agree_with(text, record, &Options::with_regex())
}
fn agree_with(text: &str, record: &Json, options: &Options) -> Result<(), TestCaseError> {
let program = Program::compile_with(text, options)
.map_err(|r| TestCaseError::fail(format!("{text}: {r}")))?;
let bytes = serde_json::to_vec(record).map_err(|e| TestCaseError::fail(e.to_string()))?;
let ours = match program.eval(&bytes) {
Outcome::True => Some(true),
Outcome::False => Some(false),
Outcome::Error(_) => None,
};
prop_assert_eq!(ours, cel_says(text, record), "{} on {}", text, record);
prop_assert_eq!(
program.eval_record(Lazy(crate::record::Json::new(&bytes))),
program.eval(&bytes),
"{} read by sonic-rs lookups on {}",
text,
record
);
let pretty =
serde_json::to_vec_pretty(record).map_err(|e| TestCaseError::fail(e.to_string()))?;
prop_assert_eq!(
program.eval(&pretty),
program.eval(&bytes),
"{} on pretty {}",
text,
record
);
#[cfg(feature = "expr-cel")]
{
let cel = Program::compile_cel(text, options)
.map_err(|r| TestCaseError::fail(format!("cel: {text}: {r}")))?;
let (lowered, fallback) = (program.eval(&bytes), cel.eval(&bytes));
let agree = match (lowered, fallback) {
(Outcome::Error(a), Outcome::Error(b)) => same_kind(text, a, b),
(a, b) => a == b,
};
prop_assert!(
agree,
"{} on {}: lowered {:?}, cel's fallback {:?}",
text,
record,
lowered,
fallback
);
}
Ok(())
}
#[cfg(feature = "expr-cel")]
fn same_kind(text: &str, lowered: super::ErrorKind, fallback: super::ErrorKind) -> bool {
use super::ErrorKind;
lowered == fallback
|| (lowered == ErrorKind::TypeMismatch
&& fallback == ErrorKind::MissingField
&& text.contains("has("))
}
const PATHS: &[&str] = &["a", "b", "a.x", "a.y", "b.x", "c.x.y"];
fn path() -> impl Strategy<Value = &'static str> {
prop::sample::select(PATHS)
}
fn literal() -> impl Strategy<Value = &'static str> {
prop::sample::select(
&[
r#""""#,
r#""q""#,
r#""query""#,
r#""answer""#,
r#""Qé""#,
r#""a\nb""#,
r"'q'",
r#"r"q""#,
"0",
"1",
"-1",
"5158",
"9223372036854775807",
"1u",
"18446744073709551615u",
"1.0",
"-0.0",
"0.5",
"5158.0",
"9007199254740992.0",
"1e3",
"true",
"false",
"null",
][..],
)
}
fn ordered_literal() -> impl Strategy<Value = &'static str> {
literal().prop_filter("no ordering on bool or null", |l| {
!matches!(*l, "true" | "false" | "null")
})
}
fn string_arg() -> impl Strategy<Value = &'static str> {
prop::sample::select(
&[
r#""""#, r#""q""#, r#""que""#, r#""ery""#, r#""é""#, r#""x""#, r#""\n""#,
][..],
)
}
fn leaf() -> impl Strategy<Value = String> {
prop_oneof![
(path(), prop::sample::select(&["x", "y"][..])).prop_map(|(p, k)| format!("has({p}.{k})")),
(path(), prop::sample::select(&["==", "!="][..]), literal())
.prop_map(|(p, op, l)| format!("{p} {op} {l}")),
(
path(),
prop::sample::select(&["<", "<=", ">", ">="][..]),
ordered_literal()
)
.prop_map(|(p, op, l)| format!("{p} {op} {l}")),
(literal(), path()).prop_map(|(l, p)| format!("{l} == {p}")),
(
path(),
prop::sample::select(&["startsWith", "endsWith", "contains"][..]),
string_arg()
)
.prop_map(|(p, m, s)| format!("{p}.{m}({s})")),
(path(), literal(), literal()).prop_map(|(p, l1, l2)| format!("{p} in [{l1}, {l2}]")),
(path(), pattern()).prop_map(|(p, re)| format!("{p}.matches({re})")),
(
prop::sample::select(&["size({})", "{}.size()", "int({})"][..]),
path(),
prop::sample::select(&["==", "!=", "<", "<=", ">", ">="][..]),
count_literal(),
)
.prop_map(|(f, p, op, l)| format!("{} {op} {l}", f.replace("{}", p))),
]
}
fn count_literal() -> impl Strategy<Value = &'static str> {
prop::sample::select(
&[
"0", "1", "2", "3", "-2", "42", "-7", "5158", "1u", "2.0", "2.5", r#""q""#,
][..],
)
}
fn pattern() -> impl Strategy<Value = &'static str> {
prop::sample::select(
&[
r#""""#,
r#""q""#,
r#""^q""#,
r#""y$""#,
r#""^qu.*y$""#,
r#""(?i)QUERY""#,
r#""\\d+""#,
r#""é""#,
r#"".""#,
r#""an|qu""#,
r#""^$""#,
r#""^a\nb$""#,
r#""[a-z]{5}""#,
][..],
)
}
fn expr() -> impl Strategy<Value = String> {
leaf().prop_recursive(3, 12, 3, |inner| {
prop_oneof![
(inner.clone(), inner.clone()).prop_map(|(a, b)| format!("({a} && {b})")),
(inner.clone(), inner.clone()).prop_map(|(a, b)| format!("({a} || {b})")),
inner.prop_map(|a| format!("!({a})")),
]
})
}
fn scalar() -> impl Strategy<Value = Json> {
prop_oneof![
prop::sample::select(
&[
"",
"q",
"query",
"answer",
"Q\u{e9}",
"a\nb",
"xqueryx",
"é",
"\u{1f600}",
"e\u{301}",
"42",
"-7",
"+3",
" 1",
"1.5",
"9223372036854775808"
][..]
)
.prop_map(|s| Json::String(s.to_owned())),
prop::sample::select(&[0_i64, 1, -1, 5158, i64::MAX, i64::MIN, 3][..])
.prop_map(|n| json!(n)),
prop::sample::select(&[9_223_372_036_854_775_808_u64, u64::MAX][..]).prop_map(|n| json!(n)),
prop::sample::select(
&[
1.0_f64,
-0.0,
0.5,
5158.0,
9_007_199_254_740_992.0,
1e3,
-2.5,
42.9,
1e19,
9_223_372_036_854_775_808.0,
-9_223_372_036_854_775_808.0,
][..]
)
.prop_map(|f| Number::from_f64(f).map_or(Json::Null, Json::Number)),
any::<bool>().prop_map(Json::Bool),
Just(Json::Null),
prop::collection::vec(prop::sample::select(&["q", "x", "query"][..]), 0..3)
.prop_map(|v| json!(v)),
]
}
fn object(depth: u32) -> BoxedStrategy<Json> {
let value = if depth == 0 {
scalar().boxed()
} else {
prop_oneof![3 => scalar(), 2 => object(depth - 1)].boxed()
};
prop::collection::vec((prop::sample::select(&["x", "y", "q"][..]), value), 0..3)
.prop_map(|kvs| {
Json::Object(
kvs.into_iter()
.map(|(k, v)| (k.to_owned(), v))
.collect::<Map<_, _>>(),
)
})
.boxed()
}
fn record() -> impl Strategy<Value = Json> {
let root = prop_oneof![2 => scalar(), 3 => object(2)];
prop::collection::vec((prop::sample::select(&["a", "b", "c"][..]), root), 0..4).prop_map(
|kvs| {
Json::Object(
kvs.into_iter()
.map(|(k, v)| (k.to_owned(), v))
.collect::<Map<_, _>>(),
)
},
)
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(4096))]
#[test]
fn a_lowered_program_gives_what_cel_gives(text in expr(), rec in record()) {
agree(&text, &rec)?;
}
}
#[test]
fn named_cases_agree_with_cel() {
let dns = r#"event.network.direction == "outbound" && event.dns.type == "query""#;
let either = r#"event.dns.type == "query" || event.dns.type == "answer""#;
let neither = r#"!(event.network.direction == "outbound" && event.dns.type == "answer")"#;
let records = [
json!({}),
json!({"event": {}}),
json!({"event": {"network": {"direction": "outbound"}, "dns": {"type": "query"}}}),
json!({"event": {"network": {"direction": "inbound"}, "dns": {"type": "answer"}}}),
json!({"event": {"dns": {"type": "answer"}}}),
json!({"event": null}),
json!({"event": 3}),
json!({"event": {"dns": {"type": 7}}}),
json!({"f": 123}),
json!({"f": "123"}),
json!({"f": null}),
json!({"f": 9_007_199_254_740_993_u64}),
json!({"f": "a\u{0061}"}),
json!({"a": {}}),
json!({"a": {"b": null}}),
json!({"a": []}),
json!({"a": ["x", "q"]}),
json!({"a": {"x": 1}}),
];
let exprs = [
dns,
either,
neither,
r#"f == "123""#,
r#"f != "123""#,
r#"!(f == "x")"#,
r#"!f.startsWith("1")"#,
r#"f.contains("2")"#,
"f == 9007199254740992.0",
"f > 3",
"f >= 1u",
r#"f == "aa""#,
"has(a.b)",
"!has(a.b)",
r#"a.contains("x")"#,
r#"a.contains("q") || f == null"#,
r#"f in ["123", 123]"#,
"true && f == 1",
];
for text in exprs {
for rec in &records {
if let Err(e) = agree(text, rec) {
panic!("{e}");
}
}
}
}
#[test]
fn size_and_int_edges_agree_with_cel() {
use super::ErrorKind;
let error = Outcome::Error;
let cases: &[(&str, Json, Outcome)] = &[
("size(s) == 2", json!({"s": "\u{e9}\u{e9}"}), Outcome::True),
("size(s) == 4", json!({"s": "\u{e9}\u{e9}"}), Outcome::False),
("s.size() == 1", json!({"s": "\u{1f600}"}), Outcome::True),
("s.size() == 4", json!({"s": "\u{1f600}"}), Outcome::False),
("size(s) == 2", json!({"s": "e\u{301}"}), Outcome::True),
(
"size(s) == 2",
json!({"s": "\u{1f600}\u{10ffff}"}),
Outcome::True,
),
("size(s) == 2", json!({"s": "a\u{0}"}), Outcome::True),
("size(s) == 0", json!({"s": ""}), Outcome::True),
("size(l) == 0", json!({"l": []}), Outcome::True),
("size(m) == 0", json!({"m": {}}), Outcome::True),
(
"size(l) == 3",
json!({"l": [1, [2, 3], {"a": 4}]}),
Outcome::True,
),
(
"size(m.n) > 1",
json!({"m": {"n": {"a": 1, "b": [], "c": null}}}),
Outcome::True,
),
("size(s) == 0", json!({}), error(ErrorKind::MissingRoot)),
(
"size(m.s) == 0",
json!({"m": {}}),
error(ErrorKind::MissingField),
),
(
"size(n) == 0",
json!({"n": null}),
error(ErrorKind::TypeMismatch),
),
(
"size(n) == 1",
json!({"n": 7}),
error(ErrorKind::TypeMismatch),
),
("int(s) == 42", json!({"s": "42"}), Outcome::True),
("int(s) == 3", json!({"s": "+3"}), Outcome::True),
(
"int(s) == 0",
json!({"s": ""}),
error(ErrorKind::Conversion),
),
(
"int(s) == 1",
json!({"s": " 1"}),
error(ErrorKind::Conversion),
),
(
"int(s) == 1",
json!({"s": "1.5"}),
error(ErrorKind::Conversion),
),
(
"int(s) > 0",
json!({"s": "abc"}),
error(ErrorKind::Conversion),
),
(
"int(s) > 0",
json!({"s": "9223372036854775808"}),
error(ErrorKind::Conversion),
),
("int(d) == 2", json!({"d": 2.9}), Outcome::True),
("int(d) == -2", json!({"d": -2.9}), Outcome::True),
("int(d) > 0", json!({"d": 1e19}), error(ErrorKind::Overflow)),
(
"int(d) > 0",
json!({"d": 9_223_372_036_854_775_808.0}),
error(ErrorKind::Overflow),
),
(
"int(d) < 0",
json!({"d": -9_223_372_036_854_775_808.0}),
error(ErrorKind::Overflow),
),
(
"int(u) > 0",
json!({"u": u64::MAX}),
error(ErrorKind::Overflow),
),
("int(i) == -1", json!({"i": -1}), Outcome::True),
(
"int(b) == 1",
json!({"b": true}),
error(ErrorKind::TypeMismatch),
),
(
"int(l) == 1",
json!({"l": [1]}),
error(ErrorKind::TypeMismatch),
),
("int(x) == 1", json!({}), error(ErrorKind::MissingRoot)),
(r#"int(s) == "42""#, json!({"s": "42"}), Outcome::False),
("int(s) == 42u", json!({"s": "42"}), Outcome::True),
("size(s) > 1.5", json!({"s": "ab"}), Outcome::True),
(
"s == 1 || int(s) == 1",
json!({"s": "x"}),
error(ErrorKind::Conversion),
),
(
"size(s) == 1 || int(s) == 1",
json!({"s": "x"}),
Outcome::True,
),
];
for (text, record, want) in cases {
let program = Program::compile(text).expect(text);
let bytes = serde_json::to_vec(record).expect("serialises");
assert_eq!(program.eval(&bytes), *want, "{text} on {record}");
assert_eq!(
cel_says(text, record),
want_cel(*want),
"cel: {text} on {record}"
);
if let Err(e) = agree(text, record) {
panic!("{e}");
}
}
}
fn cel_value(text: &str, record: &Json) -> Option<cel::Value> {
let program = cel::Program::compile(text).unwrap_or_else(|e| panic!("cel rejects {text}: {e}"));
let mut ctx = cel::Context::default();
if let Json::Object(roots) = record {
for (k, v) in roots {
ctx.add_variable_from_value(k.clone(), json_to_cel(v));
}
}
program.execute(&ctx).ok()
}
fn as_cel(v: &Value<'_>) -> cel::Value {
match v {
Value::Str(s) => cel::Value::String(s.to_string().into()),
Value::Int(n) => cel::Value::Int(*n),
Value::Uint(n) => cel::Value::UInt(*n),
Value::Double(n) => cel::Value::Float(*n),
Value::Bool(b) => cel::Value::Bool(*b),
Value::Null => cel::Value::Null,
Value::Json(text) => json_to_cel(&serde_json::from_str(text).unwrap_or(Json::Null)),
}
}
fn agree_value(text: &str, record: &Json) -> Result<(), TestCaseError> {
agree_value_with(text, record, &Options::with_regex())
}
fn agree_value_with(text: &str, record: &Json, options: &Options) -> Result<(), TestCaseError> {
let program = ValueProgram::compile_with(text, options)
.map_err(|r| TestCaseError::fail(format!("{text}: {r}")))?;
let bytes = serde_json::to_vec(record).map_err(|e| TestCaseError::fail(e.to_string()))?;
let ours = program.eval(&bytes).ok().map(|v| as_cel(&v));
let lazy = program
.eval_record(Lazy(crate::record::Json::new(&bytes)))
.ok()
.map(|v| as_cel(&v));
prop_assert_eq!(
&lazy,
&ours,
"{} read by sonic-rs lookups on {}",
text,
record
);
#[cfg(feature = "expr-cel")]
{
let cel = ValueProgram::compile_cel(text, options)
.map_err(|r| TestCaseError::fail(format!("cel: {text}: {r}")))?;
let lowered = program.eval(&bytes).map(|v| as_cel(&v));
let fallback = cel.eval(&bytes).map(|v| as_cel(&v));
let agree = match (&lowered, &fallback) {
(Err(a), Err(b)) => same_kind(text, *a, *b),
(a, b) => a == b,
};
prop_assert!(
agree,
"{} on {}: lowered {:?}, cel's fallback {:?}",
text,
record,
lowered,
fallback
);
}
prop_assert_eq!(ours, cel_value(text, record), "{} on {}", text, record);
Ok(())
}
fn value_atom() -> impl Strategy<Value = String> {
prop_oneof![
path().prop_map(str::to_owned),
literal().prop_map(str::to_owned)
]
}
fn value_expr() -> impl Strategy<Value = String> {
prop_oneof![
value_atom(),
(value_atom(), value_atom()).prop_map(|(a, b)| format!("{a} + {b}")),
(expr(), value_atom(), value_atom()).prop_map(|(c, a, b)| format!("{c} ? {a} : {b}")),
(expr(), value_atom(), expr(), value_atom(), value_atom())
.prop_map(|(c1, a, c2, b, d)| format!("{c1} ? {a} : {c2} ? {b} : {d}")),
]
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(2048))]
#[test]
fn a_lowered_value_gives_what_cel_gives(text in value_expr(), rec in record()) {
agree_value(&text, &rec)?;
}
}
#[test]
fn computed_columns_agree_with_cel() {
let exprs = [
r#"risk_score > 80 ? "high" : risk_score > 40 ? "medium" : "low""#,
r#"src_ip.startsWith("10.") || src_ip.startsWith("192.168.")"#,
"bytes_in + bytes_out",
r#"value + "_enriched""#,
r#"risk_score > 90 ? "critical" : "ok""#,
];
let records = [
json!({}),
json!({"risk_score": 95, "src_ip": "10.0.0.1", "bytes_in": 10, "bytes_out": 20, "value": "v"}),
json!({"risk_score": 50.5, "src_ip": "8.8.8.8", "bytes_in": 10, "bytes_out": 2.5, "value": 3}),
json!({"risk_score": "high", "bytes_in": i64::MAX, "bytes_out": 1}),
json!({"bytes_in": [1], "bytes_out": [2, 3]}),
json!({"bytes_in": [1], "bytes_out": {"k": 1}}),
json!({"bytes_in": {"k": 1}, "bytes_out": [1]}),
json!({"bytes_in": {"k": 1}, "bytes_out": {"j": 1}}),
];
for text in exprs {
for rec in &records {
if let Err(e) = agree_value(text, rec) {
panic!("{e}");
}
}
}
}
fn agree_set(texts: &[String], record: &Json) -> Result<(), TestCaseError> {
let options = Options::with_regex();
let set =
ProgramSet::compile(texts, &options).map_err(|r| TestCaseError::fail(r.to_string()))?;
prop_assert!(set.refused().is_empty(), "{:?}", set.refused());
let bytes = serde_json::to_vec(record).map_err(|e| TestCaseError::fail(e.to_string()))?;
let alone: Vec<usize> = texts
.iter()
.enumerate()
.filter(|(_, t)| {
Program::compile_with(t, &options).is_ok_and(|p| p.eval(&bytes) == Outcome::True)
})
.map(|(i, _)| i)
.collect();
let (mut got, mut lazy) = (Vec::new(), Vec::new());
set.matching(&bytes, &mut got);
set.matching_record(Lazy(crate::record::Json::new(&bytes)), &mut lazy);
prop_assert_eq!(
&got,
&lazy,
"{:?} read by sonic-rs lookups on {}",
texts,
record
);
prop_assert_eq!(got, alone, "{:?} on {}", texts, record);
Ok(())
}
fn equals() -> impl Strategy<Value = String> {
(
path(),
prop::sample::select(&[r#""q""#, r#""query""#, r#""answer""#, r#""""#][..]),
)
.prop_map(|(p, l)| format!("{p} == {l}"))
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(1024))]
#[test]
fn a_set_matches_what_each_filter_matches_alone(
texts in prop::collection::vec(prop_oneof![3 => equals(), 1 => expr()], 1..30),
rec in record(),
) {
agree_set(&texts, &rec)?;
}
}
#[cfg(feature = "parse")]
fn flatten(record: &Json) -> crate::parse::Fields<'static> {
use crate::parse::{FieldSink, FieldValue, Fields, Hint};
fn put(name: &str, value: &Json, out: &mut Fields<'static>) {
let (bytes, hint) = match value {
Json::Object(map) if !map.is_empty() => {
for (k, v) in map {
put(&format!("{name}.{k}"), v, out);
}
return;
}
Json::String(s) => (s.clone().into_bytes(), Hint::Text),
Json::Number(n) if n.is_f64() => (n.to_string().into_bytes(), Hint::Float),
Json::Number(n) => (n.to_string().into_bytes(), Hint::Int),
Json::Bool(b) => (b.to_string().into_bytes(), Hint::Bool),
other => (other.to_string().into_bytes(), Hint::Json),
};
out.field(name, FieldValue::owned(bytes, hint));
}
let mut out = Fields::new();
if let Json::Object(map) = record {
for (k, v) in map {
put(k, v, &mut out);
}
}
out
}
#[cfg(feature = "parse")]
fn agree_on_fields(text: &str, value: &str, record: &Json) -> Result<(), TestCaseError> {
let options = Options::with_regex();
let bytes = serde_json::to_vec(record).map_err(|e| TestCaseError::fail(e.to_string()))?;
let fields = flatten(record);
let program = Program::compile_with(text, &options)
.map_err(|r| TestCaseError::fail(format!("{text}: {r}")))?;
prop_assert_eq!(
program.eval_record(&fields),
program.eval(&bytes),
"{} on {:?}",
text,
fields.as_slice()
);
let set =
ProgramSet::compile(&[text], &options).map_err(|r| TestCaseError::fail(r.to_string()))?;
let (mut ours, mut theirs) = (Vec::new(), Vec::new());
set.matching_record(&fields, &mut ours);
set.matching(&bytes, &mut theirs);
prop_assert_eq!(ours, theirs, "set of {} on {:?}", text, fields.as_slice());
let program = ValueProgram::compile_with(value, &options)
.map_err(|r| TestCaseError::fail(format!("{value}: {r}")))?;
let ours = program.eval_record(&fields).map(|v| as_cel(&v));
let theirs = program.eval(&bytes).map(|v| as_cel(&v));
prop_assert_eq!(ours, theirs, "{} on {:?}", value, fields.as_slice());
Ok(())
}
#[cfg(feature = "parse")]
proptest! {
#![proptest_config(ProptestConfig::with_cases(2048))]
#[test]
fn fields_give_what_their_json_gives(
text in expr(),
value in value_expr(),
rec in record(),
) {
agree_on_fields(&text, &value, &rec)?;
}
}
#[cfg(all(feature = "parse-syslog", feature = "parse-cef"))]
fn nest(fields: &crate::parse::Fields<'_>) -> Json {
use crate::parse::Hint;
let mut root = Map::new();
for (name, value) in fields.as_slice() {
let text = String::from_utf8(value.bytes.to_vec()).unwrap_or_default();
let leaf = match value.hint {
Hint::Json => serde_json::from_str(&text).unwrap_or(Json::Null),
Hint::Int | Hint::Float => serde_json::from_str::<Number>(&text)
.map_or_else(|_| Json::String(text.clone()), Json::Number),
Hint::Bool if text == "true" || text == "false" => Json::Bool(text == "true"),
_ => Json::String(text),
};
let keys: Vec<&str> = name.split('.').collect();
let Some((last, parents)) = keys.split_last() else {
continue;
};
let mut at = &mut root;
for key in parents {
let next = at
.entry((*key).to_owned())
.or_insert_with(|| Json::Object(Map::new()));
let Json::Object(map) = next else {
panic!("{name} runs below a value");
};
at = map;
}
match at.get_mut(*last) {
Some(Json::Array(items)) => items.push(leaf),
Some(first) => *first = Json::Array(vec![first.take(), leaf]),
None => {
at.insert((*last).to_owned(), leaf);
}
}
}
Json::Object(root)
}
#[cfg(all(feature = "parse-syslog", feature = "parse-cef"))]
#[test]
fn a_syslog_cef_chain_reads_as_its_json_record() {
use crate::format;
use crate::parse::{Fields, ParsePlan, Parsers};
use super::ErrorKind;
let mut registry = Parsers::new();
format::register_stock(&mut registry).expect("stock parsers register");
let plan = ParsePlan::chain("syslog > cef", ®istry).expect("the chain compiles");
let line =
b"<134>Oct 30 16:05:55 fw01 CEF:0|Acme|Gate|1.0|100|login ok|5|src=10.0.0.1 suser=bob";
let mut fields = Fields::new();
plan.parse_stateless(line, &mut fields);
let record = nest(&fields);
assert_eq!(record["cef"]["src"], json!("10.0.0.1"), "{record}");
assert_eq!(record["severity"], json!(6), "{record}");
let bytes = serde_json::to_vec(&record).expect("serialises");
let error = Outcome::Error;
let cases: &[(&str, Outcome)] = &[
(r#"cef.name == "login ok""#, Outcome::True),
(
r#"cef.src.startsWith("10.") && hostname == "fw01""#,
Outcome::True,
),
(r#"cef.suser in ["alice", "bob"]"#, Outcome::True),
(
r#"cef.device_vendor == "Acme" || cef.dst == "x""#,
Outcome::True,
),
(r#"cef.src.matches("^10\\.0\\.")"#, Outcome::True),
("severity == 6 && pri > 100", Outcome::True),
(r#"cef.severity == "5""#, Outcome::True),
("cef.severity == 5", Outcome::False),
(r#"cef == "x""#, Outcome::False),
("has(cef.suser) && !has(cef.dst)", Outcome::True),
("has(cef.dst)", Outcome::False),
("cef.severity > 3", error(ErrorKind::TypeMismatch)),
(r#"cef.contains("x")"#, error(ErrorKind::TypeMismatch)),
("has(cef.name.x)", error(ErrorKind::TypeMismatch)),
(r#"cef.dst == "x""#, error(ErrorKind::MissingField)),
("cef.name.x == 1", error(ErrorKind::MissingField)),
(r#"leef.src == "x""#, error(ErrorKind::MissingRoot)),
(r#"!has(cef.dst) || cef.dst == "x""#, Outcome::True),
];
let options = Options::with_regex();
for &(text, want) in cases {
let program = Program::compile_with(text, &options).expect(text);
assert_eq!(program.eval_record(&fields), want, "{text} on {record}");
assert_eq!(program.eval(&bytes), want, "{text} on the JSON {record}");
assert_eq!(
cel_says(text, &record),
want_cel(want),
"cel: {text} on {record}"
);
}
let presence = Options {
root_presence: true,
..Options::default()
};
for (text, want) in [("has(cef)", true), ("has(leef)", false)] {
let program = Program::compile_with(text, &presence).expect(text);
assert_eq!(program.matches_record(&fields), want, "{text}");
assert_eq!(program.matches(&bytes), want, "{text} on the JSON");
}
let texts: Vec<&str> = cases.iter().map(|(t, _)| *t).collect();
let set = ProgramSet::compile(&texts, &options).expect("the set compiles");
let (mut ours, mut theirs) = (Vec::new(), Vec::new());
set.matching_record(&fields, &mut ours);
set.matching(&bytes, &mut theirs);
assert_eq!(ours, theirs);
for value in [
r#"cef.src + ":" + cef.suser"#,
r#"severity > 3 ? "high" : "low""#,
"cef",
"pri + facility",
] {
let program = ValueProgram::compile(value).expect(value);
let ours = program.eval_record(&fields).map(|v| as_cel(&v));
assert_eq!(ours, program.eval(&bytes).map(|v| as_cel(&v)), "{value}");
assert_eq!(ours.ok(), cel_value(value, &record), "cel: {value}");
}
}
#[test]
fn a_raw_line_reads_as_its_message_field() {
use crate::record::Line;
use super::ErrorKind;
let line = "login denied for bob from 10.0.0.1";
let record = json!({ "message": line });
let bytes = serde_json::to_vec(&record).expect("serialises");
let error = Outcome::Error;
let cases: &[(&str, Outcome)] = &[
(r#"message.contains("denied")"#, Outcome::True),
(
r#"message.startsWith("login") && !message.endsWith("x")"#,
Outcome::True,
),
(r#"message.matches("from [0-9.]+$")"#, Outcome::True),
(r#"message == "login""#, Outcome::False),
("message > 3", error(ErrorKind::TypeMismatch)),
("has(message.x)", error(ErrorKind::TypeMismatch)),
(r#"msg.contains("denied")"#, error(ErrorKind::MissingRoot)),
(r#"message.x == "y""#, error(ErrorKind::MissingField)),
(r#"msg == "x" || message.contains("bob")"#, Outcome::True),
];
let options = Options::with_regex();
for &(text, want) in cases {
let program = Program::compile_with(text, &options).expect(text);
assert_eq!(
program.eval_record(Line::new(line.as_bytes())),
want,
"{text}"
);
assert_eq!(program.eval(&bytes), want, "{text} on the JSON");
assert_eq!(cel_says(text, &record), want_cel(want), "cel: {text}");
let renamed = Program::compile_with(&text.replace("message", "raw"), &options).expect(text);
assert_eq!(
renamed.eval_record(Line::named(line.as_bytes(), "raw")),
want,
"{text} on a line named raw"
);
}
let presence = Options {
root_presence: true,
..Options::default()
};
for (text, want) in [("has(message)", true), ("has(msg)", false)] {
let program = Program::compile_with(text, &presence).expect(text);
assert_eq!(
program.matches_record(Line::new(line.as_bytes())),
want,
"{text}"
);
assert_eq!(program.matches(&bytes), want, "{text} on the JSON");
}
let bad = Line::new(b"bad \xff byte");
let program = Program::compile(r#"message.contains("bad")"#).expect("compiles");
assert_eq!(program.eval_record(bad), error(ErrorKind::Malformed));
let value = ValueProgram::compile(r#"message + "!""#).expect("compiles");
assert_eq!(
value.eval_record(Line::new(b"up")),
Ok(Value::Str("up!".into()))
);
}
fn want_cel(outcome: Outcome) -> Option<bool> {
match outcome {
Outcome::True => Some(true),
Outcome::False => Some(false),
Outcome::Error(_) => None,
}
}
#[test]
fn conformance_expressions_agree_with_cel() {
use crate::shared_tests::corpus::{Join, Tally, for_each_record};
let mut tally = Tally::default();
for_each_record("cel", |r| {
let Ok(text) = std::str::from_utf8(r.bytes) else {
return;
};
let Some(ours) = tally.caught("cel", r, || {
Program::compile_with(text, &Options::with_regex())
.ok()
.map(|p| want_cel(p.eval(b"{}")))
}) else {
return;
};
tally.count("cel", r, ours.is_some());
let Some(ours) = ours else { return };
let theirs = std::panic::catch_unwind(|| {
let program = cel::Program::compile(text).ok()?;
match program.execute(&cel::Context::default()) {
Ok(cel::Value::Bool(b)) => Some(Some(b)),
Ok(_) => None,
Err(_) => Some(None),
}
})
.ok()
.flatten();
if let Some(theirs) = theirs
&& ours != theirs
{
tally.problem("cel", r, &format!("ours {ours:?}, cel {theirs:?}"));
}
});
let list = Join {
open: b"[",
sep: b", ",
close: b"]",
};
tally.scales_longest("cel", list, |input| {
if let Ok(text) = std::str::from_utf8(input) {
let _ = Program::compile_with(text, &Options::with_regex()).map(|p| p.eval(b"{}"));
}
});
tally.finish("cel");
}
#[test]
fn naughty_strings_count_code_points_as_cel_does() {
use crate::shared_tests::corpus::{Tally, for_each_record};
let mut tally = Tally::default();
let ran = for_each_record("naughty", |r| {
let Ok(line) = std::str::from_utf8(r.bytes) else {
return;
};
let record = json!({ "s": line });
let bytes = serde_json::to_vec(&record).expect("serialises");
let texts = [
format!("size(s) == {}", line.chars().count()),
format!("s.size() == {}", line.len()),
format!("size(s) > {}", line.chars().count().saturating_sub(1)),
"size(s) < 2".to_owned(),
r#"s.contains("é")"#.to_owned(),
];
let differ = tally.caught("naughty size", r, || {
let mut differ = Vec::new();
for text in &texts {
let ours = want_cel(Program::compile(text).expect(text).eval(&bytes));
let theirs = cel_says(text, &record);
if ours != theirs {
differ.push(format!("{text}: ours {ours:?}, cel {theirs:?}"));
}
}
differ
});
for detail in differ.into_iter().flatten() {
tally.problem("naughty size", r, &detail);
}
});
assert!(ran > 100, "{ran} naughty strings ran");
tally.finish("naughty size");
}
#[derive(Debug, Clone, Copy)]
struct OneDouble(f64);
impl<'a> Record<'a> for OneDouble {
type At = ();
fn find<K: AsRef<str>>(self, path: &[K]) -> Result<(), Miss> {
match path {
[] => Err(Miss::MissingRoot),
[k] if k.as_ref() == "v" => Ok(()),
_ => Err(Miss::MissingField),
}
}
fn find_below<K: AsRef<str>>(self, (): (), path: &[K]) -> Result<(), Miss> {
if path.is_empty() {
Ok(())
} else {
Err(Miss::WrongParentType)
}
}
fn typed(self, (): ()) -> Result<Typed<'a>, Miss> {
Ok(Typed::Double(self.0))
}
fn typed_exact(self, (): ()) -> Result<Typed<'a>, Miss> {
self.typed(())
}
fn text(self, (): ()) -> Result<Cow<'a, str>, Miss> {
Ok(Cow::Owned(self.0.to_string()))
}
}
#[test]
fn a_nan_orders_false_as_cel_does() {
for value in [f64::NAN, -f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1.5] {
let mut ctx = cel::Context::default();
ctx.add_variable_from_value("v", cel::Value::Float(value));
for op in ["<", "<=", ">", ">=", "==", "!="] {
for lit in ["1", "1u", "1.5", "-1", "0.0", r#""a""#] {
for expr in [format!("v {op} {lit}"), format!("{lit} {op} v")] {
let ours = Program::compile(&expr)
.expect(&expr)
.eval_record(OneDouble(value));
let theirs = match cel::Program::compile(&expr).expect(&expr).execute(&ctx) {
Ok(cel::Value::Bool(b)) => Some(b),
Ok(other) => panic!("{expr} gave {other:?}"),
Err(_) => None,
};
assert_eq!(want_cel(ours), theirs, "{expr} with v {value}");
#[cfg(feature = "expr-cel")]
assert_eq!(
Program::compile_cel(&expr, &Options::default())
.expect(&expr)
.eval_record(OneDouble(value)),
ours,
"{expr} with v {value} on cel's fallback"
);
}
}
}
}
}
#[test]
fn a_list_plus_a_map_is_an_error_as_cel_gives() {
let record = json!({"a": [1], "b": {"k": 1}});
for text in ["a + b", "b + a", "a + a", "b + b"] {
if let Err(e) = agree_value(text, &record) {
panic!("{e}");
}
}
let bytes = br#"{"a":[1],"b":{"k":1}}"#;
let program = ValueProgram::compile("a + b").expect("compiles");
assert_eq!(program.eval(bytes), Err(super::ErrorKind::TypeMismatch));
}
#[test]
fn operator_nesting_compiles_as_cel_compiles() {
fn chain(term: &str, operators: usize) -> String {
format!("{term}{}", format!(" + {term}").repeat(operators))
}
type Shape = Box<dyn Fn(usize) -> String>;
let shapes: Vec<(&str, Shape)> = vec![
("a chain", Box::new(|n| chain("a", n))),
("a chain of paths", Box::new(|n| chain("a.b.c", n))),
(
"a chain in parentheses",
Box::new(|n| format!("({}) + a", chain("a", n))),
),
(
"a chain as a term",
Box::new(|n| format!("a + ({})", chain("a", n))),
),
(
"a chain in a ternary",
Box::new(|n| format!("a == 1 ? {} : 1", chain("a", n))),
),
(
"a chain after a ternary",
Box::new(|n| format!("a == 1 ? 1 : {}", chain("a", n))),
),
];
for (name, shape) in &shapes {
for n in 88..=100 {
let text = shape(n);
let ours = ValueProgram::compile(&text);
let theirs = cel::Program::compile(&text);
assert_eq!(
ours.is_ok(),
theirs.is_ok(),
"{name} of {n} operators: {text}"
);
}
}
let refused = ValueProgram::compile(&chain("a", 97)).expect_err("97 operators");
assert_eq!(refused.why, "operators nested deeper than cel compiles");
}
#[test]
fn a_root_key_holding_a_dot_reads_as_a_qualified_name() {
let a = [
None,
Some(json!({})),
Some(json!({"x": 2})),
Some(json!({"x": {"y": 2}})),
Some(json!(5)),
];
let ax = [None, Some(json!(1)), Some(json!({"y": 3})), Some(json!({}))];
let axy = [None, Some(json!(1))];
let tests = [
"a.x == 1",
"a.x == 2",
"a.x.y == 1",
"a.x.y == 2",
"a.x.y == 3",
"has(a.x)",
"has(a.x.y)",
"size(a.x) == 1",
r#"a["x"] == 1"#,
r#"a["x"].y == 2"#,
r#"a.x["y"] == 3"#,
];
let values = ["a.x", "a.x.y", r#"a.x["y"]"#];
let mut options = Options::with_regex();
options.dotted_root_keys = true;
let mut rows = 0;
for a in &a {
for ax in &ax {
for axy in &axy {
let mut record = Map::new();
for (key, value) in [("a", a), ("a.x", ax), ("a.x.y", axy)] {
if let Some(v) = value {
record.insert(key.to_owned(), v.clone());
}
}
let record = Json::Object(record);
for text in tests {
if let Err(e) = agree_with(text, &record, &options) {
panic!("{e}");
}
rows += 1;
}
for text in values {
if let Err(e) = agree_value_with(text, &record, &options) {
panic!("{e}");
}
rows += 1;
}
}
}
}
assert_eq!(rows, 560);
let both = br#"{"a.x": 1, "a": {"x": 2}}"#;
assert!(Program::compile("a.x == 2").expect("lowers").matches(both));
}
#[test]
fn nesting_compiles_where_cel_does() {
std::thread::Builder::new()
.stack_size(256 << 20)
.spawn(nesting_against_cel)
.unwrap()
.join()
.unwrap();
}
fn nesting_against_cel() {
type Form = fn(usize) -> String;
let forms: [(&str, Form); 10] = [
("parens round a field", |n| {
format!("{}a{}", "(".repeat(n), ")".repeat(n))
}),
("parens round a test", |n| {
format!("{}a == 1{}", "(".repeat(n), ")".repeat(n))
}),
("parens round a sum", |n| {
format!("{}a + 1{}", "(".repeat(n), ")".repeat(n))
}),
("nots", |n| format!("{}true", "!".repeat(n))),
("nots in parens", |n| {
format!("{}a == 1{}", "!(".repeat(n), ")".repeat(n))
}),
("nots then parens", |n| {
format!("{}{}a == 1{}", "!".repeat(n), "(".repeat(n), ")".repeat(n))
}),
("else chain", |n| format!("{}0", "a == 1 ? 1 : ".repeat(n))),
("then chain", |n| {
format!("{}1{}", "a == 1 ? ".repeat(n), " : 0".repeat(n))
}),
("then in parens", |n| {
format!("{}1{}", "a == 1 ? (".repeat(n), "): 0".repeat(n))
}),
("else in parens", |n| {
format!("{}0{}", "a == 1 ? 1 : (".repeat(n), ")".repeat(n))
}),
];
let mut wrong = Vec::new();
for (name, form) in forms {
let mut from = None;
for n in 1..=121 {
let text = form(n);
let theirs = cel::Program::compile(&text).is_ok();
let ours = ValueProgram::compile(&text).is_ok();
match (ours == theirs, from) {
(false, None) => from = Some((n, ours, theirs)),
(true, Some((a, ours, theirs))) => {
wrong.push(format!(
"{name} at {a}..{}: ours {ours}, cel {theirs}",
n - 1
));
from = None;
}
_ => {}
}
}
if let Some((a, ours, theirs)) = from {
wrong.push(format!("{name} from {a}: ours {ours}, cel {theirs}"));
}
}
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
let nots = format!("{}true", "!".repeat(30_000));
assert!(
cel::Program::compile(¬s).is_ok(),
"cel reads any run of `!`s"
);
}
#[test]
fn deep_nesting_is_refused() {
for text in [
format!("{}a{}", "(".repeat(30_000), ")".repeat(30_000)),
format!("{}0", "a == 1 ? 1 : ".repeat(30_000)),
format!("{}1{}", "a == 1 ? (".repeat(30_000), "): 0".repeat(30_000)),
format!("{}a == 1{}", "!(".repeat(30_000), ")".repeat(30_000)),
] {
assert!(ValueProgram::compile(&text).is_err());
assert!(Program::compile(&text).is_err());
}
let nots = format!("{}true", "!".repeat(30_000));
assert!(Program::compile(¬s).is_ok());
}
#[cfg(feature = "expr-cel")]
fn refused_leaf() -> impl Strategy<Value = String> {
let ops = prop::sample::select(&["==", "!=", "<", ">="][..]);
let macros = prop::sample::select(
&[
"$p.exists(t, t == $l)",
"$p.all(t, t != $l)",
"$p.exists_one(t, t == $l)",
"size($p.filter(t, t == $l)) == 1",
"$p.map(t, t == $l).exists(t, t)",
"$l in $p",
"$p + 1 > 2",
r#"$p + "x" == "qx""#,
"size($p) + 1 == 2",
"$p == 1 ? true : $p == $l",
"uint($p) > 0u",
"double($p) > 0.5",
"string($p) == $l",
"type($p) == string",
"[$p][0] == $l",
r#"{"k": $p}.k == $l"#,
r#"matches($p, "q")"#,
"has($p) || $p == $l",
][..],
);
prop_oneof![
(path(), ops, path()).prop_map(|(a, op, b)| format!("{a} {op} {b}")),
(macros, path(), literal()).prop_map(|(m, p, l)| m.replace("$p", p).replace("$l", l)),
]
}
#[cfg(feature = "expr-cel")]
fn mixed_expr() -> impl Strategy<Value = String> {
prop_oneof![2 => refused_leaf(), 1 => leaf()].prop_recursive(2, 8, 3, |inner| {
prop_oneof![
(inner.clone(), inner.clone()).prop_map(|(a, b)| format!("({a} && {b})")),
(inner.clone(), inner.clone()).prop_map(|(a, b)| format!("({a} || {b})")),
inner.prop_map(|a| format!("!({a})")),
]
})
}
#[cfg(feature = "expr-cel")]
fn fallback_agrees(text: &str, record: &Json) -> Result<(), TestCaseError> {
use super::Engine;
let mut options = Options::with_regex();
options.fallback = super::Fallback::Cel;
let theirs = cel::Program::compile(text)
.ok()
.map(|_| cel_says(text, record));
let Some(theirs) = theirs else {
prop_assert!(Program::compile_with(text, &options).is_err(), "{}", text);
return Ok(());
};
let program = Program::compile_with(text, &options)
.map_err(|r| TestCaseError::fail(format!("{text}: {r}")))?;
let bytes = serde_json::to_vec(record).map_err(|e| TestCaseError::fail(e.to_string()))?;
let ours = program.eval(&bytes);
prop_assert_eq!(want_cel(ours), theirs, "{} on {}", text, record);
if program.engine() == Engine::Cel {
prop_assert_eq!(
program.eval_record(Lazy(crate::record::Json::new(&bytes))),
ours,
"{} read by lookups on {}",
text,
record
);
let pretty =
serde_json::to_vec_pretty(record).map_err(|e| TestCaseError::fail(e.to_string()))?;
prop_assert_eq!(program.eval(&pretty), ours, "{} on pretty {}", text, record);
#[cfg(feature = "parse")]
prop_assert_eq!(
program.eval_record(&flatten(record)),
ours,
"{} on the fields of {}",
text,
record
);
}
Ok(())
}
#[cfg(feature = "expr-cel")]
proptest! {
#![proptest_config(ProptestConfig::with_cases(2048))]
#[test]
fn a_refused_form_runs_on_cel_as_cel_gives(text in mixed_expr(), rec in record()) {
fallback_agrees(&text, &rec)?;
}
}
#[cfg(feature = "expr-cel")]
#[test]
fn named_refused_forms_agree_with_cel() {
use super::{Engine, ErrorKind};
let records = [
json!({}),
json!({"tags": ["q", "x"], "a": 3, "b": 4}),
json!({"tags": [], "a": "3", "b": 3}),
json!({"tags": "q", "a": {"x": 1}, "b": {"x": 1}}),
json!({"event": {"dns": {"type": "query", "answers": [{"ip": "10.0.0.1"}, {"ip": "8.8.8.8"}]}}}),
json!({"event": {"dns": {"type": 7}}, "a": 1, "b": 1.0}),
json!({"bytes_in": 10, "bytes_out": 20, "limit": 25}),
];
let texts = [
r#"tags.exists(t, t == "q")"#,
r#"tags.all(t, t.startsWith("q"))"#,
r#"size(tags.filter(t, t == "x")) > 0"#,
"a == b",
"a < b",
"a.x == b.x",
"bytes_in + bytes_out > limit",
"bytes_in * 2 >= limit",
r#"event.dns.answers.exists(a, a.ip.startsWith("10."))"#,
r#"event.dns.type == "query" && event.dns.answers.all(a, has(a.ip))"#,
r#"event.dns.answers.map(a, a.ip)[0] == "10.0.0.1""#,
r#"has(event.dns) ? event.dns.type == "query" : false"#,
"tags[0] == \"q\"",
"1 / (a - a) == 0",
"undefined_fn(a)",
];
let mut options = Options::with_regex();
options.fallback = super::Fallback::Cel;
for text in texts {
assert!(Program::compile(text).is_err(), "{text} lowers");
let program = Program::compile_with(text, &options).expect(text);
assert_eq!(program.engine(), Engine::Cel, "{text}");
assert!(program.to_string().starts_with("cel("), "{program}");
for record in &records {
if let Err(e) = fallback_agrees(text, record) {
panic!("{e}");
}
}
}
let lowered = Program::compile_with(r#"a == "x""#, &options).expect("lowers");
assert_eq!(lowered.engine(), Engine::Lowered);
let error = |text: &str, json: &[u8]| {
Program::compile_with(text, &options)
.expect(text)
.eval(json)
};
let cases: &[(&str, &[u8], Outcome)] = &[
(
"a == b",
br#"{"b":1}"#,
Outcome::Error(ErrorKind::MissingRoot),
),
(
"a.x == b",
br#"{"a":{},"b":1}"#,
Outcome::Error(ErrorKind::MissingField),
),
(
"a.x == b",
br#"{"a":5,"b":1}"#,
Outcome::Error(ErrorKind::MissingField),
),
(
"a + 1 == b",
br#"{"a":"s","b":1}"#,
Outcome::Error(ErrorKind::TypeMismatch),
),
(
"a + 1 == b",
br#"{"a":9223372036854775807,"b":1}"#,
Outcome::Error(ErrorKind::Overflow),
),
(
"int(a) + 1 == b",
br#"{"a":"x","b":1}"#,
Outcome::Error(ErrorKind::Conversion),
),
(
"1 / (a - a) == b",
br#"{"a":1,"b":1}"#,
Outcome::Error(ErrorKind::Other),
),
(
"undefined_fn(a)",
br#"{"a":1}"#,
Outcome::Error(ErrorKind::Other),
),
(
"a + b",
br#"{"a":1,"b":1}"#,
Outcome::Error(ErrorKind::TypeMismatch),
),
(
"a == b",
br#"{"a":1,"b":"#,
Outcome::Error(ErrorKind::Malformed),
),
];
for &(text, json, want) in cases {
assert_eq!(
error(text, json),
want,
"{text} on {}",
String::from_utf8_lossy(json)
);
}
}
#[cfg(feature = "expr-cel")]
#[test]
fn the_fallback_refuses_what_cel_refuses() {
let mut options = Options {
fallback: super::Fallback::Cel,
..Options::default()
};
let refused = Program::compile_with("tags.exists(t, t ==", &options).expect_err("cel refuses");
assert_eq!(refused.why, "text cel doesn't compile");
let refused =
Program::compile_with(r#"tags.exists(t, t.matches("q"))"#, &options).expect_err("no regex");
assert_eq!(
refused.why,
"matches(), which runs only with Options::allow_regex"
);
assert_eq!(refused.span, 17..24);
options.allow_regex = true;
assert!(Program::compile_with(r#"tags.exists(t, t.matches("q"))"#, &options).is_ok());
let refused = Program::compile_with("has(x)", &options).expect_err("cel refuses has(x)");
assert_eq!(refused.why, "text cel doesn't compile");
}
#[cfg(feature = "expr-cel")]
#[test]
fn a_refused_value_gives_cels_value() {
use super::Engine;
let options = Options {
fallback: super::Fallback::Cel,
..Options::default()
};
let record = json!({"a": 2, "b": 3, "tags": ["q", "x"], "m": {"z": 1, "y": [true]}});
let bytes = serde_json::to_vec(&record).expect("serialises");
let rows: &[(&str, Value<'_>)] = &[
("a * b", Value::Int(6)),
("double(a) / 4.0", Value::Double(0.5)),
(
r#"tags.map(t, t + "!")"#,
Value::Json(r#"["q!","x!"]"#.into()),
),
(
r#"{"z": m.z, "y": m.y}"#,
Value::Json(r#"{"y":[true],"z":1}"#.into()),
),
(
r#"{"b": b, "a": a}"#,
Value::Json(r#"{"a":2,"b":3}"#.into()),
),
(r#"tags.exists(t, t == "q")"#, Value::Bool(true)),
("uint(a)", Value::Uint(2)),
(r#"string(a) + "x""#, Value::Str("2x".into())),
];
for (text, want) in rows {
assert!(ValueProgram::compile(text).is_err(), "{text} lowers");
let program = ValueProgram::compile_with(text, &options).expect(text);
assert_eq!(program.engine(), Engine::Cel);
assert_eq!(program.eval(&bytes).as_ref(), Ok(want), "{text}");
assert_eq!(
program.eval(&bytes).ok().map(|v| as_cel(&v)),
cel_value(text, &record),
"cel: {text}"
);
}
assert_eq!(
ValueProgram::compile_with("b'x'", &options)
.expect("compiles")
.eval(&bytes),
Err(super::ErrorKind::Other)
);
let keyed =
ValueProgram::compile_with(r#"{1: "a", "2": "b", true: "c"}"#, &options).expect("compiles");
assert_eq!(
keyed.eval(&bytes),
Ok(Value::Json(r#"{"1":"a","2":"b","true":"c"}"#.into()))
);
for text in [
r#"{1: "a", "1": "b"}"#,
r#"{true: 1, "true": 2}"#,
r#"{1: "a", 1u: "b"}"#,
] {
let program = ValueProgram::compile_with(text, &options).expect(text);
assert_eq!(program.eval(&bytes), Err(super::ErrorKind::Other), "{text}");
}
}
#[cfg(feature = "expr-cel")]
#[test]
fn a_set_runs_refused_rows_on_cel() {
let options = Options {
fallback: super::Fallback::Cel,
..Options::default()
};
let texts = [
r#"tags.exists(t, t == "q")"#,
r#"host == "h1""#,
"a < b",
"a ==",
r#"host.startsWith("h")"#,
];
let set = ProgramSet::compile(&texts, &options).expect("compiles");
assert_eq!(
set.refused().iter().map(|(i, _)| *i).collect::<Vec<_>>(),
[3]
);
let mut out = Vec::new();
set.matching(br#"{"tags":["q"],"host":"h1","a":1,"b":2}"#, &mut out);
assert_eq!(out, [0, 1, 2, 4]);
set.matching(br#"{"tags":[],"host":"x","a":3,"b":2}"#, &mut out);
assert!(out.is_empty(), "{out:?}");
}