b482e264d2
subject: app:<id> applied to every device in the mesh, so whoever could write one road (app:steam goes-direct 0.0.0.0/0) changed the tunnel of other people's devices, an exit and a classic router. An app road now needs the new header key on: (a person, group or device), and reaches only those devices; on: is forbidden on any other subject. The home fixture's steam road is on Mark's devices, so it leaves Jana's, Petr's and the router's plans. Four fixtures, a B-3 test (fails if app roads reach every device again), the property generator scopes app roads to a person, and the R-55 renaming rewrites on: like subject:.
442 lines
16 KiB
Rust
442 lines
16 KiB
Rust
//! QA R-55: renaming every id gives an isomorphic plan.
|
|
//!
|
|
//! Road ids are random, so nothing the compiler decides may depend on how ids sort. This test takes the home
|
|
//! store plus roads that hit the order-sensitive paths (two exits for one device, two kill switches through
|
|
//! different exits, two roads to one peer with different `via`), renames every road id, person id, group id,
|
|
//! device key, device name and service hostname consistently, compiles both, maps the renamed output back and
|
|
//! compares: plans, problems and `explain` must be the same up to the renaming.
|
|
//!
|
|
//! Regression-checked by reintroducing the bug, twice, and reverting: (1) the exit conflict resolved as "the
|
|
//! first exit by key wins" instead of "neither"; (2) two disagreeing kill switches resolved as "the one with
|
|
//! the smallest road id wins" instead of "no exit". Each made the property fail within a few cases
|
|
//! ("the plan of mark-pc depends on how ids are spelt").
|
|
|
|
mod common;
|
|
|
|
use common::{Parts, key, now};
|
|
use proptest::prelude::*;
|
|
use roads::{DeviceKey, Place, Store, compile};
|
|
use serde_json::Value;
|
|
use std::collections::{BTreeMap, BTreeSet};
|
|
|
|
const ALPHA: &[u8] = b"0123456789abcdefghjkmnpqrstvwxyz";
|
|
|
|
/// Roads that exercise the paths where an order could leak into the result.
|
|
fn extra_roads() -> Vec<(String, String)> {
|
|
let mark_pc = key(1);
|
|
let home = key(2);
|
|
let friend = key(6);
|
|
let road = |id: &str, slug: &str, lines: &[String]| {
|
|
(
|
|
format!("{id}-{slug}.md"),
|
|
format!(
|
|
"---\nid: {id}\n{}\ncreated: 2026-11-25T10:00:00Z\n---\n",
|
|
lines.join("\n")
|
|
),
|
|
)
|
|
};
|
|
vec![
|
|
// A second exit for mark-pc: with p4n6rb this is an exit conflict, so mark-pc exits through neither.
|
|
road(
|
|
"q7r2kd",
|
|
"mark-pc-exits-friend",
|
|
&[
|
|
format!("subject: device:{mark_pc}"),
|
|
"verb: exits-through".into(),
|
|
format!("object: exit:{friend}"),
|
|
],
|
|
),
|
|
// A second kill switch through another exit: the kill switch goes through no exit at all.
|
|
road(
|
|
"t3w8yn",
|
|
"mark-pc-kill-friend",
|
|
&[
|
|
format!("subject: device:{mark_pc}"),
|
|
"verb: never-online-without".into(),
|
|
format!("object: exit:{friend}"),
|
|
],
|
|
),
|
|
// Two roads from jana to the home server with different path hints: the peer gets no hint.
|
|
road(
|
|
"v5b1jx",
|
|
"jana-git-via-friend",
|
|
&[
|
|
"subject: person:jana".into(),
|
|
"verb: can-reach".into(),
|
|
"object: service:git.home.arpa".into(),
|
|
format!("via: device:{friend}"),
|
|
],
|
|
),
|
|
road(
|
|
"y2n4fs",
|
|
"jana-server-via-home",
|
|
&[
|
|
"subject: person:jana".into(),
|
|
"verb: can-reach".into(),
|
|
format!("object: device:{home}"),
|
|
"ports: [tcp/22]".into(),
|
|
format!("via: device:{home}"),
|
|
],
|
|
),
|
|
// Petr's second exit, the other way round: a conflict whose roads sort the other way.
|
|
road(
|
|
"0aa9zz",
|
|
"petr-exits-home",
|
|
&[
|
|
"subject: person:petr".into(),
|
|
"verb: exits-through".into(),
|
|
format!("object: exit:{home}"),
|
|
],
|
|
),
|
|
]
|
|
}
|
|
|
|
fn base_parts() -> Parts {
|
|
let mut p = Parts::home();
|
|
for (name, text) in extra_roads() {
|
|
p = p.with_road(&name, &text);
|
|
}
|
|
p
|
|
}
|
|
|
|
struct Rng(u64);
|
|
|
|
impl Rng {
|
|
fn next(&mut self) -> u64 {
|
|
// splitmix64
|
|
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
|
let mut z = self.0;
|
|
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
|
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
|
z ^ (z >> 31)
|
|
}
|
|
fn word(&mut self, alphabet: &[u8], len: usize) -> String {
|
|
(0..len)
|
|
.map(|_| alphabet[(self.next() % alphabet.len() as u64) as usize] as char)
|
|
.collect()
|
|
}
|
|
}
|
|
|
|
/// old -> new, for every kind of id at once (the kinds never share a spelling in the home store).
|
|
struct Renaming {
|
|
to_new: BTreeMap<String, String>,
|
|
to_old: BTreeMap<String, String>,
|
|
}
|
|
|
|
impl Renaming {
|
|
fn new(parts: &Parts, seed: u64) -> Renaming {
|
|
let mut rng = Rng(seed);
|
|
let dir: Value = serde_json::from_slice(&parts.directory).unwrap();
|
|
let devs: Value = serde_json::from_slice(&parts.devices).unwrap();
|
|
let mut taken: BTreeSet<String> = BTreeSet::new();
|
|
let mut olds: Vec<(String, u8)> = Vec::new(); // (old, kind)
|
|
for (name, _) in &parts.roads {
|
|
olds.push((name.split('-').next().unwrap().to_string(), 0));
|
|
}
|
|
for p in dir["people"].as_array().unwrap() {
|
|
olds.push((p["id"].as_str().unwrap().to_string(), 1));
|
|
}
|
|
for g in dir["groups"].as_array().unwrap() {
|
|
olds.push((g["id"].as_str().unwrap().to_string(), 1));
|
|
}
|
|
for d in devs["devices"].as_array().unwrap() {
|
|
olds.push((d["key"].as_str().unwrap().to_string(), 2));
|
|
olds.push((d["name"].as_str().unwrap().to_string(), 3));
|
|
for s in d["services"].as_array().into_iter().flatten() {
|
|
olds.push((s["host"].as_str().unwrap().to_string(), 4));
|
|
}
|
|
}
|
|
for (o, _) in &olds {
|
|
taken.insert(o.clone());
|
|
}
|
|
// `back` maps strings anywhere in the output, so a new id must never spell a word the output already
|
|
// holds for another reason: a group renamed to `in` turned every firewall `"direction": "in"` into
|
|
// the group's old name (seed 8124609985917702487). Reserve every string the plans and problems hold.
|
|
fn strings(v: &Value, out: &mut BTreeSet<String>) {
|
|
match v {
|
|
Value::String(s) => {
|
|
out.insert(s.clone());
|
|
}
|
|
Value::Array(a) => a.iter().for_each(|x| strings(x, out)),
|
|
Value::Object(m) => m.iter().for_each(|(k, x)| {
|
|
out.insert(k.clone());
|
|
strings(x, out);
|
|
}),
|
|
_ => {}
|
|
}
|
|
}
|
|
let c = compile(
|
|
&Store::from_parts(&parts.roads, Some(&parts.directory), Some(&parts.devices)),
|
|
now(),
|
|
);
|
|
strings(
|
|
&serde_json::to_value(c.plans.values().collect::<Vec<_>>()).unwrap(),
|
|
&mut taken,
|
|
);
|
|
strings(&serde_json::to_value(&c.problems).unwrap(), &mut taken);
|
|
let mut to_new = BTreeMap::new();
|
|
for (old, kind) in olds {
|
|
let new = loop {
|
|
let cand = match kind {
|
|
0 => rng.word(ALPHA, 6),
|
|
1 => {
|
|
let len = 1 + (rng.next() % 12) as usize;
|
|
rng.word(
|
|
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-",
|
|
len,
|
|
)
|
|
}
|
|
2 => {
|
|
let mut b = [0u8; 32];
|
|
for x in b.iter_mut() {
|
|
*x = rng.next() as u8;
|
|
}
|
|
DeviceKey::from_bytes(&b).to_string()
|
|
}
|
|
3 => format!("n{}", rng.word(b"abcdefghijklmnopqrstuvwxyz0123456789-", 7)),
|
|
_ => format!("{}.test", rng.word(b"abcdefghijklmnopqrstuvwxyz", 8)),
|
|
};
|
|
if taken.insert(cand.clone()) {
|
|
break cand;
|
|
}
|
|
};
|
|
to_new.insert(old, new);
|
|
}
|
|
let to_old = to_new.iter().map(|(a, b)| (b.clone(), a.clone())).collect();
|
|
Renaming { to_new, to_old }
|
|
}
|
|
|
|
fn new_of(&self, s: &str) -> String {
|
|
self.to_new.get(s).cloned().unwrap_or_else(|| s.to_string())
|
|
}
|
|
|
|
/// A `kind:value` reference with its value renamed (subnets are left alone).
|
|
fn reference(&self, r: &str) -> String {
|
|
match r.split_once(':') {
|
|
Some((kind, v)) if kind != "subnet" => format!("{kind}:{}", self.new_of(v)),
|
|
_ => r.to_string(),
|
|
}
|
|
}
|
|
|
|
fn apply(&self, parts: &Parts) -> Parts {
|
|
let mut dir: Value = serde_json::from_slice(&parts.directory).unwrap();
|
|
for p in dir["people"].as_array_mut().unwrap() {
|
|
p["id"] = Value::String(self.new_of(p["id"].as_str().unwrap()));
|
|
}
|
|
for g in dir["groups"].as_array_mut().unwrap() {
|
|
g["id"] = Value::String(self.new_of(g["id"].as_str().unwrap()));
|
|
for m in g["members"].as_array_mut().unwrap() {
|
|
*m = Value::String(self.new_of(m.as_str().unwrap()));
|
|
}
|
|
}
|
|
let mut devs: Value = serde_json::from_slice(&parts.devices).unwrap();
|
|
for d in devs["devices"].as_array_mut().unwrap() {
|
|
for k in ["key", "name", "owner"] {
|
|
if let Some(v) = d.get(k).and_then(|v| v.as_str()).map(|s| self.new_of(s)) {
|
|
d[k] = Value::String(v);
|
|
}
|
|
}
|
|
for s in d
|
|
.get_mut("services")
|
|
.and_then(|s| s.as_array_mut())
|
|
.into_iter()
|
|
.flatten()
|
|
{
|
|
s["host"] = Value::String(self.new_of(s["host"].as_str().unwrap()));
|
|
}
|
|
}
|
|
let roads = parts
|
|
.roads
|
|
.iter()
|
|
.map(|(name, bytes)| {
|
|
let (id, rest) = name.split_once('-').unwrap();
|
|
let text = String::from_utf8(bytes.clone()).unwrap();
|
|
let mut out = String::new();
|
|
let mut in_header = 0;
|
|
for line in text.split_inclusive('\n') {
|
|
if line.trim_end() == "---" {
|
|
in_header += 1;
|
|
out.push_str(line);
|
|
continue;
|
|
}
|
|
if in_header == 1
|
|
&& let Some((k, v)) = line.trim_end_matches(['\n', '\r']).split_once(": ")
|
|
{
|
|
let v2 = match k {
|
|
"id" => self.new_of(v),
|
|
"subject" | "on" | "object" | "via" => self.reference(v),
|
|
_ => v.to_string(),
|
|
};
|
|
out.push_str(&format!("{k}: {v2}\n"));
|
|
continue;
|
|
}
|
|
out.push_str(line);
|
|
}
|
|
(format!("{}-{rest}", self.new_of(id)), out.into_bytes())
|
|
})
|
|
.collect();
|
|
Parts {
|
|
roads,
|
|
directory: serde_json::to_vec(&dir).unwrap(),
|
|
devices: serde_json::to_vec(&devs).unwrap(),
|
|
}
|
|
}
|
|
|
|
/// Every string that is exactly a renamed id goes back to its old spelling.
|
|
fn back(&self, v: &mut Value) {
|
|
match v {
|
|
Value::String(s) => {
|
|
if let Some(o) = self.to_old.get(s.as_str()) {
|
|
*s = o.clone();
|
|
}
|
|
}
|
|
Value::Array(a) => a.iter_mut().for_each(|x| self.back(x)),
|
|
Value::Object(m) => m.values_mut().for_each(|x| self.back(x)),
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
fn path_back(&self, path: &str) -> String {
|
|
match path.strip_prefix("roads/").and_then(|n| n.split_once('-')) {
|
|
Some((id, rest)) => format!(
|
|
"roads/{}-{rest}",
|
|
self.to_old.get(id).cloned().unwrap_or(id.to_string())
|
|
),
|
|
None => path.to_string(),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Lists are sets in every plan (docs/FORMATS.md, "Every list is sorted"), so sorting each one by its text makes
|
|
/// two plans that differ only in the spelling of their ids comparable.
|
|
fn canonical(v: &mut Value) {
|
|
match v {
|
|
Value::Array(a) => {
|
|
a.iter_mut().for_each(canonical);
|
|
a.sort_by_key(|x| x.to_string());
|
|
}
|
|
Value::Object(m) => m.values_mut().for_each(canonical),
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
fn store_of(p: &Parts) -> Store {
|
|
Store::from_parts(&p.roads, Some(&p.directory), Some(&p.devices))
|
|
}
|
|
|
|
fn check_isomorphic(seed: u64) -> Result<(), TestCaseError> {
|
|
let parts = base_parts();
|
|
let ren = Renaming::new(&parts, seed);
|
|
let renamed = ren.apply(&parts);
|
|
let (s0, s1) = (store_of(&parts), store_of(&renamed));
|
|
let (c0, c1) = (compile(&s0, now()), compile(&s1, now()));
|
|
prop_assert!(c0.has_plans() && c1.has_plans());
|
|
prop_assert_eq!(c0.plans.len(), c1.plans.len());
|
|
|
|
for (k, p0) in &c0.plans {
|
|
let k1 = DeviceKey::new(&ren.new_of(k.as_str())).unwrap();
|
|
let mut a = serde_json::to_value(p0).unwrap();
|
|
let mut b = serde_json::to_value(&c1.plans[&k1]).unwrap();
|
|
ren.back(&mut b);
|
|
canonical(&mut a);
|
|
canonical(&mut b);
|
|
prop_assert_eq!(a, b, "the plan of {} depends on how ids are spelt", p0.name);
|
|
}
|
|
|
|
let problems =
|
|
|c: &roads::Compiled, back: bool| -> BTreeSet<(String, Option<String>, String, String)> {
|
|
c.problems
|
|
.iter()
|
|
.map(|p| {
|
|
(
|
|
if back {
|
|
ren.path_back(&p.path)
|
|
} else {
|
|
p.path.clone()
|
|
},
|
|
p.field.clone(),
|
|
p.code.to_string(),
|
|
format!("{:?}", p.severity),
|
|
)
|
|
})
|
|
.collect()
|
|
};
|
|
prop_assert_eq!(problems(&c0, false), problems(&c1, true));
|
|
|
|
let (d0, d1) = (s0.devices.as_ref().unwrap(), s1.devices.as_ref().unwrap());
|
|
for a in d0.devices.keys() {
|
|
for b in d0.devices.keys() {
|
|
let a1 = DeviceKey::new(&ren.new_of(a.as_str())).unwrap();
|
|
let b1 = DeviceKey::new(&ren.new_of(b.as_str())).unwrap();
|
|
for (p0, p1) in [
|
|
(Place::Device(b.clone()), Place::Device(b1.clone())),
|
|
(Place::Exit(b.clone()), Place::Exit(b1)),
|
|
] {
|
|
let w0: BTreeSet<String> = roads::explain(&c0, d0, a, &p0)
|
|
.iter()
|
|
.map(|r| r.to_string())
|
|
.collect();
|
|
let w1: BTreeSet<String> = roads::explain(&c1, d1, &a1, &p1)
|
|
.iter()
|
|
.map(|r| ren.to_old[r.as_str()].clone())
|
|
.collect();
|
|
prop_assert_eq!(w0, w1, "explain {:?} -> {:?}", a, p0);
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn the_extra_roads_reach_the_order_sensitive_paths() {
|
|
// Guards the fixture: without these the property would pass for a reason that has nothing to do with order.
|
|
let c = base_parts().compile();
|
|
let codes: BTreeSet<&str> = c.problems.iter().map(|p| p.code).collect();
|
|
assert!(codes.contains("exit.conflict"), "{codes:?}");
|
|
let mark = &c.plans[&key(1)];
|
|
assert!(mark.exit.is_none(), "two exits: neither");
|
|
assert_eq!(
|
|
mark.kill_switch.as_ref().unwrap().through,
|
|
None,
|
|
"two kill switches: no exit"
|
|
);
|
|
let jana_phone = &c.plans[&key(3)];
|
|
let server = jana_phone.peers.iter().find(|p| p.key == key(2)).unwrap();
|
|
assert_eq!(server.via, None, "two different path hints: none");
|
|
assert!(
|
|
c.errors().next().is_none(),
|
|
"{:?}",
|
|
c.errors().collect::<Vec<_>>()
|
|
);
|
|
}
|
|
|
|
/// A seed that once renamed the household group to `in`, a word the plans already hold (a firewall
|
|
/// direction). The renaming must avoid it, not the comparison.
|
|
#[test]
|
|
fn a_new_id_never_spells_a_word_of_the_output() {
|
|
check_isomorphic(8124609985917702487).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn the_identity_renaming_changes_nothing() {
|
|
let parts = base_parts();
|
|
let before = common::plans_bytes(&parts.compile());
|
|
let ren = Renaming {
|
|
to_new: BTreeMap::new(),
|
|
to_old: BTreeMap::new(),
|
|
};
|
|
assert_eq!(
|
|
common::plans_bytes(&compile(&store_of(&ren.apply(&parts)), now())),
|
|
before
|
|
);
|
|
}
|
|
|
|
proptest! {
|
|
#![proptest_config(ProptestConfig { cases: 300, failure_persistence: None, .. ProptestConfig::default() })]
|
|
|
|
#[test]
|
|
fn r55_renaming_every_id_gives_an_isomorphic_plan(seed in any::<u64>()) {
|
|
check_isomorphic(seed)?;
|
|
}
|
|
}
|