use std::collections::BTreeMap;
use std::fmt::Write as _;
use proptest::prelude::*;
use serde_json::{Map, Number, Value};
use super::*;
#[derive(Debug, Clone, Copy)]
enum P {
Text(&'static str),
Keys(&'static [&'static str]),
Whole(&'static str),
Pointer(&'static str),
}
impl P {
fn path(self) -> Path {
match self {
Self::Text(text) => Path::parse(text).unwrap(),
Self::Keys(keys) => Path::from_keys(keys.iter().copied()).unwrap(),
Self::Whole(text) => Path::whole_key_first(text).unwrap(),
Self::Pointer(text) => Path::from_pointer(text).unwrap(),
}
}
}
const fn found(text: &'static str, kind: Kind) -> Slot<'static> {
Slot::Found(Raw {
text,
kind,
start: 0,
})
}
const fn bare(slot: Slot<'_>) -> Slot<'_> {
match slot {
Slot::Found(Raw { text, kind, .. }) => Slot::Found(Raw {
text,
kind,
start: 0,
}),
other => other,
}
}
const S: Kind = Kind::String;
const N: Kind = Kind::Number;
const O: Kind = Kind::Object;
const A: Kind = Kind::Array;
const B: Kind = Kind::Bool;
const Z: Kind = Kind::Null;
const KEY: Slot<'static> = Slot::MissingKey;
const BAD: Slot<'static> = Slot::Malformed;
const CASES: &[(&str, P, Slot<'static>)] = &[
(r#"{"a":{"b":"x"}}"#, P::Text("a.b"), found(r#""x""#, S)),
(r#"{"a":{"b":"x"}}"#, P::Text(r#"["a.b"]"#), KEY),
(r#"{"a":{"b":"x"}}"#, P::Whole("a.b"), found(r#""x""#, S)),
(r#"{"a.b":"x"}"#, P::Text(r#"["a.b"]"#), found(r#""x""#, S)),
(r#"{"a.b":"x"}"#, P::Text("a.b"), Slot::MissingParent(0)),
(r#"{"a.b":"x"}"#, P::Whole("a.b"), found(r#""x""#, S)),
(r#"{"a":{"b.c":1}}"#, P::Text(r#"a["b.c"]"#), found("1", N)),
(
r#"[{"message":"m"}]"#,
P::Pointer("/0/message"),
found(r#""m""#, S),
),
(
r#"{"data":[{"x":1}],"n":1}"#,
P::Pointer("/data"),
found(r#"[{"x":1}]"#, A),
),
(
r#"{"data":[{"x":1},{"x":2}]}"#,
P::Text("data[1].x"),
found("2", N),
),
(
r#"{"data":[{"x":1},{"x":2}]}"#,
P::Pointer("/data/1/x"),
found("2", N),
),
(r#"{"data":[1,2]}"#, P::Text("data[2]"), KEY),
(r#"{"data":[]}"#, P::Text("data[0]"), KEY),
(
r#"{"data":[]}"#,
P::Text("data[0].x"),
Slot::MissingParent(1),
),
(
r#"{"data":{"0":"k"}}"#,
P::Pointer("/data/0"),
found(r#""k""#, S),
),
(
r#"{"data":{"0":"k"}}"#,
P::Text("data[0]"),
Slot::WrongParentType(1),
),
(
r#"{"data":[5]}"#,
P::Text(r#"data["0"]"#),
Slot::WrongParentType(1),
),
(
r#"{"data":"x"}"#,
P::Pointer("/data/0"),
Slot::WrongParentType(1),
),
("[1, 2]", P::Text("[1]"), found("2", N)),
("[1,2]", P::Text("a"), Slot::WrongParentType(0)),
(r#"{"a":1}"#, P::Text("[0]"), Slot::WrongParentType(0)),
(r#"{"a":[[1,2],[3]]}"#, P::Text("a[0][1]"), found("2", N)),
(r#"{"a":[[1,2],[3]]}"#, P::Text("a[1][0]"), found("3", N)),
(
r#"{"a":[ "s" , {"b":[true]} ]}"#,
P::Text("a[1].b[0]"),
found("true", B),
),
(r#"{"a":[1,2"#, P::Text("a[0]"), found("1", N)),
(r#"{"a":[1"#, P::Text("a[0]"), BAD),
(r#"{"a":[1,"#, P::Text("a[1]"), BAD),
(r#"{"a":[1}"#, P::Text("a[1]"), BAD),
(r#"{"a/b":1,"m~n":2}"#, P::Pointer("/a~1b"), found("1", N)),
(r#"{"a/b":1,"m~n":2}"#, P::Pointer("/m~0n"), found("2", N)),
(r#"{"01":3}"#, P::Pointer("/01"), found("3", N)),
(r#"["x","y"]"#, P::Pointer("/01"), Slot::WrongParentType(0)),
(r#"["x","y"]"#, P::Pointer("/-"), Slot::WrongParentType(0)),
(r#"{"":4}"#, P::Pointer("/"), found("4", N)),
(r#"{"n":1.50}"#, P::Text("n"), found("1.50", N)),
(r#"{"n":-0}"#, P::Text("n"), found("-0", N)),
(r#"{"n":1E+3}"#, P::Text("n"), found("1E+3", N)),
(
r#"{"n":18446744073709551616}"#,
P::Text("n"),
found("18446744073709551616", N),
),
(r#"{"t":true}"#, P::Text("t"), found("true", B)),
(r#"{"f":false}"#, P::Text("f"), found("false", B)),
(r#"{"z":null}"#, P::Text("z"), found("null", Z)),
(r#"{"s":""}"#, P::Text("s"), found(r#""""#, S)),
(r#"{"o":{}}"#, P::Text("o"), found("{}", O)),
(r#"{"l":[]}"#, P::Text("l"), found("[]", A)),
(r#"{"s":"a\"b"}"#, P::Text("s"), found(r#""a\"b""#, S)),
(r#"{"\u0061":1}"#, P::Text("a"), found("1", N)),
(r#"{"a\"b":1}"#, P::Text(r#"["a\"b"]"#), found("1", N)),
(
r#"{"\ud83d\ude00":2}"#,
P::Keys(&["\u{1F600}"]),
found("2", N),
),
(r#"{"\/x":3}"#, P::Text("/x"), found("3", N)),
(r#"{"a\nb":4}"#, P::Keys(&["a\nb"]), found("4", N)),
(r#"{"\u00e9":5}"#, P::Keys(&["\u{e9}"]), found("5", N)),
(r#"{"\u00E9":5}"#, P::Keys(&["\u{e9}"]), found("5", N)),
(r#"{"\u0061bcdefgh":1,"a":2}"#, P::Text("a"), found("2", N)),
("{\"a\nb\":4}", P::Keys(&["a\nb"]), BAD),
(r#"{"\q":1}"#, P::Text("a"), BAD),
(r#"{"\ud800":1}"#, P::Text("a"), BAD),
(r#"{"\ud800\u0041":1}"#, P::Text("a"), BAD),
(r#"{"\udc00":1}"#, P::Text("a"), BAD),
("{ \"a\" :\t{\n\"b\" : 1 } }", P::Text("a.b"), found("1", N)),
(
"{ \"a\" :\t{\n\"b\" : 1 } }",
P::Text("a"),
found("{\n\"b\" : 1 }", O),
),
(" \r\n{\"a\":1}", P::Text("a"), found("1", N)),
(
r#"{"a":{"b":{"c":{"d":[1,{"e":2}]}}}}"#,
P::Text("a.b.c.d"),
found(r#"[1,{"e":2}]"#, A),
),
(
r#"{"a":{"b":{"c":{"d":[1,{"e":2}]}}}}"#,
P::Text("a.b.c.d.e"),
Slot::WrongParentType(4),
),
(
r#"{"a":[{"b":1}]}"#,
P::Text("a.b"),
Slot::WrongParentType(1),
),
(r#"{"a":"s"}"#, P::Text("a.b.c"), Slot::WrongParentType(1)),
(
r#"{"a":{"b":5}}"#,
P::Text("a.b.c"),
Slot::WrongParentType(2),
),
(r#"{"a":null}"#, P::Text("a.b"), Slot::WrongParentType(1)),
("[1]", P::Text("a"), Slot::WrongParentType(0)),
(r#""s""#, P::Text("a"), Slot::WrongParentType(0)),
("7", P::Text("a"), Slot::WrongParentType(0)),
(r#"{"x":1}"#, P::Text("a"), KEY),
(r#"{"x":1}"#, P::Text("a.b"), Slot::MissingParent(0)),
(r#"{"a":{}}"#, P::Text("a.b.c"), Slot::MissingParent(1)),
(r#"{"a":{}}"#, P::Text("a.b"), KEY),
("{}", P::Text("a"), KEY),
(r#"{"a":1,"a":2}"#, P::Text("a"), found("1", N)),
(
r#"{"a":{"b":1},"a":{"b":2}}"#,
P::Text("a.b"),
found("1", N),
),
(r#"{"a":{"x":1},"a":{"b":2}}"#, P::Text("a.b"), KEY),
(r#"{"\u0061":1,"a":2}"#, P::Text("a"), found("1", N)),
("", P::Text("a"), BAD),
(" ", P::Text("a"), BAD),
("x", P::Text("a"), BAD),
(r#"{"a":"#, P::Text("a"), BAD),
(r#"{"a":tru}"#, P::Text("a"), BAD),
(r#"{"a":nul}"#, P::Text("a"), BAD),
(r#"{"a":01}"#, P::Text("a"), BAD),
(r#"{"a":1.}"#, P::Text("a"), BAD),
(r#"{"a":-}"#, P::Text("a"), BAD),
(r#"{"a":1e}"#, P::Text("a"), BAD),
(r#"{"a":+1}"#, P::Text("a"), BAD),
(r#"{"a":"\x"}"#, P::Text("a"), BAD),
(r#"{"a":"\ud800"}"#, P::Text("a"), BAD),
(r#"{"a":"\u12"}"#, P::Text("a"), BAD),
("{\"a\":\"\t\"}", P::Text("a"), BAD),
(r#"{"a":"x"#, P::Text("a"), BAD),
(r#"{"a":1"#, P::Text("a"), BAD),
(r#"{"a":1x}"#, P::Text("a"), BAD),
(r#"{"a":1"}"#, P::Text("a"), BAD),
(r#"{"a" 1}"#, P::Text("a"), BAD),
(r#"{"a":1 "b":2}"#, P::Text("b"), BAD),
("{a:1}", P::Text("a"), BAD),
(r#"{"a":{"b":1"#, P::Text("a"), BAD),
(r#"{"a":[1,"]""#, P::Text("a"), BAD),
(r#"{"a":[\"]}"#, P::Text("a"), BAD),
(r#"{"x":tru,"a":1}"#, P::Text("a"), found("1", N)),
(r#"{"x":"\q","a":1}"#, P::Text("a"), found("1", N)),
(r#"{"x":[1,{"y":2]],"a":1}"#, P::Text("a"), found("1", N)),
(r#"{"a":[1,2}}"#, P::Text("a"), found("[1,2}", A)),
(r#"{"a":{"b":1,"c":[}}"#, P::Text("a.b"), found("1", N)),
(r#"{"a":1,"b":tru"#, P::Text("a"), found("1", N)),
(r#"{"a":1,"b":tru"#, P::Text("c"), BAD),
(r#"{"a":{"x":1},"b":tru"#, P::Text("a.y"), KEY),
(r#"{"a":{"x":1},"b":tru"#, P::Text("a.x"), found("1", N)),
(r#"{"a":1,"b":"#, P::Text("a"), found("1", N)),
(r#"{"a":1} trailing"#, P::Text("a"), found("1", N)),
(r#"{"a":{"b":1,"c":tru"#, P::Text("a.b"), found("1", N)),
(r#"{"a":{"b":1},"c":tru"#, P::Text("a.b"), found("1", N)),
];
fn alone(json: &str, path: P) -> Slot<'_> {
let paths = Paths::new([path.path()]);
let mut slots = Slots::new();
bare(paths.read(json.as_bytes(), &mut slots).get(0).unwrap())
}
#[test]
fn table_cases_read_alone() {
for &(json, path, want) in CASES {
assert_eq!(alone(json, path), want, "{path:?} in {json}");
}
}
#[test]
fn table_cases_read_together_per_record() {
let mut by_record: BTreeMap<&str, Vec<(P, Slot<'static>)>> = BTreeMap::new();
for &(json, path, want) in CASES {
by_record.entry(json).or_default().push((path, want));
}
let mut slots = Slots::new();
for (json, cases) in by_record {
let paths = Paths::new(cases.iter().map(|(p, _)| p.path()));
let values = paths.read(json.as_bytes(), &mut slots);
let valid = serde_json::from_str::<Value>(json).is_ok();
for ((path, want), got) in cases.iter().zip(values.iter().map(bare)) {
assert!(
got == *want || (!valid && got == BAD),
"{path:?} in {json}: {got:?}, alone {want:?}"
);
}
}
}
#[test]
fn a_key_found_inside_an_object_keeps_its_answer_past_a_later_fault() {
let paths = Paths::new([
P::Text("a").path(),
P::Text("a.b").path(),
P::Text("a.c").path(),
]);
let mut slots = Slots::new();
let values = paths.read(br#"{"a":{"b":1,"x":tru"#, &mut slots);
let got: Vec<Slot<'_>> = values.iter().map(bare).collect();
assert_eq!(got, [BAD, found("1", N), BAD]);
}
#[test]
fn a_prefix_and_a_path_below_it_read_together() {
let paths = Paths::new([P::Text("a").path(), P::Text("a.b").path()]);
let mut slots = Slots::new();
let values = paths.read(br#"{"a":{"b":1,"c":[2,3]},"d":4}"#, &mut slots);
assert_eq!(
values.get(0).map(bare),
Some(found(r#"{"b":1,"c":[2,3]}"#, O))
);
assert_eq!(values.get(1).map(bare), Some(found("1", N)));
assert_eq!(
values.get(1).and_then(Slot::found).map(Raw::span),
Some(10..11)
);
assert_eq!(values.get(2), None);
assert_eq!(values.len(), 2);
}
#[test]
fn an_empty_set_reads_nothing() {
let paths = Paths::new([]);
let mut slots = Slots::new();
let values = paths.read(b"{", &mut slots);
assert!(paths.is_empty() && values.is_empty());
assert_eq!(values.get(0), None);
}
#[test]
fn one_scratch_serves_sets_of_any_size() {
let small = Paths::new([P::Text("a").path()]);
let large =
Paths::new((0..50).map(|i| Path::from_keys([format!("k{i}"), "v".into()]).unwrap()));
let mut record = String::from("{");
for i in 0..50 {
let comma = if i == 0 { "" } else { "," };
write!(record, r#"{comma}"k{i}":{{"v":{i}}}"#).unwrap();
}
record.push('}');
let mut slots = Slots::new();
for _ in 0..2 {
let one = small.read(br#"{"a":1}"#, &mut slots).get(0);
assert_eq!(one.map(bare), Some(found("1", N)));
let values = large.read(record.as_bytes(), &mut slots);
for (i, slot) in values.iter().enumerate() {
assert_eq!(slot.found().map(Raw::text), Some(i.to_string().as_str()));
}
}
}
#[test]
fn strings_decode_their_escapes() {
for (json, want) in [
(r#""plain""#, "plain"),
(r#""a\"b\\c\/d""#, "a\"b\\c/d"),
(r#""\b\f\n\r\t""#, "\u{8}\u{c}\n\r\t"),
(r#""\u0041\u00e9\u20ac""#, "A\u{e9}\u{20ac}"),
(r#""\ud83d\ude00!""#, "\u{1F600}!"),
(r#""\u0000""#, "\0"),
(r#""""#, ""),
] {
let record = format!(r#"{{"s":{json}}}"#);
let raw = alone(&record, P::Text("s")).found().unwrap();
assert_eq!(raw.text(), json);
assert_eq!(raw.to_str().as_deref(), Some(want), "{json}");
assert_eq!(
matches!(raw.to_str(), Some(Cow::Borrowed(_))),
!json.contains('\\')
);
}
let number = alone(r#"{"n":1}"#, P::Text("n")).found().unwrap();
assert_eq!(number.to_str(), None);
}
#[test]
fn paths_parse_from_text() {
let ok: &[(&str, &[&str])] = &[
("a", &["a"]),
("a.b.c", &["a", "b", "c"]),
(r#"["a.b"]"#, &["a.b"]),
(r#"a["b.c"].d"#, &["a", "b.c", "d"]),
(r#"a["b"]["c"]"#, &["a", "b", "c"]),
(r#"["A\n"]"#, &["A\n"]),
(r#"[""]"#, &[""]),
("a b.c-d", &["a b", "c-d"]),
("\u{e9}.\u{1F600}", &["\u{e9}", "\u{1F600}"]),
("a]b", &["a]b"]),
];
for &(text, keys) in ok {
assert_eq!(
Path::parse(text),
Path::from_keys(keys.iter().copied()),
"{text}"
);
assert_eq!(text.parse::<Path>(), Path::parse(text));
}
let syntax = |at, why| Err(PathError::Syntax { at, why });
let bad: &[(&str, Result<Path, PathError>)] = &[
("", Err(PathError::Empty)),
("a..b", syntax(2, "a key name")),
(".a", syntax(0, "a key name")),
("a.", syntax(2, "a key name")),
(r#"a.["b"]"#, syntax(2, "a key name")),
(r#"["a""#, syntax(4, "`]` after the key")),
(r#"["a"]x"#, syntax(5, "`.` or `[` after `]`")),
("[a]", syntax(1, "a JSON string after `[`")),
(r#"["\q"]"#, syntax(1, "a JSON string")),
(r#"["a"#, syntax(1, "a closing quote")),
];
for (text, want) in bad {
assert_eq!(&Path::parse(text), want, "{text}");
}
assert_eq!(Path::from_keys(Vec::<String>::new()), Err(PathError::Empty));
let steps = |steps: Vec<Step>| Ok(Path::steps(steps));
let key = |k: &str| Step::Key(k.to_owned());
let either = |k: &str, i| Step::Either(k.to_owned(), i);
let indexed: &[(Result<Path, PathError>, Result<Path, PathError>)] = &[
(Path::parse("a[0]"), steps(vec![key("a"), Step::Index(0)])),
(
Path::parse("[12].b"),
steps(vec![Step::Index(12), key("b")]),
),
(
Path::parse(r#"a["0"][3]"#),
steps(vec![key("a"), key("0"), Step::Index(3)]),
),
(
Path::parse("a[01]"),
syntax(2, "an index with no leading zero"),
),
(Path::parse("a[1"), syntax(3, "`]` after the index")),
(Path::parse("a[1x]"), syntax(3, "`]` after the index")),
(
Path::parse("a[99999999999999999999999]"),
syntax(2, "an index that fits a usize"),
),
(
Path::from_pointer("/data/0/x"),
steps(vec![key("data"), either("0", 0), key("x")]),
),
(
Path::from_pointer("/a~1b/~0/10"),
steps(vec![key("a/b"), key("~"), either("10", 10)]),
),
(
Path::from_pointer("/01/-/"),
steps(vec![key("01"), key("-"), key("")]),
),
(Path::from_pointer(""), Err(PathError::Empty)),
(
Path::from_pointer("a/b"),
syntax(0, "`/` to start a pointer"),
),
(Path::from_pointer("/a~2"), syntax(2, "`~0` or `~1`")),
(Path::from_pointer("/a~"), syntax(2, "`~0` or `~1`")),
];
for (got, want) in indexed {
assert_eq!(got, want);
}
assert_eq!(
Path::whole_key_first("a.b.c.d.e.f.g.h.i"),
Err(PathError::TooManyParts { parts: 9 })
);
assert!(Path::whole_key_first("a.b.c.d.e.f.g.h").is_ok());
}
#[test]
fn whole_key_first_tries_the_whole_key_then_each_dot_from_the_left() {
let (readings, plain) = Path::whole_key_first("a.b.c").unwrap().readings();
let want: Vec<Vec<Step>> = [
&["a.b.c"][..],
&["a", "b.c"],
&["a", "b", "c"],
&["a.b", "c"],
]
.iter()
.map(|keys| keys.iter().map(|k| Step::Key((*k).to_owned())).collect())
.collect();
assert_eq!((readings, plain), (want, 2));
let cases: &[(&str, Slot<'static>)] = &[
(r#"{"a":{"b.c":1},"a.b":{"c":2}}"#, found("1", N)),
(r#"{"a.b.c":0,"a":{"b.c":1}}"#, found("0", N)),
(r#"{"a.b":{"c":2},"a":{"b":{"c":3}}}"#, found("3", N)),
(r#"{"a":5,"a.b":{"c":2}}"#, found("2", N)),
(r#"{"a":{"b":{}}}"#, KEY),
(r#"{"a":{"b":7}}"#, Slot::WrongParentType(2)),
(r#"{"x":1}"#, Slot::MissingParent(0)),
(r#"{"a":{"b.c":tru}}"#, BAD),
(r#"{"a":{"b.c":1},"a.b":"#, BAD),
(r#"{"a.b.c":0,"a":"#, found("0", N)),
];
for &(json, want) in cases {
assert_eq!(alone(json, P::Whole("a.b.c")), want, "{json}");
}
}
type Expect = (&'static str, Slot<'static>);
fn reads_as(json: &str, cases: &[Expect], whole_key_first: bool) {
let paths = Paths::new(cases.iter().map(|(text, _)| {
if whole_key_first {
Path::whole_key_first(text).unwrap()
} else {
Path::from_keys(text.split('.')).unwrap()
}
}));
let mut slots = Slots::new();
let values = paths.read(json.as_bytes(), &mut slots);
for ((text, want), got) in cases.iter().zip(values.iter()) {
assert_eq!(bare(got), *want, "{text}");
}
}
#[test]
fn the_receivers_paths_on_a_receiver_record() {
let record = r#"{"message":"m","event":{"original":"raw","dataset":"web.access"},"tags":{"event":{"org_id":"o1"},"event_category":"auth"},"version":"1.1","host":"h1","short_message":"s","level":6,"data_stream":{"dataset":"logs.web"},"org_id":"o1","_source":"syslog","_org_id":"acme","_timestamp_received":"2026-11-30T10:00:00Z"}"#;
reads_as(
record,
&[
("_source", found(r#""syslog""#, S)),
("_org_id", found(r#""acme""#, S)),
("_timestamp_received", found(r#""2026-11-30T10:00:00Z""#, S)),
("_timestamp_received_original", KEY),
("event.original", found(r#""raw""#, S)),
("log.original", Slot::MissingParent(0)),
(
"tags",
found(
r#"{"event":{"org_id":"o1"},"event_category":"auth"}"#,
Kind::Object,
),
),
("message", found(r#""m""#, S)),
("tags.event.org_id", found(r#""o1""#, S)),
("org_id", found(r#""o1""#, S)),
("tags.event_category", found(r#""auth""#, S)),
("version", found(r#""1.1""#, S)),
("host", found(r#""h1""#, S)),
("short_message", found(r#""s""#, S)),
("level", found("6", N)),
("data_stream.dataset", found(r#""logs.web""#, S)),
("event.dataset", found(r#""web.access""#, S)),
],
false,
);
reads_as(r#"{"a.b":1}"#, &[("a.b", Slot::MissingParent(0))], false);
}
#[test]
fn the_loaders_paths_on_a_loader_record() {
let record = r#"{"_timestamp":"2026-11-30T10:00:00Z","event_category":"network","tags":{"event":{"category":"flow"}},"ResourceAttributes":{"service.name":"checkout","host.name":"n1"},"host":{"name":"web-1"},"srcip":"10.0.0.1","_source":"otlp","_org_id":"acme"}"#;
reads_as(
record,
&[
("_source", found(r#""otlp""#, S)),
("_org_id", found(r#""acme""#, S)),
("event_category", found(r#""network""#, S)),
("tags.event.category", found(r#""flow""#, S)),
("ResourceAttributes.service.name", Slot::MissingParent(1)),
],
false,
);
reads_as(
record,
&[
("ResourceAttributes.service.name", found(r#""checkout""#, S)),
("ResourceAttributes.host.name", found(r#""n1""#, S)),
("_timestamp", found(r#""2026-11-30T10:00:00Z""#, S)),
("host.name", found(r#""web-1""#, S)),
("src_ip", KEY),
("srcip", found(r#""10.0.0.1""#, S)),
("source_ip", KEY),
],
true,
);
let split = r#"{"a":{"b.c":1},"a.b":{"c":2}}"#;
reads_as(split, &[("a.b.c", found("1", N))], true);
reads_as(split, &[("a.b.c", Slot::MissingParent(1))], false);
}
#[test]
fn the_archivers_paths_on_an_archiver_record() {
let record = r#"{"event_type":"login","tags":{"event_type":"auth"},"payload":{"big":[1,2,3]},"_source":"grpc","_org_id":"acme"}"#;
reads_as(
record,
&[
("_org_id", found(r#""acme""#, S)),
("_source", found(r#""grpc""#, S)),
("tags.event_type", found(r#""auth""#, S)),
("event_type", found(r#""login""#, S)),
],
false,
);
let dotted = r#"{"tags.event_type":"x"}"#;
reads_as(
dotted,
&[("tags.event_type", Slot::MissingParent(0))],
false,
);
reads_as(dotted, &[("tags.event_type", found(r#""x""#, S))], true);
}
#[test]
fn scalos_rule_fields_on_a_windows_dns_event() {
let record = r#"{"event":{"dns":{"type":"query","question":{"name":"example.com","type":"A"},"response_code":"NOERROR"},"network":{"transport":"udp"},"source":{"ip":"10.0.0.5"},"destination":{"ip":"10.0.0.53"}},"n":1.50}"#;
reads_as(
record,
&[
("event.dns.type", found(r#""query""#, S)),
("event.dns.question.name", found(r#""example.com""#, S)),
("event.dns.question.type", found(r#""A""#, S)),
("event.dns.response_code", found(r#""NOERROR""#, S)),
("event.network.transport", found(r#""udp""#, S)),
("event.source.ip", found(r#""10.0.0.5""#, S)),
("event.destination.ip", found(r#""10.0.0.53""#, S)),
("event.parse_error", KEY),
("n", found("1.50", N)),
],
false,
);
reads_as(r#"{"a":1,"a":2}"#, &[("a", found("1", N))], false);
}
#[test]
fn types_are_send_and_sync() {
const fn send_sync<T: Send + Sync>() {}
send_sync::<Path>();
send_sync::<PathError>();
send_sync::<Paths>();
send_sync::<Slots>();
send_sync::<Values<'static, 'static>>();
send_sync::<Slot<'static>>();
}
fn reference_close(json: &[u8], from: usize) -> Option<usize> {
let mut depth = 1_usize;
let mut in_string = false;
let mut escaped = false;
for (i, &b) in json.iter().enumerate().skip(from) {
if in_string {
if escaped {
escaped = false;
} else if b == b'\\' {
escaped = true;
} else if b == b'"' {
in_string = false;
}
continue;
}
match b {
b'"' => in_string = true,
b'\\' => return None,
b'{' | b'[' => depth += 1,
b'}' | b']' => {
depth -= 1;
if depth == 0 {
return Some(i + 1);
}
}
_ => {}
}
}
None
}
fn closes_agree(json: &[u8], from: usize) {
assert_eq!(
close(json, from).ok(),
reference_close(json, from),
"from {from}: {:?}",
String::from_utf8_lossy(json)
);
}
#[test]
fn the_block_closer_agrees_on_every_short_string_across_block_edges() {
let alphabet = b"]\"\\x[";
for len in 0..=5_u32 {
for n in 0..alphabet.len().pow(len) {
let mut body = Vec::new();
let mut k = n;
for _ in 0..len {
body.push(alphabet[k % alphabet.len()]);
k /= alphabet.len();
}
for before in [0, 1, 31, 59, 62, 63, 64, 65, 127] {
for prefix in [0, 7] {
let mut json = vec![b'['; prefix];
json.extend(std::iter::repeat_n(b' ', before));
json.extend_from_slice(&body);
json.push(b']');
closes_agree(&json, prefix);
}
}
}
}
}
const STRUCTURAL: &[u8] = b"{}[]\"\\\\x ,:";
pub(in crate::json) struct Style {
pub(in crate::json) seed: u64,
pub(in crate::json) spaces: bool,
pub(in crate::json) escapes: bool,
}
impl Style {
fn pick(&mut self, n: u64) -> u64 {
self.seed ^= self.seed << 13;
self.seed ^= self.seed >> 7;
self.seed ^= self.seed << 17;
self.seed % n
}
pub(in crate::json) fn space(&mut self, out: &mut String) {
if self.spaces {
out.push_str(["", " ", "\n ", "\t", "\r\n"][usize::try_from(self.pick(5)).unwrap()]);
}
}
pub(in crate::json) fn string(&mut self, s: &str, out: &mut String) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' if self.pick(2) == 0 => out.push_str("\\n"),
'\t' if self.pick(2) == 0 => out.push_str("\\t"),
'/' if self.escapes && self.pick(2) == 0 => out.push_str("\\/"),
c if u32::from(c) < 0x20 || (self.escapes && self.pick(3) == 0) => {
let mut units = [0; 2];
for unit in c.encode_utf16(&mut units) {
if self.pick(2) == 0 {
write!(out, "\\u{unit:04x}").unwrap();
} else {
write!(out, "\\u{unit:04X}").unwrap();
}
}
}
c => out.push(c),
}
}
out.push('"');
}
pub(in crate::json) fn write(&mut self, v: &Value, out: &mut String) {
match v {
Value::String(s) => self.string(s, out),
Value::Array(items) => {
out.push('[');
for (i, item) in items.iter().enumerate() {
if i > 0 {
self.space(out);
out.push(',');
}
self.space(out);
self.write(item, out);
}
self.space(out);
out.push(']');
}
Value::Object(map) => {
out.push('{');
for (i, (key, item)) in map.iter().enumerate() {
if i > 0 {
self.space(out);
out.push(',');
}
self.space(out);
self.string(key, out);
self.space(out);
out.push(':');
self.space(out);
self.write(item, out);
}
self.space(out);
out.push('}');
}
scalar => out.push_str(&scalar.to_string()),
}
}
}
fn written(record: &Value, seed: u64) -> [String; 4] {
[(false, false), (true, false), (false, true), (true, true)].map(|(spaces, escapes)| {
let mut style = Style {
seed: seed | 1,
spaces,
escapes,
};
let mut out = String::new();
style.space(&mut out);
style.write(record, &mut out);
style.space(&mut out);
out
})
}
pub(in crate::json) const KEYS: &[&str] = &[
"a",
"b",
"c",
"a.b",
"b.c",
"",
"k\"q",
"x\\y",
"\u{e9}",
"\u{1F600}",
"t\tab",
"/s",
"a key longer than any short one",
];
fn key() -> impl Strategy<Value = String> {
prop::sample::select(KEYS).prop_map(str::to_owned)
}
fn object(fields: BTreeMap<String, Value>) -> Value {
Value::Object(fields.into_iter().collect::<Map<String, Value>>())
}
pub(in crate::json) fn value() -> impl Strategy<Value = Value> {
let leaf = prop_oneof![
Just(Value::Null),
any::<bool>().prop_map(Value::Bool),
any::<i64>().prop_map(Value::from),
any::<u64>().prop_map(Value::from),
any::<f64>().prop_filter_map("finite", |f| Number::from_f64(f).map(Value::Number)),
key().prop_map(Value::String),
"[a-z\\[\\]{}\"\\\\/ ]{0,90}".prop_map(Value::String),
prop::collection::vec(any::<char>(), 0..12)
.prop_map(|cs| Value::String(cs.into_iter().collect())),
];
leaf.prop_recursive(4, 48, 6, |inner| {
prop_oneof![
prop::collection::vec(inner.clone(), 0..5).prop_map(Value::Array),
prop::collection::btree_map(key(), inner, 0..6).prop_map(object),
]
})
}
fn record() -> impl Strategy<Value = Value> {
prop_oneof![
9 => prop::collection::btree_map(key(), value(), 0..8).prop_map(object),
1 => value(),
]
}
fn real_paths(record: &Value, above: &mut Vec<String>, out: &mut Vec<Vec<String>>) {
if let Value::Object(map) = record
&& above.len() < 4
{
for (key, item) in map {
above.push(key.clone());
out.push(above.clone());
real_paths(item, above, out);
above.pop();
}
}
}
fn parsed(json: &str) -> Result<Value, TestCaseError> {
serde_json::from_str(json).map_err(|e| TestCaseError::fail(format!("{json}: {e}")))
}
fn expect<'v>(record: &'v Value, keys: &[String]) -> Result<&'v Value, Slot<'static>> {
let mut at = record;
for (i, key) in keys.iter().enumerate() {
let Value::Object(map) = at else {
return Err(Slot::WrongParentType(i));
};
at = map.get(key).ok_or(if i + 1 == keys.len() {
Slot::MissingKey
} else {
Slot::MissingParent(i)
})?;
}
Ok(at)
}
fn whole_key_first<'v>(map: &'v Map<String, Value>, path: &str) -> Option<&'v Value> {
if let Some(v) = map.get(path) {
return Some(v);
}
path.match_indices('.')
.find_map(|(dot, _)| match map.get(&path[..dot]) {
Some(Value::Object(child)) => whole_key_first(child, &path[dot + 1..]),
_ => None,
})
}
const fn kind_of(v: &Value) -> Kind {
match v {
Value::Null => Kind::Null,
Value::Bool(_) => Kind::Bool,
Value::Number(_) => Kind::Number,
Value::String(_) => Kind::String,
Value::Array(_) => Kind::Array,
Value::Object(_) => Kind::Object,
}
}
fn agrees(
got: Slot<'_>,
want: Result<&Value, Slot<'static>>,
json: &str,
) -> Result<(), TestCaseError> {
match (got, want) {
(Slot::Found(raw), Ok(v)) => {
prop_assert_eq!(raw.kind(), kind_of(v));
let reparsed: Value = serde_json::from_str(raw.text())
.map_err(|e| TestCaseError::fail(format!("{}: {e}", raw.text())))?;
prop_assert_eq!(&reparsed, v);
prop_assert!(
json.as_bytes()
.as_ptr_range()
.contains(&raw.text().as_ptr())
);
prop_assert_eq!(
raw.span().start,
raw.text().as_ptr().addr() - json.as_ptr().addr()
);
prop_assert_eq!(&json[raw.span()], raw.text());
if let Value::String(s) = v {
let decoded = raw.to_str();
prop_assert_eq!(decoded.as_deref(), Some(s.as_str()));
}
}
(got, Err(miss)) => prop_assert_eq!(got, miss),
(got, Ok(v)) => prop_assert!(false, "{:?} where {} is", got, v),
}
Ok(())
}
const RECORD_CASES: u32 = 1024;
proptest! {
#![proptest_config(ProptestConfig::with_cases(RECORD_CASES))]
#[test]
fn slots_agree_with_serde_json(
record in record(),
extra in prop::collection::vec(prop::collection::vec(key(), 1..5), 0..12),
seed in any::<u64>(),
) {
let mut wanted = Vec::new();
real_paths(&record, &mut Vec::new(), &mut wanted);
wanted.truncate(40);
wanted.extend(extra);
let paths = Paths::new(wanted.iter().map(|keys| Path::from_keys(keys.iter().cloned()).unwrap()));
let mut slots = Slots::new();
for json in written(&record, seed) {
let tree = parsed(&json)?;
let values = paths.read(json.as_bytes(), &mut slots);
for (keys, got) in wanted.iter().zip(values.iter()) {
agrees(got, expect(&tree, keys), &json)?;
}
}
}
#[test]
fn pointers_agree_with_serde_json(
record in record(),
extra in prop::collection::vec(prop::collection::vec(prop_oneof![key(), (0_usize..4).prop_map(|i| i.to_string())], 1..4), 0..8),
seed in any::<u64>(),
) {
let mut wanted = Vec::new();
real_pointers(&record, "", &mut wanted);
wanted.truncate(40);
wanted.extend(extra.iter().map(|segments| {
let mut pointer = String::new();
for s in segments {
write!(pointer, "/{}", s.replace('~', "~0").replace('/', "~1")).unwrap();
}
pointer
}));
let paths = Paths::new(wanted.iter().map(|p| Path::from_pointer(p).unwrap()));
let mut slots = Slots::new();
for json in written(&record, seed) {
let tree = parsed(&json)?;
let values = paths.read(json.as_bytes(), &mut slots);
for (pointer, got) in wanted.iter().zip(values.iter()) {
match (got, tree.pointer(pointer)) {
(Slot::Found(_), Some(v)) => agrees(got, Ok(v), &json)?,
(Slot::Found(raw), None) => prop_assert!(false, "{} found {:?} in {}", pointer, raw, json),
(Slot::Malformed, _) => prop_assert!(false, "{} malformed in {}", pointer, json),
(miss, Some(v)) => prop_assert!(false, "{} gave {:?} where {} is, in {}", pointer, miss, v, json),
(_, None) => {}
}
}
}
}
#[test]
fn whole_key_first_agrees_with_the_reading_on_a_tree(
record in record(),
joined in prop::collection::vec(prop::collection::vec(key(), 1..5), 1..10),
seed in any::<u64>(),
) {
let texts: Vec<String> = joined.iter().map(|keys| keys.join(".")).collect();
let paths = Paths::new(texts.iter().map(|t| Path::whole_key_first(t).unwrap()));
let mut slots = Slots::new();
for json in written(&record, seed) {
let tree = parsed(&json)?;
let values = paths.read(json.as_bytes(), &mut slots);
for (text, got) in texts.iter().zip(values.iter()) {
let plain: Vec<String> = text.split('.').map(str::to_owned).collect();
let want = match &tree {
Value::Object(map) => whole_key_first(map, text)
.ok_or_else(|| expect(&tree, &plain).err().unwrap_or(KEY)),
_ => Err(Slot::WrongParentType(0)),
};
agrees(got, want, &json)?;
}
}
}
#[test]
fn a_cut_record_keeps_each_answer_or_says_malformed(
record in record(),
extra in prop::collection::vec(prop::collection::vec(key(), 1..4), 0..8),
cut in any::<prop::sample::Index>(),
seed in any::<u64>(),
) {
let mut wanted = Vec::new();
real_paths(&record, &mut Vec::new(), &mut wanted);
wanted.truncate(20);
wanted.extend(extra);
let paths = Paths::new(wanted.iter().map(|keys| Path::from_keys(keys.iter().cloned()).unwrap()));
let (mut whole, mut part) = (Slots::new(), Slots::new());
for json in written(&record, seed) {
let bytes = json.as_bytes();
let short = &bytes[..cut.index(bytes.len() + 1)];
let full = paths.read(bytes, &mut whole);
let shortened = paths.read(short, &mut part);
for (a, b) in full.iter().zip(shortened.iter()) {
prop_assert!(b == a || b == BAD, "{:?} cut, {:?} whole", b, a);
}
}
}
#[test]
fn the_block_closer_agrees_on_generated_bytes(
prefix in prop::collection::vec(prop::sample::select(STRUCTURAL), 0..130),
body in prop::collection::vec(prop::sample::select(STRUCTURAL), 0..300),
) {
let mut json = prefix.clone();
json.extend_from_slice(&body);
closes_agree(&json, prefix.len());
}
}
fn real_pointers(v: &Value, at: &str, out: &mut Vec<String>) {
let mut step = |segment: &str, child: &Value| {
let pointer = format!("{at}/{}", segment.replace('~', "~0").replace('/', "~1"));
out.push(pointer.clone());
real_pointers(child, &pointer, out);
};
match v {
Value::Object(map) => map.iter().for_each(|(k, child)| step(k, child)),
Value::Array(items) => items
.iter()
.enumerate()
.for_each(|(i, child)| step(&i.to_string(), child)),
_ => {}
}
}