Files
mnovak 3bd87ebccf [roads] QA F-03: a kill-switch road with an error fails closed, through no exit
Any check() error used to make a road grant nothing, and for
never-online-without nothing meant no kill switch: an exit that stopped being
one (or left devices.json) silently turned off every kill switch through it.
The road is still reported as an error, but its subject's kill switch stays
on through no exit (only the mesh), and going direct to the internet is still
dropped. An expired kill switch ends as written. The road_file fuzz target's
deny-by-default check now allows exactly that narrowing and nothing else.
2026-11-25 08:46:30 +01:00

185 lines
6.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. The one exception fails closed (QA F-03): a kill-switch
//! road with an error may turn a kill switch on through no exit, and so drop going direct to the internet,
//! and nothing else.
//!
//! 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
})
}
fn baseline_plans() -> &'static std::collections::BTreeMap<roads::DeviceKey, roads::plan::Plan> {
static B: OnceLock<std::collections::BTreeMap<roads::DeviceKey, roads::plan::Plan>> = OnceLock::new();
B.get_or_init(|| {
compile(
&Store::from_parts(&files(None), Some(DIRECTORY), Some(DEVICES)),
now(),
)
.plans
})
}
/// 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 {
let kill = parsed
.as_ref()
.is_ok_and(|r| r.verb == roads::Verb::NeverOnlineWithout);
if kill {
let base = baseline_plans();
for (k, p) in &c.plans {
let b = &base[k];
let mut p = p.clone();
let ks = p.kill_switch.take();
assert!(
ks.as_ref().is_none_or(|ks| ks.through.is_none()) || ks == b.kill_switch,
"a refused kill switch named an exit"
);
assert!(
p.direct.iter().all(|d| b.direct.contains(d)),
"a refused kill switch added a direct subnet"
);
p.direct = b.direct.clone();
p.kill_switch = b.kill_switch.clone();
p.expires = b.expires.clone();
assert_eq!(&p, b, "a refused kill-switch road changed more than the kill switch");
}
} else {
assert_eq!(&plans, baseline(), "a refused road changed a plan");
}
}
});