Files
via-core/fuzz/fuzz_targets/road_file.rs
T
mnovak d5917e7aab [fuzz] cargo fuzz targets for the road-file parser and the control envelope
road_file: any bytes as one road file in the home store. The parser never panics;
a road that parses renders to canonical text that parses back to the same road
and rendering is a fixed point; compile never panics; and a file that does not
parse, or a road the compiler reports an error for, leaves every plan
byte-identical (deny by default).

envelope: Envelope::decode never panics; whatever it accepts re-encodes, decodes
to the same envelope and encodes stably.

Own workspace, as cargo fuzz lays it out. On Windows with the stable MSVC
toolchain and no sanitizer, build.rs links win_sections.c, which gives the
SanitizerCoverage counters their COFF section bounds (compiler-rt only ships them
inside a sanitizer runtime); the exact command is in road_file.rs.
2026-11-25 08:15:53 +01:00

119 lines
4.9 KiB
Rust

//! Fuzzes the road-file parser and the compiler behind it (QA review of PR #1).
//!
//! For any bytes as one road file, added to the home store:
//! 1. `Road::parse` never panics;
//! 2. a road that parses renders to canonical text that parses back to the same road, and rendering is a fixed
//! point (`render(parse(render(r))) == render(r)`);
//! 3. `compile` never panics (its `expect`/`unreachable!` paths assume the parser's checks);
//! 4. deny by default: a file that does not parse, or a road the compiler reports an error for, leaves every
//! plan byte-identical to the home store without it.
//!
//! Run on Linux with nightly: `cargo fuzz run road_file -- -max_total_time=600`.
//!
//! Run on Windows with the stable MSVC toolchain and no sanitizer (`cargo fuzz -s none` adds the PC table, which
//! does not link on COFF without a sanitizer runtime; `build.rs` + `win_sections.c` supply the counter bounds):
//! cd fuzz
//! RUSTFLAGS="-Cpasses=sancov-module -Cllvm-args=-sanitizer-coverage-level=4
//! -Cllvm-args=-sanitizer-coverage-inline-8bit-counters -Cllvm-args=-sanitizer-coverage-trace-compares
//! -Cllvm-args=-simplifycfg-branch-fold-threshold=0 -Ccodegen-units=1 --cfg fuzzing -Cdebug-assertions
//! -Clink-arg=/include:main" \
//! cargo build --release --target x86_64-pc-windows-msvc --target-dir target-none --bin road_file
//! target-none/x86_64-pc-windows-msvc/release/road_file.exe -max_total_time=600 corpus/road_file
//! Seed the corpus with `crates/roads/tests/fixtures/home/roads/*` and `fixtures/invalid/roads/*`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use roads::{Road, RoadId, Store, compile};
use std::sync::OnceLock;
macro_rules! home {
($f:literal) => {
(
$f,
include_bytes!(concat!("../../crates/roads/tests/fixtures/home/roads/", $f)).as_slice(),
)
};
}
const DIRECTORY: &[u8] = include_bytes!("../../crates/roads/tests/fixtures/home/directory.json");
const DEVICES: &[u8] = include_bytes!("../../crates/roads/tests/fixtures/home/devices.json");
const HOME: [(&str, &[u8]); 10] = [
home!("7tq0mz-jana-photos-until-sunday.md"),
home!("c0z5wn-petr-exits-friend.md"),
home!("e5yj1s-steam-goes-direct.md"),
home!("h2x8vd-mark-home-lan.md"),
home!("k3f9q2-household-home-server.md"),
home!("m6v0hp-petr-git-expired.md"),
home!("p4n6rb-mark-pc-exits-home.md"),
home!("r8m2tg-router-home-server.md"),
home!("w9c3ke-mark-pc-kill-switch.md"),
home!("x1d7qa-router-imported.md"),
];
fn now() -> jiff::Timestamp {
"2026-11-25T12:00:00+01:00".parse().unwrap()
}
fn files(extra: Option<(&str, &[u8])>) -> Vec<(String, Vec<u8>)> {
HOME.iter()
.copied()
.chain(extra)
.map(|(n, b)| (n.to_string(), b.to_vec()))
.collect()
}
fn plans_json(store: &Store) -> (Vec<String>, roads::Compiled) {
let c = compile(store, now());
(c.plans.values().map(|p| p.to_json()).collect(), c)
}
fn baseline() -> &'static Vec<String> {
static B: OnceLock<Vec<String>> = OnceLock::new();
B.get_or_init(|| plans_json(&Store::from_parts(&files(None), Some(DIRECTORY), Some(DEVICES))).0)
}
/// The id the file claims, so the file name can match it and the fuzzer reaches past `id.file-name`.
fn claimed_id(data: &[u8]) -> String {
std::str::from_utf8(data)
.ok()
.and_then(|t| {
t.lines()
.find_map(|l| l.strip_prefix("id: ").map(|v| v.trim_end_matches('\r')))
})
.filter(|v| RoadId::new(v).is_some())
.unwrap_or("zz9zz9")
.to_string()
}
fuzz_target!(|data: &[u8]| {
let id = claimed_id(data);
let name = format!("{id}-fuzz.md");
let path = format!("roads/{name}");
// 1 and 2: the parser, and the canonical round trip.
let parsed = Road::parse(&path, data);
if let Ok(road) = &parsed {
let text = road.render();
let again = match Road::parse(&path, text.as_bytes()) {
Ok(r) => r,
Err(p) => panic!("a rendered road does not parse: {p:?}\n--- rendered ---\n{text}"),
};
assert_eq!(again.render(), text, "render is not a fixed point");
assert_eq!(
(&again.id, &again.subject, again.verb, &again.object, &again.until, &again.ports, &again.via, again.classic, &again.created, &again.body),
(&road.id, &road.subject, road.verb, &road.object, &road.until, &road.ports, &road.via, road.classic, &road.created, &road.body),
"the canonical text means something else:\n{text}"
);
}
// 3 and 4: the compiler behind it, with the home store.
let store = Store::from_parts(&files(Some((&name, data))), Some(DIRECTORY), Some(DEVICES));
let (plans, c) = plans_json(&store);
let collides = HOME.iter().any(|(n, _)| n.starts_with(&format!("{id}-")));
let refused = parsed.is_err() || c.errors().any(|p| p.path == path);
if refused && !collides {
assert_eq!(&plans, baseline(), "a refused road changed a plan");
}
});