Files
mnovak 69e3a9377d [roads] QA F-01: a service road grants only that service
A firewall sees an address and a port, never a hostname, so a road to
photos.home.arpa compiled to home-server:443 and also opened git.home.arpa
there. Rules are now per service:

- devices.json services may carry their own mesh address (same rules as a
  device address, unique among all of them). A road to such a service compiles
  to that address only; the hosting device's plan lists it in the new field
  services[] so it answers on it, and DNS points there.
- A road to a service that shares its address and a port with another service
  is refused (service.shared), naming the others, instead of opening both.
  Narrowing ports: to a port nobody else serves on that address is allowed.
- A device: road reaches the whole device: its own address and its services'
  own addresses.

No Ianitor identity check is needed for this. The home fixture gives photos
its own address (100.96.1.2); tests that encoded the old host:port model are
updated, three new snapshot fixtures cover the address rules, and the golden
plans and pinned digest are regenerated. Mutation-checked: dropping the
refusal, or ignoring the service address, each fails an F-01 test.
2026-11-25 09:01:18 +01:00

448 lines
15 KiB
Rust

//! Mandatory test 1: every rule has a failing fixture, and its problem names the file and the field. A road
//! with an error grants nothing: every plan stays byte for byte what it was without that road.
//!
//! Fixtures: `tests/fixtures/invalid/expect.txt` lists each fixture file with its rule and field. The few
//! cases that cannot be a committed file (a 300 KiB file, a BOM, invalid UTF-8, a folder in roads/, ten
//! thousand files) are made here.
mod common;
use common::{Parts, fixtures, now, plans_bytes};
use roads::{Severity, Store, compile, rules};
use std::collections::BTreeSet;
struct Case {
kind: String,
file: String,
code: String,
field: Option<String>,
}
fn manifest() -> Vec<Case> {
let text = std::fs::read_to_string(fixtures().join("invalid").join("expect.txt")).unwrap();
text.lines()
.filter(|l| !l.starts_with('#') && !l.trim().is_empty())
.map(|l| {
let f: Vec<&str> = l.split_whitespace().collect();
assert_eq!(f.len(), 4, "bad manifest line {l}");
Case {
kind: f[0].into(),
file: f[1].into(),
code: f[2].into(),
field: (f[3] != "-").then(|| f[3].to_string()),
}
})
.collect()
}
fn inactive_code(code: &str) -> bool {
[
rules::ROAD_EXPIRED,
rules::ROAD_NO_DEVICES,
rules::ROAD_SELF,
rules::EXIT_CONFLICT,
rules::DIRECT_KILL_SWITCH,
rules::ROAD_FAMILY,
rules::DIRECT_TUNNELLED,
]
.contains(&code)
}
/// Snapshot errors that are a dangling reference, not a structural fault: reported, but plans are produced.
fn dangling_code(code: &str) -> bool {
[
rules::DEVICES_OWNER_UNKNOWN,
rules::DIRECTORY_MEMBER_UNKNOWN,
]
.contains(&code)
}
/// Runs one case; returns the codes it produced.
fn run(case: &Case, baseline: &[u8]) -> BTreeSet<String> {
let bytes = std::fs::read(
fixtures()
.join("invalid")
.join(if case.kind == "road" {
"roads"
} else {
"snapshots"
})
.join(&case.file),
)
.unwrap();
let parts = Parts::home();
let (parts, path) = match case.kind.as_str() {
"road" => (
parts.with_road(&case.file, std::str::from_utf8(&bytes).unwrap()),
format!("roads/{}", case.file),
),
"directory" => (
Parts {
directory: bytes,
..parts
},
"directory.json".to_string(),
),
"devices" => (
Parts {
devices: bytes,
..parts
},
"devices.json".to_string(),
),
k => panic!("unknown kind {k}"),
};
let c = parts.compile();
let hit = c
.problems
.iter()
.find(|p| p.path == path && p.code == case.code && p.field == case.field);
assert!(
hit.is_some(),
"{}: expected `{}` on field {:?} at {path}; got:\n{}",
case.file,
case.code,
case.field,
c.problems
.iter()
.map(|p| p.to_string())
.collect::<Vec<_>>()
.join("\n")
);
let hit = hit.unwrap();
// The message names the file and the field.
let line = hit.to_string();
assert!(
line.starts_with(&path) || line.starts_with(&format!("inactive: {path}")),
"{line}"
);
if let Some(f) = &case.field {
assert!(
line.contains(&format!(": {f}: ")),
"{line} does not name {f}"
);
}
if inactive_code(&case.code) {
assert_eq!(hit.severity, Severity::Inactive, "{line}");
} else {
assert_eq!(hit.severity, Severity::Error, "{line}");
if case.kind == "road" {
assert_eq!(
plans_bytes(&c),
baseline,
"{}: a road with an error changed a plan",
case.file
);
} else if dangling_code(&case.code) {
// QA F-04: a dangling reference drops only itself; everybody else keeps a plan.
assert!(
c.has_plans(),
"{}: one dangling reference stopped every plan",
case.file
);
} else {
assert!(
c.plans.is_empty(),
"{}: a snapshot with an error still produced plans",
case.file
);
}
}
c.problems.iter().map(|p| p.code.to_string()).collect()
}
/// Cases that are built in code, with the rule and field they must report.
fn generated(baseline: &[u8]) -> BTreeSet<String> {
let mut hit = BTreeSet::new();
let ok = Parts::home().road_text("k3f9q2");
let mut check = |parts: Parts, path: &str, code: &str, grants_nothing: bool| {
let c = parts.compile();
assert!(
c.problems.iter().any(|p| p.path == path && p.code == code),
"expected {code} at {path}; got {:?}",
c.problems
);
if grants_nothing {
assert_eq!(plans_bytes(&c), baseline, "{path}: {code} changed a plan");
}
hit.extend(c.problems.iter().map(|p| p.code.to_string()));
};
// file.size: one byte over 256 KiB, refused before parsing.
let big = format!("{ok}{}", "x".repeat(roads::road::MAX_FILE));
check(
Parts::home().with_road("b00001-big.md", &big),
"roads/b00001-big.md",
rules::FILE_SIZE,
true,
);
// file.encoding: a BOM, and bytes that are not UTF-8.
let mut parts = Parts::home();
parts.roads.push((
"b00002-bom.md".into(),
[&[0xEF, 0xBB, 0xBF][..], ok.as_bytes()].concat(),
));
check(parts, "roads/b00002-bom.md", rules::FILE_ENCODING, true);
let mut parts = Parts::home();
parts.roads.push((
"b00003-latin1.md".into(),
b"---\nid: b00003\nsubject: person:jan\xe1\n---\n".to_vec(),
));
check(parts, "roads/b00003-latin1.md", rules::FILE_ENCODING, true);
// id.duplicate: the same id in two files; neither grants anything.
let c = Parts::home().with_road("k3f9q2-copy.md", &ok).compile();
for path in [
"roads/k3f9q2-household-home-server.md",
"roads/k3f9q2-copy.md",
] {
assert!(c.problems.iter().any(|p| p.path == path
&& p.code == rules::ID_DUPLICATE
&& p.field.as_deref() == Some("id")));
}
let without = Parts::home().without_road("k3f9q2").compile();
assert_eq!(
plans_bytes(&c),
plans_bytes(&without),
"a duplicated road still granted"
);
hit.insert(rules::ID_DUPLICATE.into());
// file.count: more than 10,000 road files.
let mut parts = Parts::home();
for i in 0..roads::store::MAX_ROADS {
parts.roads.push((format!("z{i:05}-x.md"), b"x".to_vec()));
}
let s = parts.store();
assert!(s.problems.iter().any(|p| p.code == rules::FILE_COUNT));
assert!(s.roads.is_empty(), "nothing is read past the limit");
hit.insert(rules::FILE_COUNT.into());
// snapshot.json: a missing snapshot.
let parts = Parts::home();
let s = Store::from_parts(&parts.roads, None, Some(&parts.devices));
let c = compile(&s, now());
assert!(
c.problems
.iter()
.any(|p| p.path == "directory.json" && p.code == rules::SNAPSHOT_JSON)
);
assert!(c.plans.is_empty());
// store.roads: a store folder without roads/, and one whose roads/ is a file (QA F-07).
for make_roads in [false, true] {
let tmp = tempfile::tempdir().unwrap();
for f in ["directory.json", "devices.json"] {
std::fs::copy(common::home_dir().join(f), tmp.path().join(f)).unwrap();
}
if make_roads {
std::fs::write(tmp.path().join("roads"), "not a folder").unwrap();
}
let s = Store::load_dir(tmp.path()).unwrap();
assert!(
s.problems
.iter()
.any(|p| p.path == "roads" && p.code == rules::STORE_ROADS && p.is_error()),
"{:?}",
s.problems
);
}
hit.insert(rules::STORE_ROADS.into());
// road.family: an IPv4 subject to an IPv6 subnet needs an IPv6 route in devices.json (QA F-06).
let v6 = Parts::home()
.edit_devices(|d| {
d.replace(
r#""routes": ["192.168.100.0/24"]"#,
r#""routes": ["192.168.100.0/24", "fd00:1::/64"]"#,
)
})
.with_road(
"b00004-mark-v6.md",
"---\nid: b00004\nsubject: person:mark\nverb: can-reach\nobject: subnet:fd00:1::/64\ncreated: 2026-11-25T10:00:00Z\n---\n",
);
let c = v6.compile();
let hit_family = c
.problems
.iter()
.find(|p| p.path == "roads/b00004-mark-v6.md" && p.code == rules::ROAD_FAMILY);
assert!(
hit_family.is_some_and(|p| !p.is_error() && p.field.as_deref() == Some("object")),
"{:?}",
c.problems
);
hit.insert(rules::ROAD_FAMILY.into());
// service.shared: without its own address, photos shares home-server:443 with git (QA F-01). The road
// grants nothing: the plans equal those of the same store without it.
let shared = Parts::home().edit_devices(|d| d.replace(r#", "address": "100.96.1.2""#, ""));
let c = shared.compile();
assert!(
c.problems
.iter()
.any(|p| p.path == "roads/7tq0mz-jana-photos-until-sunday.md"
&& p.code == rules::SERVICE_SHARED
&& p.field.as_deref() == Some("object")
&& p.is_error()),
"{:?}",
c.problems
);
let without = shared.without_road("7tq0mz").compile();
assert_eq!(
plans_bytes(&c),
plans_bytes(&without),
"a refused service road granted"
);
hit.insert(rules::SERVICE_SHARED.into());
hit
}
#[test]
fn every_rule_has_a_failing_fixture_naming_the_file_and_the_field() {
let baseline = plans_bytes(&Parts::home().compile());
let mut covered = BTreeSet::new();
let cases = manifest();
for case in &cases {
let codes = run(case, &baseline);
covered.insert(case.code.clone());
let _ = codes;
}
covered.extend(generated(&baseline));
// file.kind needs a real folder: see `entries_that_are_not_road_files_are_reported` below.
covered.insert(rules::FILE_KIND.into());
let missing: Vec<&&str> = rules::ALL
.iter()
.filter(|c| !covered.contains(**c))
.collect();
assert!(
missing.is_empty(),
"rules without a failing fixture: {missing:?}"
);
eprintln!(
"validation: {} fixture files, {} rules covered",
cases.len(),
rules::ALL.len()
);
}
#[test]
fn the_home_fixture_is_clean_except_its_two_inactive_roads() {
let c = Parts::home().compile();
assert_eq!(c.errors().count(), 0, "{:?}", c.problems);
let codes: Vec<&str> = c.problems.iter().map(|p| p.code).collect();
assert_eq!(codes, [rules::DIRECT_KILL_SWITCH, rules::ROAD_EXPIRED]);
}
#[test]
fn entries_that_are_not_road_files_are_reported() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::copy(
common::home_dir().join("directory.json"),
root.join("directory.json"),
)
.unwrap();
std::fs::copy(
common::home_dir().join("devices.json"),
root.join("devices.json"),
)
.unwrap();
let roads = root.join("roads");
std::fs::create_dir_all(roads.join("sub")).unwrap();
std::fs::write(
roads.join("sub").join("k3f9q2-hidden.md"),
Parts::home().road_text("k3f9q2"),
)
.unwrap();
std::fs::write(roads.join("k3f9q2-household.md.swp"), "x").unwrap();
std::fs::write(roads.join("notes.txt"), "x").unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink("/etc/hostname", roads.join("c00001-link.md")).unwrap();
let store = Store::load_dir(root).unwrap();
let kinds: Vec<&str> = store
.problems
.iter()
.filter(|p| p.code == rules::FILE_KIND)
.map(|p| p.path.as_str())
.collect();
for p in [
"roads/sub",
"roads/k3f9q2-household.md.swp",
"roads/notes.txt",
] {
assert!(kinds.contains(&p), "{p} not reported: {kinds:?}");
}
#[cfg(unix)]
assert!(
kinds.contains(&"roads/c00001-link.md"),
"a symbolic link was followed"
);
assert!(
store.roads.is_empty(),
"the road inside a sub-folder was read"
);
}
#[test]
fn unknown_keys_are_errors_in_every_spelling() {
// QA R-35: a misspelt condition must never turn a temporary grant into a permanent one.
let base = Parts::home();
let original = base.road_text("7tq0mz");
for bad in ["untill", "Until", "until_", "expires", "Ports", "subjects"] {
let text = original.replace("until: ", &format!("{bad}: "));
let text = if bad == "Ports" || bad == "subjects" {
original.replace("ports: ", &format!("{bad}: "))
} else {
text
};
let c = Parts::home().replace_road("7tq0mz", &text).compile();
let p = c
.problems
.iter()
.find(|p| p.is_error())
.unwrap_or_else(|| panic!("{bad} accepted"));
if bad == "until_" {
// `_` is not in the key grammar `[A-Za-z][A-Za-z0-9]*`: refused as YAML syntax, before key checks.
assert_eq!(p.code, rules::YAML_SYNTAX, "{p}");
} else {
assert_eq!(
(p.code, p.field.as_deref()),
(rules::KEY_UNKNOWN, Some(bad)),
"{p}"
);
}
let jana = common::key(3);
assert!(
roads::explain(
&c,
Parts::home().store().devices.as_ref().unwrap(),
&jana,
&roads::Place::Service(roads::Hostname::new("photos.home.arpa").unwrap())
)
.iter()
.all(|r| r.as_str() != "7tq0mz"),
"{bad}: the road still grants"
);
}
}
#[test]
fn no_serde_flatten_anywhere_in_the_sources() {
// Rung 1 guardrail (QA R-35, fact G3): `serde(flatten)` silently turns `deny_unknown_fields` off.
let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
let mut stack = vec![src];
while let Some(dir) = stack.pop() {
for e in std::fs::read_dir(&dir).unwrap() {
let p = e.unwrap().path();
if p.is_dir() {
if p.file_name()
.is_some_and(|n| n != "target" && n != "fixtures")
{
stack.push(p);
}
} else if p.extension().is_some_and(|x| x == "rs") && !p.ends_with("validation.rs") {
let text = std::fs::read_to_string(&p).unwrap();
assert!(
!text.contains("serde(flatten"),
"{} uses serde(flatten)",
p.display()
);
}
}
}
}