#![allow(
clippy::format_push_string,
clippy::format_collect,
clippy::items_after_statements,
clippy::cast_precision_loss,
let_underscore_drop,
reason = "test fixtures favor compact setup, generated inputs, and literal YAML braces"
)]
use std::hash::Hash;
use std::io::{Read, Write};
use std::time::{Duration, Instant};
use ayaml::{ErrorKind, LimitExceeded, LimitKind, Limits, MAX_DEPTH, MAX_DEPTH_CAP, Value};
use serde::de::IgnoredAny;
#[path = "adversarial/runner.rs"]
mod runner;
use runner::{
child_command, read_all, run_child, run_child_ending_itself, run_command, wait_or_kill,
};
const CHILD: &str = "AYAML_ADVERSARIAL_CHILD";
const ADDRESS_SPACE_KIB: u64 = 1 << 20;
const NORMAL_PEAK_KIB: u64 = ADDRESS_SPACE_KIB / 4;
const CHILD_DEADLINE: Duration = Duration::from_secs(300);
const CHILD_GRACE: Duration = Duration::from_secs(30);
const OUTPUT_KEPT_BYTES: u64 = 1 << 20;
const LIMIT_THEN_RUN: &str = r#"
[ "$(ulimit -v)" != unlimited ] && [ "$(ulimit -v)" -le "$1" ] || ulimit -v "$1" || exit 125
ulimit -c 0
shift
exec "$0" "$@"
"#;
macro_rules! in_child {
($body:expr $(,)?) => {{
fn here() {}
let path = std::any::type_name_of_val(&here);
let test = path
.strip_suffix("::here")
.and_then(|path| path.split_once("::"))
.map_or(path, |(_, test)| test);
in_child_named(test, $body);
}};
}
fn proc_self_number(file: &str, label: &str) -> Option<u64> {
std::fs::read_to_string(format!("/proc/self/{file}"))
.ok()?
.lines()
.find_map(|line| line.strip_prefix(label))?
.split_whitespace()
.next()?
.parse()
.ok()
}
fn assert_limited() {
if cfg!(target_os = "linux") {
let limit = proc_self_number("limits", "Max address space");
assert!(
limit.is_some_and(|bytes| bytes <= ADDRESS_SPACE_KIB * 1024),
"no address-space limit in this child: {limit:?}"
);
}
}
fn is_child() -> bool {
let Some(seconds) = std::env::var_os(CHILD) else {
return false;
};
let seconds: u64 = seconds
.to_str()
.and_then(|seconds| seconds.parse().ok())
.expect("a child's deadline, in seconds");
std::thread::spawn(move || {
std::thread::sleep(Duration::from_secs(seconds));
let _ = writeln!(
std::io::stderr(),
"this child passed its own deadline of {seconds} s"
);
std::process::abort();
});
true
}
fn in_child_named(test: &str, body: impl FnOnce()) {
if !is_child() {
let run = run_child(test, CHILD_DEADLINE);
assert!(
run.passed(),
"{test}: ended with {:?} after {:?}\n{}",
run.status,
run.elapsed,
run.output
);
return;
}
assert_limited();
body();
if cfg!(target_os = "linux") {
let peak = proc_self_number("status", "VmHWM:").expect("VmHWM");
println!("{test}: peak memory {peak} KiB");
assert!(
peak <= NORMAL_PEAK_KIB,
"{test} used {peak} KiB of memory, over the {NORMAL_PEAK_KIB} KiB expected"
);
}
}
#[cfg(target_os = "linux")]
#[test]
#[ignore = "only for a child of runaway_allocation_fails_quickly_and_cleanly"]
fn keep_allocating() {
if is_child() {
assert_limited();
let mut blocks = Vec::new();
loop {
blocks.push(vec![1_u8; 1 << 20]);
std::hint::black_box(&blocks);
}
}
}
#[cfg(target_os = "linux")]
#[test]
fn runaway_allocation_fails_quickly_and_cleanly() {
let run = run_child("keep_allocating", CHILD_DEADLINE);
assert!(!run.passed(), "{}", run.output);
assert!(run.status.is_some(), "hit the deadline: {}", run.output);
assert!(
run.output.contains("memory allocation of"),
"{:?}: {}",
run.status,
run.output
);
assert!(run.elapsed < Duration::from_secs(60), "{:?}", run.elapsed);
}
#[test]
#[ignore = "only for a child of a_failing_child_fails_its_test"]
fn fail_in_a_child() {
assert!(
std::env::var_os(CHILD).is_none(),
"deliberate failure in a child"
);
}
#[test]
#[should_panic(expected = "deliberate failure in a child")]
fn a_failing_child_fails_its_test() {
in_child_named("fail_in_a_child", || unreachable!("this isn't the child"));
}
#[test]
#[ignore = "only for a child of a_child_past_its_deadline_is_killed"]
fn never_finish() {
if is_child() {
std::thread::sleep(Duration::from_secs(3_600));
}
}
#[test]
fn a_child_past_its_deadline_is_killed() {
let run = run_child("never_finish", Duration::from_secs(1));
assert!(run.status.is_none(), "{:?}: {}", run.status, run.output);
assert!(run.elapsed < Duration::from_secs(60), "{:?}", run.elapsed);
}
#[test]
fn a_child_nobody_kills_ends_itself() {
let run = run_child_ending_itself("never_finish", CHILD_DEADLINE, Duration::from_secs(1));
assert!(!run.passed(), "{}", run.output);
assert!(run.status.is_some(), "hit the deadline: {}", run.output);
assert!(
run.output.contains("passed its own deadline"),
"{:?}: {}",
run.status,
run.output
);
assert!(run.elapsed < Duration::from_secs(60), "{:?}", run.elapsed);
}
#[test]
fn a_child_whose_stderr_is_closed_ends_itself() {
let started = Instant::now();
let mut child = child_command("never_finish", Duration::from_secs(1))
.spawn()
.expect("start the child");
let stdout = read_all(child.stdout.take().expect("piped stdout"));
drop(child.stderr.take());
let status = wait_or_kill(&mut child, started, Duration::from_secs(60));
let output = stdout.join().expect("stdout reader");
assert!(
status.is_some_and(|status| !status.success()),
"{status:?}: {output}"
);
}
#[test]
fn a_childs_output_is_capped() {
let flood = std::io::repeat(b'x').take(3 * OUTPUT_KEPT_BYTES);
let kept = read_all(flood).join().expect("reader");
assert_eq!(kept.len() as u64, OUTPUT_KEPT_BYTES);
}
#[cfg(target_os = "linux")]
#[test]
#[ignore = "only for a child of a_child_over_its_normal_peak_fails"]
fn hold_too_much_memory() {
if std::env::var_os(CHILD).is_some() {
in_child!(|| {
let kib = usize::try_from(NORMAL_PEAK_KIB).expect("fits") + 16 * 1024;
let held = vec![1_u8; kib * 1024];
std::hint::black_box(&held);
});
}
}
#[cfg(target_os = "linux")]
#[test]
fn a_child_over_its_normal_peak_fails() {
let run = run_child("hold_too_much_memory", CHILD_DEADLINE);
assert!(!run.passed(), "{}", run.output);
assert!(run.output.contains("KiB expected"), "{}", run.output);
}
#[test]
fn a_child_that_runs_no_test_does_not_pass() {
let run = run_child("no_such_test", CHILD_DEADLINE);
assert!(
run.status.is_some_and(|status| status.success()),
"{:?}: {}",
run.status,
run.output
);
assert!(!run.passed(), "{}", run.output);
}
fn alias_bomb() -> String {
let mut bomb = String::from("a0: &a0 [x, x, x, x, x, x, x, x, x]\n");
for level in 1..9 {
let previous = format!("*a{}", level - 1);
let row = [previous.as_str(); 9].join(", ");
bomb.push_str(&format!("a{level}: &a{level} [{row}]\n"));
}
bomb
}
fn ok<T>(result: Result<T, ayaml::Error>) -> Result<(), ayaml::Error> {
result.map(drop)
}
fn entry_points(input: &str) -> Vec<(&'static str, Result<(), ayaml::Error>)> {
let cursor = |next: fn(&mut ayaml::Deserializer<'_>) -> Result<(), ayaml::Error>| {
ayaml::Deserializer::from_str(input).and_then(|mut cursor| next(&mut cursor))
};
let results = vec![
("parse_value", ok(ayaml::parse_value(input))),
("parse_documents", ok(ayaml::parse_documents(input))),
("from_str", ok(ayaml::from_str::<Value>(input))),
(
"from_slice",
ok(ayaml::from_slice::<Value>(input.as_bytes())),
),
(
"from_str_borrowed",
ok(ayaml::from_str_borrowed::<Value>(input)),
),
(
"from_str_borrowed (IgnoredAny)",
ok(ayaml::from_str_borrowed::<IgnoredAny>(input)),
),
(
"from_slice_borrowed",
ok(ayaml::from_slice_borrowed::<Value>(input.as_bytes())),
),
(
"Deserializer::next",
cursor(|cursor| cursor.next::<Value>().map(drop)),
),
(
"Deserializer::next_borrowed",
cursor(|cursor| cursor.next_borrowed::<IgnoredAny>().map(drop)),
),
(
"Deserializer::next_seed",
cursor(|cursor| {
cursor
.next_seed(std::marker::PhantomData::<Value>)
.map(drop)
}),
),
(
"Deserializer::next_seed_borrowed",
cursor(|cursor| {
cursor
.next_seed_borrowed(std::marker::PhantomData::<IgnoredAny>)
.map(drop)
}),
),
];
#[cfg(feature = "libyaml-compat")]
let results = {
let mut results = results;
results.extend([
(
"compat::from_str",
ok(ayaml::compat::from_str::<Value>(input)),
),
(
"compat::from_str_seed",
ok(ayaml::compat::from_str_seed(
input,
std::marker::PhantomData::<IgnoredAny>,
)),
),
(
"compat::deserialize_any",
ok(ayaml::compat::deserialize_any(input, IgnoredAny)),
),
]);
results
};
results
}
#[test]
fn alias_bomb_is_rejected_on_every_entry_point() {
in_child!(|| {
let bomb = alias_bomb();
assert!(bomb.len() < 512, "{} bytes", bomb.len());
for (name, result) in entry_points(&bomb) {
let error = result.expect_err(name);
assert_eq!(error.kind(), ErrorKind::Limit, "{name}: {error}");
}
});
}
#[test]
fn alias_dereference_limit_is_enforced_on_every_entry_point() {
in_child!(|| {
let mut input = String::from("a: &a 1\nb: [");
input.push_str(&vec!["*a"; 100_001].join(", "));
input.push_str("]\n");
for (name, result) in entry_points(&input) {
let error = result.expect_err(name);
assert!(
error.kind() == ErrorKind::Limit || error.to_string().contains("alias"),
"{name}: {error}"
);
}
},);
}
#[test]
fn ordinary_aliases_are_accepted_on_every_entry_point() {
in_child!(|| {
let input = "base: &b {x: [1, 2]}\nuse: *b\nmore: [*b, *b]\n";
for (name, result) in entry_points(input) {
result.unwrap_or_else(|error| panic!("{name}: {error}"));
}
});
}
#[test]
fn compat_profile_keeps_its_single_document_limit() {
assert_eq!(Limits::compat().max_documents, 1);
}
fn alias_chain(links: usize) -> String {
let mut chain = String::from("a0: &a0 [0]\n");
for link in 1..links {
chain.push_str(&format!("a{link}: &a{link} [*a{}]\n", link - 1));
}
chain
}
#[test]
fn alias_nesting_counts_toward_the_depth_limit_on_every_entry_point() {
in_child!(|| {
for (name, result) in entry_points(&alias_chain(127)) {
result.unwrap_or_else(|error| panic!("{name}: {error}"));
}
for links in [128, 8_000] {
for (name, result) in entry_points(&alias_chain(links)) {
assert_depth_error_kind(name, &result.expect_err(name));
}
}
},);
}
#[test]
fn nested_anchors_are_not_copied() {
in_child!(|| {
let mut input = String::new();
for level in 0..100 {
input.push_str(&format!("&a{level} ["));
}
input.push_str(&"x".repeat(4 << 20));
input.push_str(&"]".repeat(100));
let mut value = &ayaml::parse_value(&input).expect("parse");
for _ in 0..100 {
value = &value[0];
}
assert_eq!(value.as_str().map(str::len), Some(4 << 20));
ayaml::from_str_borrowed::<IgnoredAny>(&input).expect("typed");
});
}
fn repeated_inputs(length: usize) -> Vec<String> {
let all = |unit: &str| unit.repeat(length / unit.len());
let half = |unit: &str| unit.repeat(length / 2 / unit.len());
vec![
format!("a\n{}", all("\u{feff}#\n")),
format!("a\n{}", all("\u{feff}\n")),
format!("a\n{}---\nb\n", all("\u{feff}#\n")),
format!("|\n a\n{}", all("\u{feff}#\n")),
format!("a\n{}---\nb\n", all("\u{feff}")),
format!("{}k: a{}", half("\u{feff}"), half("\n b")),
format!("a\n...\n{}k: a{}", half("\u{feff}"), half("\n b")),
format!("{}- a{}", half("\u{feff}"), half("\n b")),
format!("k: [{}]\n", all("'a',")),
format!("k: [{}]\n", all("\"a\",")),
format!("[{}]\n", all("'a',")),
format!("k: [\n{}{}]\n", half(" "), half("'a',")),
format!("k:\n{} [{}]\n", half("#\n"), half("'a\n ',")),
format!("k: &{} [{}]\n", half("a"), half("\"a\n \",")),
format!("k:\n{} [{}]\n", half("\n"), half("{a: 'a\n '},")),
format!("k: [\n{}]\n", all("\t")),
format!("[\n{}]\n", all("\t")),
format!("{}x\n", all("\t")),
format!("{}#\nx\n", all("\t")),
format!("k: [{}a]\n", all("a\t,\t")),
format!("k: [{}]\n", all("'a'\t,")),
all("[]\t"),
all("{}\t"),
all("'a'\t"),
all("!t\t"),
format!("k: {}", all("[]\t")),
format!("{}k: {}", half("\u{feff}"), half("'a'\t")),
format!("k: [x\ny{}{}]\n", half("\n"), half(",\"a\": \"\"")),
format!("{}k: {}", half("\u{feff}"), half("[]\t")),
all("-\t'a' "),
all("-\t[a] "),
all("-\t*a "),
all("-\t&a "),
all("-\t] "),
format!("{}\n", all("\t'a'\n")),
format!("a{}b\n", all("\n")),
format!("a{}b\n", all(" \n")),
format!("k: a{} b\n", all("\r\n")),
format!("k: [{}]\n", all(" \n")),
format!("[a{}]\n", all(" ")),
format!("k: 'a{}b'\n", all(" \n")),
format!("{}#\na\n", all(" \n")),
format!("k: |\n{} a\n", all(" \n")),
format!("k: '{}b'\n", all("a\n ")),
format!("k: \"{}b\"\n", all("a\n ")),
format!("k: |\n{}", all(" a\n")),
format!("k: >\n{}", all(" a\n")),
format!("{}---\na\n", all("%X a\n")),
all("- &a a\n"),
format!("- &a a\n{}", all("- *a\n")),
format!("- &a a\n- [{}]\n", all("*a, ")),
format!("[[[{}]]]\n", all("a,")),
format!("k: [{{a: [{}]}}]\n", all("'a',")),
format!("[{}]\n", all("[],")),
format!("[{}]\n", all("{},")),
format!("k: [{}]\n", all("[],")),
format!("[{}]\n", all("é,")),
format!("# é\n[{}]\n", all("a,")),
format!("{{\"name\":\"é\",\"items\":[{}]}}\n", all("{\"a\":1},")),
format!("{}[{}]\n", half("\u{feff}"), half("a,")),
format!("{}a{}", half(" "), half("\n b")),
format!("{}: a{}", half("x"), half("\n b")),
]
}
const LARGEST_RATIO: u32 = 3;
const QUICK: Duration = Duration::from_millis(100);
const MOST_REPEATS: u32 = 1 << 16;
const TRIES: usize = 12;
const RETRY_BUDGET: Duration = Duration::from_secs(40);
type Reading = fn(&str);
fn time_runs(read: &dyn Fn(&str), input: &str, repeats: u32) -> Duration {
let started = Instant::now();
for _ in 0..repeats {
read(input);
}
started.elapsed()
}
fn linear_time(read: &dyn Fn(&str), short: &str, long: &str) -> Result<Duration, String> {
let mut repeats = 1;
let mut long_time = time_runs(read, long, repeats);
while long_time < QUICK && repeats < MOST_REPEATS {
repeats *= 2;
long_time = time_runs(read, long, repeats);
}
if long_time < QUICK {
return Ok(long_time / repeats);
}
let mut shorts_time = Duration::MAX;
let started = Instant::now();
for _ in 0..TRIES {
shorts_time = shorts_time.min(time_runs(read, short, 8 * repeats));
if long_time < shorts_time * LARGEST_RATIO || started.elapsed() > RETRY_BUDGET {
break;
}
long_time = long_time.min(time_runs(read, long, repeats));
}
if long_time < shorts_time * LARGEST_RATIO {
Ok(long_time / repeats)
} else {
Err(format!(
"{shorts_time:?} for {} short runs, then {long_time:?} for {repeats} on 8 times the \
length",
8 * repeats
))
}
}
#[test]
fn scanning_takes_time_linear_in_the_input() {
in_child!(|| {
const LENGTH: usize = 1 << 19;
const SLOWEST: Duration = Duration::from_secs(20);
let readers: Vec<(&str, Reading)> = vec![
("parse_documents", |input| {
let _ = ayaml::parse_documents(input);
}),
#[cfg(feature = "libyaml-compat")]
("compat", |input| {
let _ = ayaml::compat::from_str::<Value>(input);
}),
];
let shorter = repeated_inputs(LENGTH / 8);
for (short, long) in shorter.iter().zip(repeated_inputs(LENGTH)) {
let name: String = long.chars().take(30).collect();
for (reader, read) in &readers {
match linear_time(read, short, &long) {
Ok(time) => assert!(time < SLOWEST, "{reader}: {name:?}: {time:?}"),
Err(times) => panic!("{reader}: {name:?}: {times}"),
}
}
}
});
}
#[test]
fn many_tag_directives_take_time_linear_in_their_number() {
in_child!(|| {
const DIRECTIVES: usize = 8_000;
let input = |count: usize| {
let mut text = String::new();
for index in 0..count {
text.push_str(&format!("%TAG !t{index}! tag:x{index}:\n"));
}
text.push_str("---\n[\n");
for index in 0..count {
text.push_str(&format!(" !t{index}!a%20b,\n"));
}
text.push_str("]\n");
text
};
let (short, long) = (input(DIRECTIVES / 8), input(DIRECTIVES));
let scan: fn(&str) = |text| {
let _ = ayaml::parse_documents(text);
};
if let Err(times) = linear_time(&scan, &short, &long) {
panic!("scanner: {times}");
}
let emit: fn(&str) = |text| {
let events = ayaml::parse_events(text)
.and_then(Iterator::collect::<Result<Vec<_>, _>>)
.expect("events");
let _ = ayaml::to_string_events(&events);
};
if let Err(times) = linear_time(&emit, &short, &long) {
panic!("event writer: {times}");
}
});
}
#[test]
fn many_keys_take_time_linear_in_their_number() {
in_child!(|| {
const KEYS: usize = 40_000;
let readers: Vec<(&str, Reading)> = vec![
("parse_value", |input| {
ayaml::parse_value(input).expect("distinct keys parse");
}),
("from_str", |input| {
ayaml::from_str::<Value>(input).expect("distinct keys parse");
}),
#[cfg(feature = "libyaml-compat")]
("compat", |input| {
ayaml::compat::from_str::<Value>(input).expect("distinct keys parse");
}),
];
type Key = fn(usize) -> String;
let shapes: [(&str, Key); 8] = [
("floats", |key| format!("{key}.5: x\n")),
("exponents", |key| format!("{key}e3: x\n")),
("integers", |key| format!("{key}: x\n")),
("strings", |key| format!("k{key}: x\n")),
("mappings", |key| format!("? {{k{key}: x}}\n: x\n")),
("tags", |key| format!("? !t{key} x\n: x\n")),
("opposite integers", |key| {
let (negative, positive) = (key + 1, (1_u128 << 64) - key as u128 - 1);
format!("? {{-{negative}: 0, {positive}: 0}}\n: 0\n")
}),
("wide integers", |key| {
let wide = (2_u128 << 64) + key as u128;
format!("? {{{key}: 0, {wide}: null}}\n: 0\n")
}),
];
for (shape, key) in shapes {
let keys = |count: usize| (0..count).map(key).collect::<String>();
let (short, long) = (keys(KEYS / 8), keys(KEYS));
for (reader, read) in &readers {
if let Err(times) = linear_time(read, &short, &long) {
panic!("{reader}: {shape}: {times}");
}
}
}
});
}
#[test]
fn the_linear_time_check_fails_a_quick_quadratic_scan() {
in_child!(|| {
const LENGTH: usize = 1 << 19;
let quadratic: fn(&str) = |input| {
let bytes = &input.as_bytes()[..input.len() / 512];
let mut sum = 0_u64;
for first in bytes {
for second in bytes {
sum = sum.wrapping_add(u64::from(first ^ second));
}
}
std::hint::black_box(sum);
};
let linear: fn(&str) = |input| {
std::hint::black_box(input.bytes().map(u64::from).sum::<u64>());
};
let short = "ab".repeat(LENGTH / 16);
let long = "ab".repeat(LENGTH / 2);
let one_run = (0..5)
.map(|_| time_runs(&quadratic, &long, 1))
.min()
.expect("runs");
assert!(one_run < QUICK, "one run took {one_run:?}");
assert!(
linear_time(&quadratic, &short, &long).is_err(),
"a quadratic scan passed"
);
linear_time(&linear, &short, &long).expect("a linear scan");
});
}
#[test]
fn a_long_tag_prefix_cannot_multiply_memory() {
in_child!(|| {
const PREFIX: usize = 1 << 20;
const TAGS: usize = 4_000;
let long = "e".repeat(PREFIX);
let inputs = [
format!("%TAG !e! tag:{long}:\n---\n{}", "- !e!x a\n".repeat(TAGS)),
format!("%TAG !! tag:{long}:\n---\n{}", "- !!x a\n".repeat(TAGS)),
format!("%TAG ! tag:{long}:\n---\n{}", "- !x a\n".repeat(TAGS)),
format!(
"%TAG !e! tag:yaml.org,2002:{long}:\n---\n{}",
"- !e!x a\n".repeat(TAGS)
),
];
for input in &inputs {
for (entry_point, result) in entry_points(input) {
let error = result.expect_err(entry_point);
let limit = error.limit().map(LimitExceeded::kind);
assert_eq!(
limit,
Some(LimitKind::TagExpansion),
"{entry_point}: {error}"
);
}
}
});
}
#[test]
fn an_alias_cannot_multiply_a_long_tag() {
in_child!(|| {
const ALIASES: usize = 4_000;
let long = "e".repeat(1 << 20);
let aliases = "- *x\n".repeat(ALIASES);
let limits = Limits::default().with_max_alias_expansion_bytes(8 << 20);
let inputs = [
format!("%TAG !e! tag:{long}:\n---\n- &x !e!v a\n{aliases}"),
format!("---\n- &x !<tag:{long}:v> a\n{aliases}"),
format!("---\n- &x !<tag:{long}:v> [a]\n{aliases}"),
format!("---\n- &x !<tag:{long}:v> {{a: b}}\n{aliases}"),
format!(
"---\n- &x {{a: !<tag:{long}:v> b}}\n{}",
"- {<<: *x}\n".repeat(ALIASES)
),
];
let options = ayaml::ParseOptions::new().with_limits(limits);
for input in &inputs {
let cursor = ayaml::Deserializer::from_str_with(input, &options)
.and_then(|mut cursor| cursor.next::<Value>().map(drop));
for (entry_point, result) in [
("parse_value", ok(ayaml::parse_value_with(input, &options))),
(
"parse_documents",
ok(ayaml::parse_documents_with(input, &options)),
),
(
"from_str_with",
ok(ayaml::from_str_with::<Value>(input, &options)),
),
("Deserializer::next", cursor),
] {
let error = result.expect_err(entry_point);
let limit = error.limit().map(LimitExceeded::kind);
assert_eq!(
limit,
Some(LimitKind::AliasExpansion),
"{entry_point}: {error}"
);
}
}
});
}
const SHAPES: [&str; 9] = [
"tagged flow mapping",
"flow sequence",
"flow mapping",
"flow pair",
"flow key",
"block sequence",
"block mapping",
"compact sequence",
"alias chain",
];
fn nested(shape: &str, depth: usize) -> String {
let lines = |entry: &str| {
let mut text: String = (0..depth)
.map(|level| format!("{}{entry}\n", " ".repeat(level)))
.collect();
text.push_str(&format!("{}0\n", " ".repeat(depth)));
text
};
match shape {
"tagged flow mapping" => format!("{}0{}", "!t {a: ".repeat(depth), "}".repeat(depth)),
"flow sequence" => format!("{}0{}", "[".repeat(depth), "]".repeat(depth)),
"flow mapping" => format!("{}0{}", "{a: ".repeat(depth), "}".repeat(depth)),
"flow pair" => format!(
"{}{}{}",
"[a: ".repeat(depth / 2),
if depth % 2 == 1 { "[0]" } else { "0" },
"]".repeat(depth / 2)
),
"flow key" => format!("{}0{}: 0\n", "[".repeat(depth - 1), "]".repeat(depth - 1)),
"block sequence" => lines("-"),
"block mapping" => lines("a:"),
"compact sequence" => format!("{}0\n", "- ".repeat(depth)),
"alias chain" => {
let mut chain = String::from("a0: &a0 {k: 0}\n");
for link in 1..depth - 1 {
chain.push_str(&format!("a{link}: &a{link} {{k: *a{}}}\n", link - 1));
}
chain
}
_ => unreachable!("{shape}"),
}
}
fn on_small_stack(body: impl FnOnce() + Send + 'static) {
std::thread::Builder::new()
.stack_size(2 << 20)
.spawn(body)
.expect("spawn")
.join()
.expect("no panic");
}
fn limited_entry_points(
input: &str,
limits: &Limits,
) -> Vec<(&'static str, Result<(), ayaml::Error>)> {
let options = ayaml::ParseOptions::new().with_limits(limits.clone());
let cursor = |next: fn(&mut ayaml::Deserializer<'_>) -> Result<(), ayaml::Error>| {
ayaml::Deserializer::from_str_with(input, &options).and_then(|mut cursor| next(&mut cursor))
};
vec![
(
"parse_events_with",
ayaml::parse_events_with(input, &options)
.and_then(Iterator::collect::<Result<Vec<_>, _>>)
.map(drop),
),
(
"parse_value_with",
ok(ayaml::parse_value_with(input, &options)),
),
(
"parse_documents_with",
ok(ayaml::parse_documents_with(input, &options)),
),
(
"from_str_with",
ok(ayaml::from_str_with::<Value>(input, &options)),
),
(
"from_str_with (serde_json)",
ok(ayaml::from_str_with::<serde_json::Value>(input, &options)),
),
(
"from_str_with (IgnoredAny)",
ok(ayaml::from_str_with::<IgnoredAny>(input, &options)),
),
(
"Deserializer::next",
cursor(|cursor| cursor.next::<Value>().map(drop)),
),
(
"Deserializer::next_borrowed",
cursor(|cursor| cursor.next_borrowed::<serde_json::Value>().map(drop)),
),
(
"Deserializer::next_seed",
cursor(|cursor| {
cursor
.next_seed(std::marker::PhantomData::<Value>)
.map(drop)
}),
),
(
"Deserializer::next_seed_borrowed",
cursor(|cursor| {
cursor
.next_seed_borrowed(std::marker::PhantomData::<IgnoredAny>)
.map(drop)
}),
),
]
}
fn value_paths(input: &str, limits: &Limits) -> Vec<(&'static str, Result<(), ayaml::Error>)> {
let parse_options = ayaml::ParseOptions::new().with_limits(limits.clone());
let emit_options = ayaml::EmitOptions::new().with_limits(limits.clone());
let value = ayaml::parse_value_with(input, &parse_options).expect("parse");
let events = ayaml::parse_events_with(input, &parse_options)
.and_then(Iterator::collect::<Result<Vec<_>, _>>)
.expect("events");
let mut merged = value.clone();
let mut hasher = std::collections::hash_map::DefaultHasher::new();
value.hash(&mut hasher);
let debug = format!("{value:?}");
vec![
("from_value", ok(ayaml::from_value::<Value>(value.clone()))),
(
"from_value (serde_json)",
ok(ayaml::from_value::<serde_json::Value>(value.clone())),
),
("to_value", ok(ayaml::to_value(&value))),
(
"to_string_value_with",
ok(ayaml::to_string_value_with(&value, &emit_options)),
),
(
"to_string_with",
ok(ayaml::to_string_with(&value, &emit_options)),
),
(
"to_string_documents_with",
ok(ayaml::to_string_documents_with(
std::slice::from_ref(&value),
&emit_options,
)),
),
(
"to_string_events_with",
ok(ayaml::to_string_events_with(&events, &emit_options)),
),
(
"to_writer_event_stream_with",
ayaml::parse_events_with(input, &parse_options).and_then(|stream| {
ayaml::to_writer_event_stream_with(&mut Vec::new(), stream, &emit_options)
}),
),
("apply_merge_keys", merged.apply_merge_keys()),
("clone, eq, hash, debug", {
assert_eq!(merged, value);
assert_ne!(debug, "");
Ok(())
}),
]
}
fn limited_emitters(input: &str, limits: &Limits) -> Vec<(&'static str, Result<(), ayaml::Error>)> {
let value = ayaml::parse_value(input).expect("parse");
let documents = std::slice::from_ref(&value);
let events = ayaml::parse_events(input)
.and_then(Iterator::collect::<Result<Vec<_>, _>>)
.expect("events");
let options = ayaml::EmitterOptions::default();
let emit = ayaml::EmitOptions::new().with_limits(limits.clone());
let styled = emit.clone().with_styles(ayaml::EmitterStyles::default());
let emitter = ayaml::Emitter::new(limits, &options);
vec![
(
"to_string_value_with",
ok(ayaml::to_string_value_with(&value, &emit)),
),
(
"to_string_value_with (styles)",
ok(ayaml::to_string_value_with(&value, &styled)),
),
(
"to_writer_value_with",
ayaml::to_writer_value_with(&mut Vec::new(), &value, &emit),
),
(
"to_writer_value_with (styles)",
ayaml::to_writer_value_with(&mut Vec::new(), &value, &styled),
),
("to_string_with", ok(ayaml::to_string_with(&value, &emit))),
(
"to_writer_with",
ayaml::to_writer_with(&mut Vec::new(), &value, &emit),
),
(
"to_string_documents_with",
ok(ayaml::to_string_documents_with(documents, &emit)),
),
(
"to_writer_documents_with",
ayaml::to_writer_documents_with(&mut Vec::new(), documents, &emit),
),
(
"to_string_events_with",
ok(ayaml::to_string_events_with(&events, &emit)),
),
(
"to_writer_events_with",
ayaml::to_writer_events_with(&mut Vec::new(), &events, &emit),
),
(
"to_writer_event_stream_with",
ayaml::parse_events(input).and_then(|stream| {
ayaml::to_writer_event_stream_with(&mut Vec::new(), stream, &emit)
}),
),
("Emitter::to_string", ok(emitter.to_string(&value))),
(
"Emitter::value_to_string",
ok(emitter.value_to_string(&value)),
),
(
"Emitter::documents_to_string",
ok(emitter.documents_to_string(documents)),
),
]
}
fn limited_readers(input: &str, limits: &Limits) -> Vec<(&'static str, Result<(), ayaml::Error>)> {
#[cfg_attr(
not(feature = "libyaml-compat"),
allow(
unused_mut,
reason = "the compat reader is pushed only with that feature"
)
)]
let mut readers = limited_entry_points(input, limits);
#[cfg(feature = "libyaml-compat")]
readers.push((
"compat::parse_events_eager_with",
ok(ayaml::compat::parse_events_eager_with(
input,
&ayaml::compat::ParseOptions::new().with_limits(limits.clone()),
)),
));
readers
}
fn assert_depth_error(shape: &str, name: &str, result: Result<(), ayaml::Error>) {
if stopped_where_json_cannot_follow(shape, &result) {
return;
}
if shape == "alias chain"
&& (name.ends_with("parse_events_with") || name.ends_with("parse_events_eager_with"))
{
result.unwrap_or_else(|error| panic!("{shape}, {name}: {error}"));
return;
}
assert_depth_error_kind(name, &result.expect_err(name));
}
fn assert_depth_error_kind(name: &str, error: &ayaml::Error) {
if name.starts_with("compat") {
assert_eq!(error.kind(), ErrorKind::Serde, "{name}: {error}");
assert_eq!(error.message(), "recursion limit exceeded", "{name}");
assert_eq!(
error.limit().map(LimitExceeded::kind),
Some(LimitKind::Depth),
"{name}"
);
} else {
assert_eq!(error.kind(), ErrorKind::Limit, "{name}: {error}");
assert!(error.to_string().contains("depth"), "{name}: {error}");
assert_eq!(
error.limit().map(LimitExceeded::kind),
Some(LimitKind::Depth),
"{name}"
);
}
}
#[test]
fn blank_and_comment_lines_do_not_count_against_max_events() {
in_child!(|| {
let lines = Limits::default().max_events + 1;
for line in ["\n", "#\n", " # c\n"] {
let input = format!("a: 1\n{}b: 2\n", line.repeat(lines));
for (name, result) in entry_points(&input)
.into_iter()
.chain(limited_readers(&input, &Limits::default()))
{
result.unwrap_or_else(|error| panic!("{line:?}, {name}: {error}"));
}
}
});
}
#[test]
fn max_depth_above_the_cap_is_rejected_on_every_entry_point() {
in_child!(|| {
let over = Limits::default().with_max_depth(MAX_DEPTH_CAP + 1);
let at_cap = Limits::default().with_max_depth(MAX_DEPTH_CAP);
let input = "a: [1, {b: 2}]\n";
for (name, result) in limited_readers(input, &over)
.into_iter()
.chain(limited_emitters(input, &over))
{
let error = result.expect_err(name);
assert_eq!(error.kind(), ErrorKind::Limit, "{name}: {error}");
let expected = format!("max_depth {}", MAX_DEPTH_CAP + 1);
assert!(error.to_string().contains(&expected), "{name}: {error}");
}
for (name, result) in limited_readers(input, &at_cap)
.into_iter()
.chain(limited_emitters(input, &at_cap))
{
result.unwrap_or_else(|error| panic!("{name}: {error}"));
}
});
}
#[test]
fn every_entry_point_fits_a_small_stack_at_the_depth_cap() {
in_child!(|| {
on_small_stack(|| {
let limits = Limits::default().with_max_depth(MAX_DEPTH_CAP);
for shape in SHAPES {
let input = nested(shape, MAX_DEPTH_CAP);
for (name, result) in limited_entry_points(&input, &limits)
.into_iter()
.chain(value_paths(&input, &limits))
{
assert_fits(shape, name, result);
}
for (name, result) in
limited_entry_points(&nested(shape, MAX_DEPTH_CAP + 1), &limits)
{
assert_depth_error(shape, name, result);
}
}
});
},);
}
fn stopped_where_json_cannot_follow(shape: &str, result: &Result<(), ayaml::Error>) -> bool {
let expected = match shape {
"tagged flow mapping" => "expected any valid JSON value",
"flow key" => "expected a string key",
_ => return false,
};
result
.as_ref()
.is_err_and(|error| error.to_string().contains(expected))
}
fn assert_fits(shape: &str, name: &str, result: Result<(), ayaml::Error>) {
if !stopped_where_json_cannot_follow(shape, &result) {
result.unwrap_or_else(|error| panic!("{shape}, {name}: {error}"));
}
}
#[test]
fn default_entry_points_fit_a_small_stack_at_the_default_depth() {
in_child!(|| {
on_small_stack(|| {
for shape in SHAPES {
for (name, result) in entry_points(&nested(shape, MAX_DEPTH)) {
assert_fits(shape, name, result);
}
for (name, result) in entry_points(&nested(shape, MAX_DEPTH + 1)) {
assert_depth_error(shape, name, result);
}
}
});
},);
}
#[test]
fn deep_nesting_is_a_limit_error_on_a_small_stack() {
in_child!(|| {
on_small_stack(|| {
let limits = Limits::default().with_max_depth(MAX_DEPTH_CAP);
for shape in SHAPES {
let depth = if shape.starts_with("block") {
1_000
} else {
10_000
};
let input = nested(shape, depth);
for (name, result) in limited_entry_points(&input, &limits) {
assert_depth_error(shape, name, result);
}
for (name, result) in entry_points(&input) {
assert_depth_error(shape, name, result);
}
}
});
});
}
fn wide(shape: &str, entries: usize) -> String {
let each = |entry: &dyn Fn(usize) -> String| (0..entries).map(entry).collect::<String>();
match shape {
"empty explicit keys" => "?\n".repeat(entries),
"explicit pairs" => each(&|index| format!("? k{index}\n: v\n")),
"block keys" => each(&|index| format!("k{index}:\n")),
"block pairs" => each(&|index| format!("k{index}: v\n")),
"block sequence" => "-\n".repeat(entries),
"block scalars" => "- a\n".repeat(entries),
"block properties" => each(&|index| format!("- &a{index} x\n")),
"empty flow pairs" => format!("{{{}}}", ":, ".repeat(entries)),
"flow keys" => format!("{{{}}}", each(&|index| format!("k{index}, "))),
"flow explicit keys" => format!("{{{}}}", each(&|index| format!("? k{index}, "))),
"flow explicit pairs" => format!("{{{}}}", each(&|index| format!("? k{index} : v, "))),
"flow sequence" => format!("[{}]", "a, ".repeat(entries)),
"flow pairs in a sequence" => format!("[{}]", each(&|index| format!("k{index}: v, "))),
"explicit pairs in a sequence" => {
format!("[{}]", each(&|index| format!("? k{index} : v, ")))
}
"empty keys in a sequence" => format!("[{}]", ": v, ".repeat(entries)),
_ => unreachable!("{shape}"),
}
}
#[test]
fn wide_collections_fit_a_small_stack() {
in_child!(|| {
on_small_stack(|| {
let limits = Limits::default();
for shape in [
"empty explicit keys",
"explicit pairs",
"block keys",
"block pairs",
"block sequence",
"block scalars",
"block properties",
"empty flow pairs",
"flow keys",
"flow explicit keys",
"flow explicit pairs",
"flow sequence",
"flow pairs in a sequence",
"explicit pairs in a sequence",
"empty keys in a sequence",
] {
let entries = if cfg!(debug_assertions) {
3_000
} else {
10_000
};
let input = wide(shape, entries);
let parse_options = ayaml::ParseOptions::new().with_limits(limits.clone());
let emit_options = ayaml::EmitOptions::new().with_limits(limits.clone());
let events = ayaml::parse_events_with(&input, &parse_options)
.and_then(Iterator::collect::<Result<Vec<_>, _>>)
.unwrap_or_else(|error| panic!("{shape}: {error}"));
ayaml::to_string_events_with(&events, &emit_options)
.unwrap_or_else(|error| panic!("{shape}, to_string_events: {error}"));
for (name, result) in limited_entry_points(&input, &limits)
.into_iter()
.chain(entry_points(&input))
{
if let Err(error) = result {
let duplicate = error.kind() == ErrorKind::DuplicateKey
|| error.to_string().contains("duplicate");
assert!(duplicate, "{shape}, {name}: {error}");
}
}
}
});
});
}
fn empty_node_bomb() -> String {
let mut bomb = String::from("a0: &a0\n");
bomb.push_str(&"-\n".repeat(9));
for level in 1..9 {
let previous = format!("*a{}", level - 1);
let row = [previous.as_str(); 9].join(", ");
bomb.push_str(&format!("a{level}: &a{level} [{row}]\n"));
}
bomb
}
#[cfg(feature = "bench-internals")]
#[test]
fn the_internal_composer_rejects_a_node_cost_of_zero() {
let input = "a: &x [1, {b: 2}, ~]\nb: *x\n";
let events = ayaml::internals::parse_events(input, &Limits::default()).expect("events");
let zero = Limits::default().with_node_cost_bytes(0);
let error = ayaml::internals::compose_events(&events, input.len(), &zero).expect_err("cost 0");
assert_eq!(error.kind(), ErrorKind::Limit, "{error}");
assert!(error.to_string().contains("node_cost_bytes 0"), "{error}");
let one = Limits::default().with_node_cost_bytes(1);
ayaml::internals::compose_events(&events, input.len(), &one).expect("cost 1");
}
#[test]
fn a_node_cost_of_zero_is_rejected_on_every_entry_point() {
in_child!(|| {
let zero = Limits::default().with_node_cost_bytes(0);
let one = Limits::default().with_node_cost_bytes(1);
let input = "a: &x [1, {b: 2}, ~]\nb: *x\n";
for (name, result) in limited_readers(input, &zero)
.into_iter()
.chain(limited_emitters(input, &zero))
{
let error = result.expect_err(name);
assert_eq!(error.kind(), ErrorKind::Limit, "{name}: {error}");
assert_eq!(error.limit(), None, "{name}");
assert!(
error.to_string().contains("node_cost_bytes 0"),
"{name}: {error}"
);
}
for (name, result) in limited_readers(input, &one)
.into_iter()
.chain(limited_emitters(input, &one))
{
result.unwrap_or_else(|error| panic!("{name}: {error}"));
}
let small = one
.with_max_alias_expansion_bytes(256 << 10)
.with_alias_bytes_per_input_byte(0);
for (name, result) in limited_readers(&empty_node_bomb(), &small) {
if name.ends_with("parse_events_with") || name.ends_with("parse_events_eager_with") {
result.unwrap_or_else(|error| panic!("{name}: {error}"));
continue;
}
let error = result.expect_err(name);
assert_eq!(
error.limit().map(LimitExceeded::kind),
Some(LimitKind::AliasExpansion),
"{name}: {error}"
);
}
});
}
#[test]
fn tag_expansion_is_accepted_up_to_its_limit() {
in_child!(|| {
let core = "tag:yaml.org,2002:".len();
let one_document =
"%TAG !e! tag:ab:\n---\n- !!str a\n- !e!x b\n- !y c\n- ! d\n- !<tag:z> e\n";
let two_documents = "--- !!str a\n--- !!str b\n";
let streams = |input: &str, limits: &Limits| {
let options = ayaml::ParseOptions::new().with_limits(limits.clone());
let cursor = ayaml::Deserializer::from_str_with(input, &options)
.and_then(|mut cursor| cursor.next::<Value>().map(drop));
vec![
(
"parse_events_with",
ayaml::parse_events_with(input, &options)
.and_then(Iterator::collect::<Result<Vec<_>, _>>)
.map(drop),
),
(
"parse_documents_with",
ok(ayaml::parse_documents_with(input, &options)),
),
("Deserializer::next", cursor),
]
};
type Readers = fn(&str, &Limits) -> Vec<(&'static str, Result<(), ayaml::Error>)>;
let cases: [(&str, usize, (usize, usize), Readers); 2] = [
(
one_document,
core + "tag:ab:".len() + 1,
(5, 3),
limited_readers,
),
(two_documents, 2 * core, (2, 5), streams),
];
let into_json = |result: &Result<(), ayaml::Error>| {
result
.as_ref()
.is_err_and(|error| error.to_string().contains("expected any valid JSON value"))
};
for (input, cost, (line, column), readers) in cases {
for limit in [cost, cost + 1] {
let limits = Limits::default().with_max_tag_expansion_bytes(limit);
for (name, result) in readers(input, &limits) {
if !into_json(&result) {
result.unwrap_or_else(|error| panic!("{name}, limit {limit}: {error}"));
}
}
}
let limits = Limits::default().with_max_tag_expansion_bytes(cost - 1);
for (name, result) in readers(input, &limits) {
if into_json(&result) {
continue;
}
let error = result.expect_err(name);
let limit = error.limit().expect("a structured limit");
assert_eq!(limit.kind(), LimitKind::TagExpansion, "{name}: {error}");
assert_eq!(limit.limit(), (cost - 1) as u64, "{name}");
assert_eq!(limit.observed(), cost as u64, "{name}");
let at = error.location().expect("a location");
assert_eq!((at.line(), at.column()), (line, column), "{name}: {error}");
}
}
});
}
#[test]
fn a_block_scalar_counts_its_header_toward_the_scalar_limit() {
in_child!(|| {
for input in [
"k: |\n ab\n c\n",
"k: >\n ab\n c\n",
"k: >-\n ab\n\n c\n",
"k: |+ # kept\n ab\n\n\n",
"- |2\n ab\n c\n",
"k: >\n ab\n c\nnext: 1\n",
] {
let start = input.find(['|', '>']).expect("an indicator");
let end = input.find("next").unwrap_or(input.len());
let size = end - start;
for limit in [size, size + 1] {
let limits = Limits::default().with_max_scalar_bytes(limit);
for (name, result) in limited_readers(input, &limits) {
result.unwrap_or_else(|error| panic!("{name}, {input:?}, {limit}: {error}"));
}
}
let limits = Limits::default().with_max_scalar_bytes(size - 1);
for (name, result) in limited_readers(input, &limits) {
let error = result.expect_err(name);
let limit = error.limit().expect("a structured limit");
assert_eq!(limit.kind(), LimitKind::ScalarBytes, "{name}: {error}");
assert_eq!(limit.observed(), size as u64, "{name}, {input:?}");
let at = error.span().expect("a span").start();
assert_eq!(at, start, "{name}, {input:?}");
}
}
});
}
const MEASURED: &str = "AYAML_ADVERSARIAL_MEASURED";
const MEASURES_MEMORY: bool = cfg!(target_os = "linux");
fn peak_growth(read: impl FnOnce()) -> u64 {
std::fs::write("/proc/self/clear_refs", "5").unwrap_or_else(|error| {
panic!("resetting the peak through /proc/self/clear_refs: {error}")
});
let before = proc_self_number("status", "VmRSS:").expect("VmRSS in /proc/self/status");
read();
let peak = proc_self_number("status", "VmHWM:").expect("VmHWM in /proc/self/status");
peak.saturating_sub(before) * 1024
}
type MeasuredRead = fn(&str) -> bool;
fn measured_readers() -> Vec<(&'static str, MeasuredRead)> {
vec![
("parse_value", |input| ayaml::parse_value(input).is_ok()),
("from_str_borrowed (IgnoredAny)", |input| {
ayaml::from_str_borrowed::<IgnoredAny>(input).is_ok()
}),
#[cfg(feature = "libyaml-compat")]
("compat::from_str", |input| {
ayaml::compat::from_str::<Value>(input).is_ok()
}),
]
}
const BLOCK_SCALARS: [(&str, &str, &str, u64); 4] = [
("literal short lines", "k: |\n", " a\n", 8),
("folded short lines", "k: >\n", " a\n", 8),
("folded blank runs", "k: >\n", " a\n\n", 10),
("literal blank lines", "k: |\n a\n", "\n", 16),
];
const FLOW_ENTRIES: usize = 200_000;
const MOST_PER_TOKEN: u64 = 160;
const OPEN_LINES: usize = 4 << 20;
const MOST_PER_LINE: u64 = 12;
fn memory_case(case: &str) -> (String, u64, bool) {
if case == REFUSED_DENSE {
let input = "- a\n".repeat(DENSE_LINES);
let bound = MOST_REFUSED_PER_BYTE * input.len() as u64;
return (input, bound, false);
}
if case == "flow sequence" {
let tokens = 2 * FLOW_ENTRIES + 3;
let input = format!("[{}a]\n", "a,".repeat(FLOW_ENTRIES));
return (input, MOST_PER_TOKEN * tokens as u64, true);
}
if case == "unclosed flow sequence" {
let input = format!("[{}", "\n".repeat(OPEN_LINES));
return (input, MOST_PER_LINE * OPEN_LINES as u64, false);
}
let (_, header, unit, most) = BLOCK_SCALARS
.into_iter()
.find(|(name, ..)| *name == case)
.unwrap_or_else(|| panic!("no memory case {case:?}"));
let input = format!("{header}{}", unit.repeat((4 << 20) / unit.len()));
let bound = most * input.len() as u64;
(input, bound, true)
}
fn measure_in_children(case: &str) {
if !MEASURES_MEMORY {
println!("{case}: not measured, since only Linux resets a process's peak of memory");
return;
}
for (reader, _) in measured_readers() {
let mut command = child_command("measure_one_read", CHILD_DEADLINE + CHILD_GRACE);
command.env(MEASURED, format!("{case}|{reader}"));
let run = run_command(command, CHILD_DEADLINE);
assert!(
run.passed(),
"{case}, {reader}: ended with {:?} after {:?}\n{}",
run.status,
run.elapsed,
run.output
);
}
}
#[test]
#[ignore = "only for a child of a memory test"]
fn measure_one_read() {
let Ok(measured) = std::env::var(MEASURED) else {
return;
};
in_child!(|| {
let (case, reader) = measured.split_once('|').expect("case|reader");
let (_, read) = measured_readers()
.into_iter()
.find(|(name, _)| *name == reader)
.unwrap_or_else(|| panic!("no reader {reader:?}"));
let (input, most, succeeds) = memory_case(case);
let mut succeeded = !succeeds;
let growth = if case == REFUSED_DENSE {
address_space_growth(|| succeeded = read(&input))
} else {
peak_growth(|| succeeded = read(&input))
};
assert_eq!(
succeeded, succeeds,
"{case}, {reader}: whether the read succeeded"
);
let ratio = growth as f64 / input.len() as f64;
println!("{case}, {reader}: {growth} bytes at the peak, {ratio:.2} times the input");
assert!(
growth <= most,
"{case}, {reader}: {growth} bytes at the peak, over the {most} expected"
);
});
}
#[test]
fn a_block_scalar_holds_memory_in_proportion_to_its_input() {
for (case, ..) in BLOCK_SCALARS {
measure_in_children(case);
}
}
#[test]
fn tokens_hold_memory_in_proportion_to_their_number() {
measure_in_children("flow sequence");
}
#[test]
fn an_error_at_the_end_holds_one_index_of_lines() {
measure_in_children("unclosed flow sequence");
}
#[test]
fn an_input_over_the_limit_is_refused_before_it_is_read() {
in_child!(|| {
let _ = entry_points("a: 1\n");
let _ = ayaml::parse_events("a: 1\n");
let _ = ayaml::SpannedTree::parse("a: 1\n");
let _ = ayaml::from_slice::<Value>(b"\xff");
let _ = ayaml::from_slice_borrowed::<IgnoredAny>(b"\xff");
let input = "\n".repeat(ayaml::MAX_INPUT_BYTES + 1);
let bytes = vec![0xff_u8; ayaml::MAX_INPUT_BYTES + 1];
let mut results = Vec::new();
let mut read = || {
results = entry_points(&input);
results.push(("parse_events", ok(ayaml::parse_events(&input))));
results.push(("SpannedTree::parse", ok(ayaml::SpannedTree::parse(&input))));
results.push((
"from_slice (not UTF-8)",
ok(ayaml::from_slice::<Value>(&bytes)),
));
results.push((
"from_slice_borrowed (not UTF-8)",
ok(ayaml::from_slice_borrowed::<IgnoredAny>(&bytes)),
));
};
let growth = if MEASURES_MEMORY {
Some(peak_growth(&mut read))
} else {
read();
None
};
for (name, result) in results {
let error = result.expect_err(name);
assert_eq!(
error.limit().map(LimitExceeded::kind),
Some(LimitKind::InputBytes),
"{name}: {error}"
);
assert_eq!(
error.location().map(|at| (at.line(), at.column())),
Some((1, 1)),
"{name}: {error}"
);
}
if let Some(growth) = growth {
println!("an input over the limit: {growth} bytes at the peak");
assert!(
growth <= 1 << 20,
"refusing an input over the limit held {growth} bytes"
);
}
});
}
fn address_space_growth(read: impl FnOnce()) -> u64 {
let before = proc_self_number("status", "VmSize:").expect("VmSize in /proc/self/status");
read();
let peak = proc_self_number("status", "VmPeak:").expect("VmPeak in /proc/self/status");
peak.saturating_sub(before) * 1024
}
const DENSE_LINES: usize = ayaml::MAX_INPUT_BYTES / 4;
const MOST_REFUSED_PER_BYTE: u64 = 8;
const REFUSED_DENSE: &str = "refused dense input";
#[test]
fn a_refused_dense_input_reserves_no_tokens_past_the_limit() {
if MEASURES_MEMORY {
measure_in_children(REFUSED_DENSE);
return;
}
in_child!(|| {
let (input, _, _) = memory_case(REFUSED_DENSE);
for (reader, read) in measured_readers() {
assert!(
!read(&input),
"{reader}: the input is over the default max_events"
);
}
});
}
fn nested_mapping_key(depth: usize, width: usize) -> String {
let mut inner = String::from("{");
for index in 0..width {
if index != 0 {
inner.push_str(", ");
}
inner.push_str(&format!("k{index}: {index}"));
}
inner.push('}');
for _ in 0..depth {
inner = format!("{{? {inner}: null}}");
}
inner
}
fn best_times(read: &dyn Fn(&str), short: &str, long: &str) -> (Duration, Duration) {
let started = Instant::now();
let (mut short_time, mut long_time) = (Duration::MAX, Duration::MAX);
let slack = Duration::from_millis(20);
while long_time >= short_time.saturating_mul(4).saturating_add(slack)
&& started.elapsed() < RETRY_BUDGET
{
short_time = short_time.min(time_runs(read, short, 1));
long_time = long_time.min(time_runs(read, long, 1));
}
(short_time, long_time)
}
#[test]
fn nested_key_hashing_does_not_multiply_by_depth() {
let width = if cfg!(debug_assertions) {
1_000
} else {
20_000
};
let short = nested_mapping_key(1, width);
let long = nested_mapping_key(100, width);
let check = |name: &str, read: &dyn Fn(&str) -> bool| {
assert!(read(&short) && read(&long), "{name}: a key is refused");
let timed = |input: &str| {
read(input);
};
let (short_time, long_time) = best_times(&timed, &short, &long);
assert!(
long_time < short_time * 4 + Duration::from_millis(20),
"{name}: depth 100 took {long_time:?}, depth 1 took {short_time:?}"
);
};
check("parse_value", &|input| ayaml::parse_value(input).is_ok());
check("from_str", &|input| ayaml::from_str::<Value>(input).is_ok());
#[cfg(feature = "libyaml-compat")]
check("compat", &|input| {
ayaml::compat::from_str::<Value>(input).is_ok()
});
}
#[test]
fn nested_mapping_duplicate_keys_are_found_in_every_reader() {
let inputs = [
"? {a: 1, b: 2}\n: 1\n? {b: 2, a: 1}\n: 2\n",
"? {outer: {a: 1, b: 2}}\n: 1\n? {outer: {b: 2, a: 1}}\n: 2\n",
];
for input in inputs {
for (name, result) in entry_points(input) {
if name.contains("seed") || name.contains("deserialize_any") {
continue;
}
let error = result.expect_err(name);
assert!(
error.kind() == ErrorKind::DuplicateKey || error.to_string().contains("duplicate"),
"{name}: {error}"
);
}
}
}
#[path = "adversarial/dos.rs"]
mod dos;
#[path = "adversarial/merge.rs"]
mod merge;
#[path = "adversarial/reader.rs"]
mod reader;
#[path = "adversarial/post_023.rs"]
mod post_023;