19 Commits

Author SHA1 Message Date
mnovak 06ce17fbfe docs(CLAUDE.md): no build or test while CPU or RAM is over 90 %, or a written-to drive over 95 % (Mark) 2026-11-29 01:55:21 +01:00
mnovak 175cb5dc60 Merge feature/roads: Day 2, roads, the compiler and proto v1 (PR #1)
QA findings F-01 to F-10 and B-3 fixed; B-1, F-12 and F-13 recorded as gaps. 91 tests on Windows (debug and release), 182 on Linux (Fabrica nixos-vm run rpnb803g4v0t0); fuzz 601 s per target, 0 crashes.
2026-11-26 05:24:37 +01:00
mnovak 88858ef235 docs: HANDOVER for v0.1.0, with the Linux run on Fabrica's runner (QA F-11 closed) and the fuzz rerun 2026-11-26 05:24:21 +01:00
mnovak 63eaed563b ci(linux): the toolchain step starts with nix, with no && inside, for Fabrica's preflight 2026-11-26 04:24:35 +01:00
mnovak 61e1f1da19 ci: the workspace once on Linux, on Fabrica's NixOS runner, before the tag (QA F-11)
Mark, 2026-11-26: the Linux run goes on Fabrica's server runner. The flake gives only the
toolchain (nixos-26.05, locked as Ianitor's); the pipeline runs cargo test --workspace in debug
and release. It builds and switches nothing on the server.
2026-11-26 04:21:10 +01:00
mnovak 3b39ce137d [roads] Mark's decision: person and group grants leave classic devices out
Mark, 2026-11-25, "Leave classic out": a grant to a person or a group covers
only their post-quantum devices. A classic router is reached only through a
device: road of its own, which says classic: true. Before, a person grant
covered their classic devices and so needed classic: true itself, and one
classic device blocked every road of its owner (builder's self-review #5).
New test a_person_grant_never_covers_their_classic_device, which fails with
the old compiler. Docs and HANDOVER updated: 91 tests, debug and release.
2026-11-25 10:58:57 +01:00
mnovak 18e0c50e08 [docs] HANDOVER: via-core after the QA fixes, with counts, fuzz runs and what is left 2026-11-25 09:24:29 +01:00
mnovak f21f8d59fc [docs] Day 2 after QA: what each finding changed, the gaps left, open question 1 answered
02_via-core.md now describes the model as built after the QA fixes (service
addresses, app on:, fail-closed kill switch, the tunnel winning over going
direct, dangling references, empty narrowing keys, missing roads/), maps every
finding to its resolution, and lists what is recorded rather than fixed:
B-1 replay (Day 3 proto v2), a kill-switch file that does not parse, the
app-level /0 bypass, case-sensitive ids, no Linux run, and explain/check as
admin, which blocks the Day 5 web view.
2026-11-25 09:09:01 +01:00
mnovak 73426592e4 [roads] QA F-10: IPv6 is checked by embedding the property's worlds into fd00::/96
The least-privilege oracle works in u32, so P-1 never saw an IPv6 address.
P-6v6 (1,000 cases) writes the same generated world with every IPv4 address a
as fd00::a and every /L as /(L+96) (the default route as ::/0), compiles both,
and requires the IPv6 plans to equal the IPv4 plans mapped the same way, with
the same problems. So every IPv6 path behaves like the IPv4 one P-1 checks
against the oracle. Mutation-checked: IPv6 hosts as /127 fails it at once.
2026-11-25 09:07:24 +01:00
mnovak b482e264d2 [roads] QA B-3: an app road names whose devices it is for, and reaches only those
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:.
2026-11-25 09:04:50 +01:00
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
mnovak 80f73a0154 [roads] QA F-02: going direct never takes what the tunnel carries out of it
A goes-direct subnet was only checked to be canonical, and the kill switch
dropped it only when it reached the internet, so 100.96.0.0/16 (every mesh
address) or the home LAN that the plan routes into the tunnel compiled cleanly.

Now, decided here because the plan has to say which route wins:
- a goes-direct subnet other than /0 that holds a mesh address is refused
  (direct.mesh);
- per device, a direct subnet inside a net the plan tunnels is dropped and
  reported (direct.tunnelled);
- a direct subnet that holds tunnelled nets keeps them in the tunnel, listed
  in the new plan field direct[].except. A platform that cannot honour except
  (an app-level bypass) must not apply the entry.

The F-02 test now checks that every overlap is covered by except, and that
only the mesh subnet is refused. Golden plans and the pinned jana-phone digest
are regenerated: the only change is the except lists. Plan format 1 has not
been released, so it changes in place.
2026-11-25 08:54:51 +01:00
mnovak ecafe194a5 [roads] QA F-05 and F-06: classic custom blocks, and roads across address families
F-05: plan.custom took classic from the road only, so a raw block on a classic
device without classic: true was labelled post-quantum. The device's flag now
counts too, as it already did for peers.

F-06: a device has one mesh address, so a can-reach road from IPv4 devices to
an IPv6 place compiled to rules that could never match, silently. Those
devices now get nothing for that road, and the road is reported inactive
(road.family) naming them.
2026-11-25 08:52:01 +01:00
mnovak ff78361165 [roads] QA F-08: a mesh address is never an internet address
devices.address refused only special and IPv4-embedding ranges, so a public
address was accepted, and an exit's forward-to-internet rule then covered that
device's mesh address. Mesh addresses now stay inside the not-internet ranges
(100.64.0.0/10, RFC 1918, ULA). Two fixtures, IPv4 and IPv6.
2026-11-25 08:50:23 +01:00
mnovak 31a46d0367 [roads] rename.rs: a new id never spells a word the output already holds
The R-55 property mapped renamed strings back anywhere in the output, so a
group renamed to `in` turned every firewall "direction": "in" into the
group's old name and failed about once in four runs (seed
8124609985917702487). The renaming now reserves every string the plans and
problems hold; the seed is kept as a fixed test, which fails without the
reservation. No change to the compiler.
2026-11-25 08:50:23 +01:00
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
mnovak acb98a6a1c [roads] QA F-04: a dangling owner or group member drops only itself, not every plan
Deleting a person from directory.json without editing devices.json left a
dangling owner, a snapshot error, and so no plans for anybody. A well-formed
owner or member id that is not a person is now reported on its own codes
(devices.owner-unknown, directory.member-unknown) and removed: the device is
ownerless, the member leaves the group. Malformed ids, duplicates and bad JSON
still stop every plan. Two new structural fixtures keep devices.owner and
directory.member covered.
2026-11-25 08:44:09 +01:00
mnovak b6cf29b9a0 [roads] QA F-07: a missing roads/ folder is store.roads, and roads/ is never followed through a link
A store folder without roads/ compiled to plans with no access and no problem,
kill switches included. It is now an error naming roads. A roads/ that is a
file or a symbolic link is refused the same way (the builder's self-review #8):
entries inside were already refused, the folder itself was followed.
2026-11-25 08:41:10 +01:00
mnovak 93ab087648 [roads] QA F-09: a present but empty until: or ports: is key.empty, never absent
Clearing a narrowing field (until:, until: # comment, ports:) used to read as
absent, which is the widest value: a permanent grant or all traffic. It is now
an error, so the road grants nothing. Three fixtures, FORMATS.md updated, and
the F-09 test is no longer ignored.
2026-11-25 08:40:01 +01:00
49 changed files with 1587 additions and 195 deletions
+21
View File
@@ -0,0 +1,21 @@
# via-core: the whole workspace once on Linux, on the server's NixOS runner, before the v0.1.0 tag (QA F-11; Mark,
# 2026-11-26: "Fabrica server runner"). By hand (Artifex → via-core → linux, or the hub's POST /api/runs with
# pipeline linux and a ref), or on a push to feature/roads or ci/linux. It builds and switches nothing on the
# server. Every run line starts with `nix` and has no `&&`, `;` or `|` (Fabrica's preflight reads each part's first
# word as a runner tool). The toolchain is the flake's `ci` shell (nixos-26.05).
name: linux
on:
push: [feature/roads, ci/linux]
manual: true
runner: nixos
env:
CARGO_TERM_COLOR: "never"
steps:
- id: toolchain
run: nix --extra-experimental-features "nix-command flakes" develop .#ci -c cargo --version
- id: test-debug
needs: [toolchain]
run: nix --extra-experimental-features "nix-command flakes" develop .#ci -c cargo test --workspace --no-fail-fast
- id: test-release
needs: [test-debug]
run: nix --extra-experimental-features "nix-command flakes" develop .#ci -c cargo test --workspace --release --no-fail-fast
+10
View File
@@ -16,3 +16,13 @@ Read HANDOVER.md and the day's docs/NN_*.md before writing code.
## Workflow
(D)TDD doc → tests → code. Branch, PR with critical self-review, merge --no-ff, push, verify.
No AI attribution in commits. No binaries in git. Say which build you are describing.
## This PC
- **No build or test while this PC is too busy** (Mark, 2026-11-25; drive limit raised 2026-11-29). Never start a
build or a test run (cargo, npm/pnpm, Playwright, fuzz, e2e, Fabrica runs on this PC) while the CPU or the RAM is
more than 90 % used, or any drive the run writes to (D:, E:, F:) is more than 95 % used. Check first; if one is
over, don't start, wait and check again. A run already going may finish. Never stop other sessions' work to make
room. Merging, pushing and editing files are not builds. In PowerShell: CPU
`(Get-CimInstance Win32_Processor | Measure-Object LoadPercentage -Average).Average`; RAM
`$o=Get-CimInstance Win32_OperatingSystem; (1-$o.FreePhysicalMemory/$o.TotalVisibleMemorySize)*100`; drives
`Get-PSDrive D,E,F`, used / (used + free).
+94
View File
@@ -0,0 +1,94 @@
# Handover — via-core
Newest entry first. Where this file and the code disagree, the code wins and the next entry says so.
## 2026-11-26 — v0.1.0 (owner session)
**Released:** `v0.1.0`, an annotated tag on the `--no-ff` merge of PR #1 into `main`, plus a Gitea release. Mark
chose "Tag + Gitea release now"; Artifex signing comes later. **Not audited.**
**Since the 2026-11-25 entry:**
- `3b39ce1`, Mark's decision: a person or group grant leaves classic devices out. They are reached only by their own
`device:` road; test `a_person_grant_never_covers_their_classic_device`.
- The pipeline `linux` (`.fabrica/artifex/linux.yaml`) and a toolchain-only flake (`nix develop .#ci`, nixos-26.05)
for Fabrica's NixOS runner. The library is unchanged since `3b39ce1`.
**Counts:**
| Run | Where | Result |
|:--|:--|:--|
| `cargo test --workspace` (debug and release) | Windows 10, cargo 1.99.0, at `3b39ce1` | 91 passed / 0 / 0 each |
| `cargo test --workspace` (debug and release) | **Linux**: Fabrica `nixos-vm` runner, run `rpnb803g4v0t0`, at `63eaed5` | 182 passed / 0 / 0 in total (91 each); exit 0, 164 s. This closes QA F-11 |
| fuzz `road_file` | Windows, at `3b39ce1` | 601 s, 228,925 executions, 0 crashes (at 100 % CPU) |
| fuzz `envelope` | Windows, at `3b39ce1` | 601 s, 12,748,163 executions, 0 crashes |
| clippy, fmt, `cargo deny`, `cargo audit` | Windows, at `7342659` | clean |
**Still open (recorded, not fixed):** B-1, a replayable plan; Day 3 wraps every plan in a signed envelope with
`serial` and `expires`, in via's `crates/control`. F-12, case-sensitive ids. F-13, which blocks the Day 5 web view.
## 2026-11-25 — QA findings fixed on `feature/roads` (owner session)
**Who owns this:** the Via owner session. It reviews, merges `--no-ff` and tags `v0.1.0`. Mark's decisions
go through the orchestrator session.
**Where it stands:** PR #1 (`feature/roads`) is open, not merged, not tagged. QA's review (head `635d380`)
found one blocker and five majors in the model; all are fixed on the branch, one commit each, each removing
the `#[ignore]` of its finding's test in `tests/qa_findings.rs`. `main` still holds only the bootstrap.
**Build described:** Windows 10, `cargo 1.99.0` / `rustc 1.99.0` stable MSVC, debug profile, at the branch
head named in the PR.
| Run | Result |
|:--|:--|
| `cargo test --workspace` | **91 passed, 0 failed, 0 ignored** (debug and `--release`) |
| `cargo clippy --workspace --all-targets -- -D warnings` | clean |
| `cargo fmt --all --check` | clean |
| `cargo deny check` | advisories ok, bans ok, licenses ok, sources ok |
| `cargo audit` | 80 crates, 0 vulnerabilities |
| fuzz `road_file` | **631 s, 807,395 executions, 0 crashes, 0 artifacts** (features 7,711 → 9,819; corpus 1,080 → 1,289), built at `7342659`, Windows MSVC, SanitizerCoverage, no sanitizer |
| fuzz `envelope` | **331 s, 17,441,113 executions, 0 crashes** (features 5,096 → 5,256), same build |
Per file: `proto/roundtrip` 6 · `roads` unit 16 · `attacks` 8 · `custom` 6 · `determinism` 4 · `explain` 6 ·
`least_privilege` 6 (P-1 5,000 cases: 1,706 with rules, 4,420 rules and 7,784 allowed IPs checked against the
oracle; P-6v6 1,000) · `qa_findings` 13 · `rename` 4 · `revocation` 10 · `validation` 5 (83 fixture files, 65
rules) · `via-cli/cli` 7.
**What changed after QA** (details in `docs/02_via-core.md`, "QA review of PR #1"):
| # | Change |
|:--|:--|
| F-01 | services may have their own mesh address (`devices.json` `services[].address`); a road to a service that shares its address and a port with another is `service.shared`; plans list the device's service addresses (`services[]`); a `device:` road reaches all of the device's addresses |
| F-02 | `direct.mesh`, `direct.tunnelled`, and `direct[].except` (tunnelled nets that stay in the tunnel) |
| F-03 | a kill-switch road with an error fails closed, through no exit |
| F-04 | a dangling owner or group member is reported and drops only itself (`devices.owner-unknown`, `directory.member-unknown`) |
| F-05 | custom blocks on a classic device are labelled classic |
| F-06 | cross-family roads give nothing to those devices and are reported (`road.family`) |
| F-07 | no `roads/`, or a `roads/` that is a file or a link, is `store.roads` |
| F-08 | mesh addresses are never internet addresses |
| F-09 | `until:` / `ports:` present but empty is `key.empty` |
| F-10 | P-6v6: IPv6 compiles like IPv4, by embedding into `fd00::/96` |
| B-3 | `app:` roads need `on:` (person, group or device) and reach only those devices |
| R-55 | QA's renaming property was flaky (a group renamed to `in`); fixed in the test, seed pinned |
| Mark | "Leave classic out" (2026-11-25): person and group grants cover only post-quantum devices; a classic device needs its own `device:` road with `classic: true`. Test `revocation.rs::a_person_grant_never_covers_their_classic_device`, mutation-checked |
The plan format gained `services` and `direct[].except`. Format 1 has not been released, so it changed in
place; the golden plans and the pinned CBOR digest were regenerated and the diff read by hand.
**Not fixed, recorded** (`docs/02_via-core.md`, Gaps):
- **B-1** proto v1 has no serial: Day 3's signed v2 carries a monotonic serial and `not_after`.
- **F-13** `explain` and `check` answer as an administrator: **blocks the Day 5 web view**.
- **F-12** ids are case-sensitive: decide with the people directory.
- **F-11** never run on Linux (WSL does not start on this PC): wanted before the tag.
- A kill-switch file that does not *parse* applies nothing (only reported).
**Decisions taken here that Mark may want to see:** services get their own mesh address (no Ianitor identity
check needed); `except` makes the tunnel win over going direct; app roads need `on:`.
**Next:** merge `--no-ff` into `main`, push, `git rev-parse HEAD origin/main` twice, tag `v0.1.0`, per
`F:\Akce\Via\handover\MERGE-PLAN.md`, once the Linux question (F-11) and the signed-release question are answered.
## 2026-11-25 — Day 2 built (builder), reviewed (QA)
The road model, validator, compiler, `explain`, the versioned CBOR control messages and the `via` command:
72 tests by the builder; QA added the renaming property, nine finding tests and two fuzz targets
(`road_file` 721 s, 1,116,471 executions; `envelope` 331 s; no crash; Windows, no sanitizer).
+1 -1
View File
@@ -1 +1 @@
da086f1cc965aee30351547c6ac466939c627e2f915d5c67314a73357f38f68a
8eaa80e6c40ff1541d125f0755fbdddc775f9210e830f2868d4b5e5cf05c1fa4
+244 -24
View File
@@ -1,7 +1,8 @@
//! The compiler: roads + people directory + device list + `now` → one [`Plan`] per device.
//!
//! Deny by default. A road with any error grants nothing; a valid road that is expired, or whose subject has no
//! devices, grants nothing and is reported as inactive. Without both snapshots no plan is produced at all.
//! devices, grants nothing and is reported as inactive. Restrictions fail closed instead: a kill-switch road
//! with an error still turns its subject's kill switch on, through no exit (only the mesh), QA F-03. Without both snapshots no plan is produced at all.
//! Every collection on the output path is ordered, so the same input gives the same bytes.
use crate::id::RoadId;
@@ -83,28 +84,55 @@ type RuleKey = (Direction, Net, Dst, Proto, Option<[u16; 2]>);
struct Extras {
direct: BTreeMap<DirectKey, BTreeSet<RoadId>>,
kill: BTreeMap<DeviceKey, BTreeSet<RoadId>>,
/// Kill-switch roads with an error: applied closed, through no exit.
kill_closed: BTreeSet<RoadId>,
custom: Vec<plan::Custom>,
}
/// The devices a subject covers: a person's are the devices they own; a group's, its members'; an app's, every
/// device.
pub fn subject_devices(subject: &Subject, dir: &Directory, devs: &Devices) -> BTreeSet<DeviceKey> {
impl Extras {
fn has_kill_switch(&self) -> bool {
!self.kill.is_empty() || !self.kill_closed.is_empty()
}
}
/// The devices a subject covers: a person's are the post-quantum devices they own; a group's, its members';
/// an app's, those of its `on` (QA B-3: never every device of the mesh). A classic (not post-quantum) device is
/// never covered by a person or a group: it is reached only by a `device:` road of its own, which says
/// `classic: true` (Mark, 2026-11-25: "Leave classic out").
pub fn subject_devices(
subject: &Subject,
on: Option<&Subject>,
dir: &Directory,
devs: &Devices,
) -> BTreeSet<DeviceKey> {
if let Subject::App(_) = subject {
return match on {
Some(s @ (Subject::Person(_) | Subject::Group(_) | Subject::Device(_))) => {
subject_devices(s, None, dir, devs)
}
_ => BTreeSet::new(),
};
}
devs.devices
.values()
.filter(|d| match subject {
Subject::Person(p) => d.owner.as_ref() == Some(p),
Subject::Group(g) => dir
Subject::Person(p) => !d.classic && d.owner.as_ref() == Some(p),
Subject::Group(g) => {
!d.classic
&& dir
.groups
.get(g)
.is_some_and(|g| d.owner.as_ref().is_some_and(|o| g.members.contains(o))),
.is_some_and(|g| d.owner.as_ref().is_some_and(|o| g.members.contains(o)))
}
Subject::Device(k) => &d.key == k,
Subject::App(_) => true,
Subject::App(_) => false,
})
.map(|d| d.key.clone())
.collect()
}
/// Devices by owner, built once per compile so resolving a subject does not scan every device.
/// Post-quantum devices by owner, built once per compile so resolving a subject does not scan every device.
/// Classic devices are left out: no person or group grant covers them.
struct Index {
by_owner: BTreeMap<crate::ids::PersonId, BTreeSet<DeviceKey>>,
}
@@ -112,7 +140,7 @@ struct Index {
impl Index {
fn new(devs: &Devices) -> Index {
let mut by_owner: BTreeMap<_, BTreeSet<DeviceKey>> = BTreeMap::new();
for d in devs.devices.values() {
for d in devs.devices.values().filter(|d| !d.classic) {
if let Some(o) = &d.owner {
by_owner.entry(o.clone()).or_default().insert(d.key.clone());
}
@@ -124,6 +152,7 @@ impl Index {
fn devices_of(
&self,
subject: &Subject,
on: Option<&Subject>,
dir: &Directory,
devs: &Devices,
) -> BTreeSet<DeviceKey> {
@@ -147,7 +176,12 @@ impl Index {
.then(|| k.clone())
.into_iter()
.collect(),
Subject::App(_) => devs.devices.keys().cloned().collect(),
Subject::App(_) => match on {
Some(s @ (Subject::Person(_) | Subject::Group(_) | Subject::Device(_))) => {
self.devices_of(s, None, dir, devs)
}
_ => BTreeSet::new(),
},
}
}
}
@@ -163,19 +197,23 @@ fn check(
let p = |field: &str, code, msg: String| {
Problem::error(&road.path, Some(field), code, msg).at(road.line_of(field))
};
match &road.subject {
let (field, who) = match (&road.subject, &road.on) {
(Subject::App(_), Some(on)) => ("on", on),
(s, _) => ("subject", s),
};
match who {
Subject::Person(id) if !dir.people.contains_key(id) => out.push(p(
"subject",
field,
r::SUBJECT_UNKNOWN,
format!("person `{id}` is not in directory.json"),
)),
Subject::Group(id) if !dir.groups.contains_key(id) => out.push(p(
"subject",
field,
r::SUBJECT_UNKNOWN,
format!("group `{id}` is not in directory.json"),
)),
Subject::Device(k) if !devs.devices.contains_key(k) => out.push(p(
"subject",
field,
r::SUBJECT_UNKNOWN,
format!("device {} is not in devices.json", k.short()),
)),
@@ -236,6 +274,32 @@ fn check(
format!("{h} serves only {}", served.join(", ")),
));
}
// A firewall sees an address and a port, never a hostname. If another service answers on the
// same address and one of the same ports, a rule for this one opens that one too: refuse, and
// name it, rather than grant more than the road says (QA F-01).
let wanted = road.ports.as_deref().unwrap_or(&s.ports);
let mut shared: Vec<String> = d
.services
.iter()
.filter(|o| {
o.host != *h
&& o.endpoint(d) == s.endpoint(d)
&& ports::overlaps(Some(wanted), Some(&o.ports))
})
.map(|o| o.host.to_string())
.collect();
if !shared.is_empty() {
shared.sort();
out.push(p(
"object",
r::SERVICE_SHARED,
format!(
"{h} shares {} and its ports with {}, so a rule for it would open them too; give {h} its own `address` in devices.json, narrow `ports`, or write a device: road",
s.endpoint(d),
shared.join(", ")
),
));
}
}
},
Some(Place::Subnet(n)) if road.verb == Verb::CanReach => match devs.router_of(n) {
@@ -247,6 +311,27 @@ fn check(
Some(d) if d.classic => classic_peers.push(&d.name),
Some(_) => {}
},
Some(Place::Subnet(n)) if road.verb == Verb::GoesDirect && n.prefix_len() > 0 => {
// Going direct never takes the mesh's own addresses out of the tunnel (QA F-02). The default
// route is the one exception: it keeps every tunnelled net in, as `except` (below).
let mut inside: Vec<&str> = devs
.mesh_addresses()
.filter(|(_, a)| n.contains_addr(&a.0))
.map(|(d, _)| d.name.as_str())
.collect();
if !inside.is_empty() {
inside.sort();
inside.dedup();
out.push(p(
"object",
r::DIRECT_MESH,
format!(
"{n} holds the mesh address of {}: mesh traffic never goes direct",
inside.join(", ")
),
));
}
}
Some(Place::Subnet(_)) => {}
None => {}
}
@@ -314,10 +399,31 @@ pub fn compile(store: &Store, now: Instant) -> Compiled {
let mut roads: Vec<&Road> = store.roads.iter().collect();
roads.sort_by(|a, b| a.id.cmp(&b.id));
for road in roads {
let subject = index.devices_of(&road.subject, dir, devs);
let subject = index.devices_of(&road.subject, road.on.as_ref(), dir, devs);
let problems = check(road, dir, devs, &subject);
if !problems.is_empty() {
out.problems.extend(problems);
// "Grants nothing" is right for a grant and wrong for a restriction: a kill switch whose exit stops
// being one, or leaves devices.json, must not switch the protection off (QA F-03). It stays on,
// through no exit: only the mesh. An expired kill switch ends as written; one that does not parse
// is not in the store at all (`via check` reports it).
if road.verb == Verb::NeverOnlineWithout {
let exit = match &road.object {
Some(Place::Exit(k)) => Some(k),
_ => None,
};
let live = road.until.as_ref().is_none_or(|u| u.at() > now);
for d in subject.iter().filter(|d| Some(*d) != exit) {
if live {
touch(d, road);
extras
.entry(d.clone())
.or_default()
.kill_closed
.insert(road.id.clone());
}
}
}
continue;
}
let inactive = |field: Option<&str>, code, msg: String| {
@@ -357,7 +463,7 @@ pub fn compile(store: &Store, now: Instant) -> Compiled {
let ports = road.ports.clone().unwrap_or_else(|| s.ports.clone());
(
d.key.clone(),
Net::host(d.address.0),
Net::host(s.endpoint(d).0),
false,
Some(ports),
Some(h.clone()),
@@ -372,15 +478,39 @@ pub fn compile(store: &Store, now: Instant) -> Compiled {
),
Place::Exit(_) => unreachable!("the parser refuses exit objects for can-reach"),
};
// A device road reaches the whole device: its own address and those of the services it hosts on
// an address of their own (same family as the sender only).
let extra: Vec<Net> = match object {
Place::Device(k) => devs.devices[k]
.services
.iter()
.filter_map(|s| s.address.map(|a| Net::host(a.0)))
.collect(),
_ => Vec::new(),
};
let mut other_family: Vec<&str> = Vec::new();
for from in subject.iter().filter(|d| **d != host) {
// A device has one mesh address. From an IPv4 address to an IPv6 place (or the other way)
// the rule could never match: grant nothing, and say so (QA F-06).
if devs.devices[from].address.0.is_ipv4() != dst.inner().addr().is_ipv4() {
other_family.push(&devs.devices[from].name);
continue;
}
touch(from, road);
effects += 1;
touch(&host, road);
let family = devs.devices[from].address.0.is_ipv4();
for d in std::iter::once(dst).chain(
extra
.iter()
.copied()
.filter(|n| n.inner().addr().is_ipv4() == family),
) {
out.grants.push(Grant::Reach {
road: road.id.clone(),
from: from.clone(),
host: host.clone(),
dst,
dst: d,
forward,
ports: ports.clone(),
dns: dns.clone(),
@@ -388,6 +518,26 @@ pub fn compile(store: &Store, now: Instant) -> Compiled {
});
}
}
if !other_family.is_empty() {
other_family.sort();
out.problems.push(inactive(
Some("object"),
r::ROAD_FAMILY,
format!(
"{dst} is {}, and the mesh address of {} is not: nothing granted there",
if dst.inner().addr().is_ipv4() {
"IPv4"
} else {
"IPv6"
},
other_family.join(", ")
),
));
if effects == 0 {
continue;
}
}
}
(Verb::ExitsThrough, Some(Place::Exit(exit))) => {
for from in subject.iter().filter(|d| *d != exit) {
touch(from, road);
@@ -443,7 +593,9 @@ pub fn compile(store: &Store, now: Instant) -> Compiled {
.custom
.push(plan::Custom {
road: road.id.clone(),
classic: road.is_classic(),
// The device decides, like a peer's flag: a classic device's raw block is never
// labelled post-quantum, whatever the road says (QA F-05).
classic: road.is_classic() || devs.devices[d].classic,
raw: raw.clone(),
});
}
@@ -511,10 +663,18 @@ pub fn compile(store: &Store, now: Instant) -> Compiled {
// traffic outside the tunnel, whatever a goes-direct road says (QA R-47). Going direct to a private subnet
// (the local network) stays allowed.
for (key, ex) in extras.iter_mut() {
if ex.kill.is_empty() {
if !ex.has_kill_switch() {
continue;
}
let kill_roads: Vec<String> = ex.kill.values().flatten().map(|r| r.to_string()).collect();
let kill_roads: Vec<String> = ex
.kill
.values()
.flatten()
.chain(&ex.kill_closed)
.collect::<BTreeSet<_>>()
.into_iter()
.map(|r| r.to_string())
.collect();
let dropped: Vec<(DirectKey, BTreeSet<RoadId>)> = ex
.direct
.iter()
@@ -563,6 +723,50 @@ pub fn compile(store: &Store, now: Instant) -> Compiled {
build_plan(key, dev, devs, &mine, extras.remove(key), expiry.get(key)),
);
}
// What the tunnel carries wins over going direct (QA F-02). A direct subnet inside a net this plan sends
// through the tunnel is dropped; one that holds such nets keeps them in the tunnel, listed in `except`,
// so no platform has to guess which route wins.
for plan in out.plans.values_mut() {
let tunnelled: BTreeSet<Net> = plan
.peers
.iter()
.flat_map(|p| p.allowed_ips.iter().copied())
.filter(|n| n.prefix_len() > 0)
.collect();
let mut kept = Vec::new();
for mut d in std::mem::take(&mut plan.direct) {
if let Some(t) = tunnelled.iter().find(|t| t.contains(&d.subnet)) {
for id in &d.roads {
let road = store
.roads
.iter()
.find(|r| &r.id == id)
.expect("a granting road");
out.problems.push(
Problem::inactive(
&road.path,
Some("object"),
r::DIRECT_TUNNELLED,
format!(
"for {}: {} is inside {t}, which goes through the tunnel; it does not go direct",
plan.name, d.subnet
),
)
.at(road.line_of("object")),
);
}
continue;
}
d.except = tunnelled
.iter()
.filter(|t| d.subnet.overlaps(t))
.copied()
.collect();
kept.push(d);
}
plan.direct = kept;
}
out.problems.sort();
out
}
@@ -607,7 +811,9 @@ fn build_plan(
p.vias.insert(via.clone());
if let Some(h) = host_name {
dns.entry(h.clone())
.or_insert_with(|| (addr(host), BTreeSet::new()))
.or_insert_with(|| {
(crate::net::Addr(dst.inner().addr()), BTreeSet::new())
})
.1
.insert(road.clone());
}
@@ -673,8 +879,10 @@ fn build_plan(
}
let extras = extras.unwrap_or_default();
let kill_switch = (!extras.kill.is_empty()).then(|| plan::KillSwitch {
through: if extras.kill.len() == 1 {
let kill_switch = extras.has_kill_switch().then(|| plan::KillSwitch {
// One exit, from valid roads only: through it. Two exits, or any kill-switch road with an error: only
// the mesh.
through: if extras.kill.len() == 1 && extras.kill_closed.is_empty() {
extras.kill.keys().next().cloned()
} else {
None
@@ -683,6 +891,7 @@ fn build_plan(
.kill
.values()
.flatten()
.chain(&extras.kill_closed)
.cloned()
.collect::<BTreeSet<_>>()
.into_iter()
@@ -696,6 +905,16 @@ fn build_plan(
device: me.clone(),
name: dev.name.clone(),
address: dev.address,
services: dev
.services
.iter()
.filter_map(|s| {
s.address.map(|address| plan::ServiceAddress {
host: s.host.clone(),
address,
})
})
.collect(),
classic: dev.classic,
expires: expiry.map(|e| e.to_string()),
peers: peers
@@ -750,6 +969,7 @@ fn build_plan(
.map(|((app, subnet), roads)| plan::Direct {
app,
subnet,
except: Vec::new(),
roads: roads.into_iter().collect(),
})
.collect(),
+1 -1
View File
@@ -24,7 +24,7 @@ pub fn explain(
let (dst, want_ports): (Option<Net>, Option<Vec<PortSpec>>) = match place {
Place::Device(k) => (devs.devices.get(k).map(|d| Net::host(d.address.0)), None),
Place::Service(h) => match devs.service(h) {
Some((d, s)) => (Some(Net::host(d.address.0)), Some(s.ports.clone())),
Some((d, s)) => (Some(Net::host(s.endpoint(d).0)), Some(s.ports.clone())),
None => (None, None),
},
Place::Subnet(n) => (Some(*n), None),
+13 -1
View File
@@ -15,6 +15,8 @@ pub struct Plan {
pub device: DeviceKey,
pub name: String,
pub address: Addr,
/// The services this device hosts on an address of their own: it answers on these too (sorted by host).
pub services: Vec<ServiceAddress>,
/// This device is a classic WireGuard peer: not post-quantum.
pub classic: bool,
/// The earliest `until` of the roads this plan was built from, UTC: compile again by then.
@@ -105,6 +107,13 @@ pub struct Rule {
pub roads: Vec<RoadId>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ServiceAddress {
pub host: Hostname,
pub address: Addr,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Dns {
@@ -134,6 +143,9 @@ pub struct Direct {
/// `None`: all traffic to `subnet`; `Some`: only that app's.
pub app: Option<AppId>,
pub subnet: Net,
/// The nets inside `subnet` that this plan sends through the tunnel: they stay in it (QA F-02). A
/// platform that cannot keep them in (an app-level bypass, say) must not apply this entry at all.
pub except: Vec<Net>,
pub roads: Vec<RoadId>,
}
@@ -141,7 +153,7 @@ pub struct Direct {
#[serde(deny_unknown_fields)]
pub struct Custom {
pub road: RoadId,
/// The road said this is for a classic peer: not post-quantum.
/// For a classic device (or a road that says so): not post-quantum.
pub classic: bool,
/// The raw block, byte for byte. **Never checked by the compiler.**
pub raw: String,
+87 -4
View File
@@ -15,10 +15,12 @@ use std::fmt;
pub const MAX_FILE: usize = 256 * 1024;
pub const REQUIRED: [&str; 4] = ["id", "subject", "verb", "created"];
pub const OPTIONAL: [&str; 5] = ["object", "until", "ports", "via", "classic"];
pub const OPTIONAL: [&str; 6] = ["on", "object", "until", "ports", "via", "classic"];
/// Optional keys whose absence is their widest value; present but empty is `key.empty`.
pub const NARROWING: [&str; 2] = ["until", "ports"];
/// The canonical key order.
pub const ORDER: [&str; 9] = [
"id", "subject", "verb", "object", "until", "ports", "via", "classic", "created",
pub const ORDER: [&str; 10] = [
"id", "subject", "on", "verb", "object", "until", "ports", "via", "classic", "created",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
@@ -280,6 +282,9 @@ pub struct Road {
pub path: String,
pub id: RoadId,
pub subject: Subject,
/// For an `app:` subject only: whose devices the app's road applies to (a person, a group or a device).
/// Without it an app road would change the tunnel of every device in the mesh (QA B-3).
pub on: Option<Subject>,
pub verb: Verb,
pub object: Option<Place>,
pub until: Option<Timestamp>,
@@ -308,7 +313,15 @@ impl Road {
Subject::Device(k) => format!("device:{}", dev(k)),
s => s.to_string(),
};
let mut out = format!("{subject} {}", self.verb);
let mut out = subject;
if let Some(on) = &self.on {
let on = match on {
Subject::Device(k) => format!("device:{}", dev(k)),
s => s.to_string(),
};
out.push_str(&format!(" on {on}"));
}
out.push_str(&format!(" {}", self.verb));
match &self.object {
Some(Place::Device(k)) => out.push_str(&format!(" device:{}", dev(k))),
Some(Place::Exit(k)) => out.push_str(&format!(" exit:{}", dev(k))),
@@ -349,6 +362,9 @@ impl Road {
};
field("id", self.id.to_string());
field("subject", scalar(self.subject.to_string()));
if let Some(on) = &self.on {
field("on", scalar(on.to_string()));
}
field("verb", self.verb.to_string());
if let Some(o) = &self.object {
field("object", scalar(o.to_string()));
@@ -481,6 +497,23 @@ impl Road {
problems.push(p(&f.key, r::KEY_UNKNOWN, "unknown key".into()));
}
}
// A condition that narrows a road is widest when it is absent (no end, all traffic), so a key that is
// present but empty is an error, never "absent": clearing a field must not widen a road (QA F-09).
for k in NARROWING {
if fields
.iter()
.any(|f| f.key == k && f.value == Value::Absent)
{
problems.push(p(
k,
r::KEY_EMPTY,
format!(
"`{k}:` is empty, which would widen the road to {}; give a value or remove the key",
if k == "until" { "a permanent grant" } else { "all traffic" }
),
));
}
}
for k in REQUIRED {
if get(k).is_none() {
problems.push(
@@ -571,6 +604,55 @@ impl Road {
}
});
// `on` belongs to an app subject, and an app subject needs it (QA B-3).
let is_app = matches!(subject, Some(Subject::App(_)));
let on = if subject.is_some() && !is_app {
if line_of.contains_key("on") {
problems.push(p(
"on",
r::KEY_FORBIDDEN,
"only an app: road takes `on`".into(),
));
}
None
} else if is_app {
match single("on", &mut problems) {
None => {
problems.push(
Problem::error(
path,
Some("on"),
r::KEY_MISSING,
"an app: road says whose devices it is for: `on: person:<id>`, `group:<id>` or `device:<key>`",
)
.at(at("on")),
);
None
}
Some(s) => match parse_ref(&s) {
Err((code, m)) => {
problems.push(p("on", code, m));
None
}
Ok(Ref::S(sub @ (Subject::Person(_) | Subject::Group(_)))) => Some(sub),
Ok(Ref::P(Place::Device(d))) => Some(Subject::Device(d)),
Ok(rf) => {
problems.push(p(
"on",
r::SUBJECT_KIND,
format!(
"`on` takes person, group or device, not {}",
rf.kind().name()
),
));
None
}
},
}
} else {
None
};
if let Some(v) = verb {
for k in OPTIONAL {
if !v.takes(k) && line_of.contains_key(k) {
@@ -763,6 +845,7 @@ impl Road {
path: path.to_string(),
id,
subject,
on,
verb,
object,
until,
+16
View File
@@ -8,6 +8,7 @@ pub const FILE_SIZE: &str = "file.size";
pub const FILE_ENCODING: &str = "file.encoding";
pub const FILE_HEADER: &str = "file.header";
pub const FILE_COUNT: &str = "file.count";
pub const STORE_ROADS: &str = "store.roads";
pub const YAML_REFUSED: &str = "yaml.refused";
pub const YAML_SYNTAX: &str = "yaml.syntax";
pub const KEY_UNKNOWN: &str = "key.unknown";
@@ -15,6 +16,7 @@ pub const KEY_DUPLICATE: &str = "key.duplicate";
pub const KEY_MISSING: &str = "key.missing";
pub const KEY_FORBIDDEN: &str = "key.forbidden";
pub const KEY_TYPE: &str = "key.type";
pub const KEY_EMPTY: &str = "key.empty";
pub const ID_FORMAT: &str = "id.format";
pub const ID_FILE_NAME: &str = "id.file-name";
pub const ID_DUPLICATE: &str = "id.duplicate";
@@ -27,10 +29,12 @@ pub const OBJECT_UNKNOWN: &str = "object.unknown";
pub const OBJECT_NOT_EXIT: &str = "object.not-exit";
pub const SUBNET_NOT_CANONICAL: &str = "subnet.not-canonical";
pub const SUBNET_UNROUTED: &str = "subnet.unrouted";
pub const DIRECT_MESH: &str = "direct.mesh";
pub const UNTIL_FORMAT: &str = "until.format";
pub const CREATED_FORMAT: &str = "created.format";
pub const PORTS_FORMAT: &str = "ports.format";
pub const PORTS_NOT_SERVED: &str = "ports.not-served";
pub const SERVICE_SHARED: &str = "service.shared";
pub const VIA_FORMAT: &str = "via.format";
pub const VIA_UNKNOWN: &str = "via.unknown";
pub const VIA_NOT_RELAY: &str = "via.not-relay";
@@ -46,6 +50,8 @@ pub const ROAD_NO_DEVICES: &str = "road.no-devices";
pub const ROAD_SELF: &str = "road.self";
pub const EXIT_CONFLICT: &str = "exit.conflict";
pub const DIRECT_KILL_SWITCH: &str = "direct.kill-switch";
pub const ROAD_FAMILY: &str = "road.family";
pub const DIRECT_TUNNELLED: &str = "direct.tunnelled";
// Snapshots
pub const SNAPSHOT_JSON: &str = "snapshot.json";
@@ -54,10 +60,12 @@ pub const DIRECTORY_ID: &str = "directory.id";
pub const DIRECTORY_DUPLICATE: &str = "directory.duplicate";
pub const DIRECTORY_NAME: &str = "directory.name";
pub const DIRECTORY_MEMBER: &str = "directory.member";
pub const DIRECTORY_MEMBER_UNKNOWN: &str = "directory.member-unknown";
pub const DEVICES_KEY: &str = "devices.key";
pub const DEVICES_DUPLICATE: &str = "devices.duplicate";
pub const DEVICES_NAME: &str = "devices.name";
pub const DEVICES_OWNER: &str = "devices.owner";
pub const DEVICES_OWNER_UNKNOWN: &str = "devices.owner-unknown";
pub const DEVICES_ADDRESS: &str = "devices.address";
pub const DEVICES_ROUTE: &str = "devices.route";
pub const DEVICES_OVERLAP: &str = "devices.overlap";
@@ -71,6 +79,7 @@ pub const ALL: &[&str] = &[
FILE_ENCODING,
FILE_HEADER,
FILE_COUNT,
STORE_ROADS,
YAML_REFUSED,
YAML_SYNTAX,
KEY_UNKNOWN,
@@ -78,6 +87,7 @@ pub const ALL: &[&str] = &[
KEY_MISSING,
KEY_FORBIDDEN,
KEY_TYPE,
KEY_EMPTY,
ID_FORMAT,
ID_FILE_NAME,
ID_DUPLICATE,
@@ -90,10 +100,12 @@ pub const ALL: &[&str] = &[
OBJECT_NOT_EXIT,
SUBNET_NOT_CANONICAL,
SUBNET_UNROUTED,
DIRECT_MESH,
UNTIL_FORMAT,
CREATED_FORMAT,
PORTS_FORMAT,
PORTS_NOT_SERVED,
SERVICE_SHARED,
VIA_FORMAT,
VIA_UNKNOWN,
VIA_NOT_RELAY,
@@ -107,16 +119,20 @@ pub const ALL: &[&str] = &[
ROAD_SELF,
EXIT_CONFLICT,
DIRECT_KILL_SWITCH,
ROAD_FAMILY,
DIRECT_TUNNELLED,
SNAPSHOT_JSON,
SNAPSHOT_FORMAT,
DIRECTORY_ID,
DIRECTORY_DUPLICATE,
DIRECTORY_NAME,
DIRECTORY_MEMBER,
DIRECTORY_MEMBER_UNKNOWN,
DEVICES_KEY,
DEVICES_DUPLICATE,
DEVICES_NAME,
DEVICES_OWNER,
DEVICES_OWNER_UNKNOWN,
DEVICES_ADDRESS,
DEVICES_ROUTE,
DEVICES_OVERLAP,
+122 -39
View File
@@ -1,5 +1,11 @@
//! The two snapshots the compiler reads besides the roads: `directory.json` and `devices.json`
//! (docs/FORMATS.md). Both are strict: unknown fields are errors, and any error means no plan is produced.
//! (docs/FORMATS.md). Both are strict: unknown fields are errors, and a *structural* error (bad JSON, a wrong
//! format, a malformed or duplicate id, key or address) means no plan is produced.
//!
//! A *dangling reference* is different (QA F-04): a group member or a device owner that is a well-formed id
//! but no longer a person in the directory. That is what deleting a person upstream leaves behind. It is
//! still an error, and reported, but it only removes that reference: the member leaves the group, the device
//! becomes ownerless (reached only by `device:` roads). Everybody else keeps their plans.
use crate::ids::{
DeviceKey, GroupId, Hostname, PersonId, clip, is_device_key, is_hostname, is_opaque_id,
@@ -39,6 +45,17 @@ pub struct Directory {
pub struct Service {
pub host: Hostname,
pub ports: Vec<PortSpec>,
/// The service's own mesh address on its device, if it has one. A firewall sees addresses and ports, not
/// hostnames, so only a service with its own address (or alone on its ports) can be granted by itself
/// (QA F-01).
pub address: Option<Addr>,
}
impl Service {
/// Where a road to this service sends traffic: its own address, or its device's.
pub fn endpoint(&self, device: &Device) -> Addr {
self.address.unwrap_or(device.address)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -73,6 +90,17 @@ impl Devices {
.find_map(|d| d.services.iter().find(|s| &s.host == host).map(|s| (d, s)))
}
/// Every mesh address: each device's own and its services' own. Never goes direct (QA F-02).
pub fn mesh_addresses(&self) -> impl Iterator<Item = (&Device, Addr)> {
self.devices.values().flat_map(|d| {
std::iter::once((d, d.address)).chain(
d.services
.iter()
.filter_map(move |s| s.address.map(|a| (d, a))),
)
})
}
/// The one device whose routes cover `net`.
pub fn router_of(&self, net: &Net) -> Option<&Device> {
self.devices
@@ -137,6 +165,8 @@ struct RawDevice {
struct RawService {
host: String,
ports: Vec<String>,
#[serde(default)]
address: Option<String>,
}
fn read_json<T: for<'de> Deserialize<'de>>(path: &str, bytes: &[u8]) -> Result<T, Vec<Problem>> {
@@ -161,6 +191,22 @@ fn read_json<T: for<'de> Deserialize<'de>>(path: &str, bytes: &[u8]) -> Result<T
})
}
/// A mesh address: one canonical IP address, never loopback, link-local, multicast, IPv4-embedding IPv6 or an
/// internet address, so an exit's `internet` rule can never cover a device or service of the mesh (QA F-08).
fn mesh_address(text: &str) -> Option<Addr> {
let a = text.parse::<std::net::IpAddr>().ok()?;
let n = Net::host(a);
(a.to_string() == text && !n.is_special() && !n.embeds_ipv4() && !n.reaches_internet())
.then_some(Addr(a))
}
fn not_mesh(text: &str) -> String {
format!(
"`{}` is not one private IP address (a mesh address is never loopback, link-local, multicast, embedded IPv4 or on the internet; use 100.64.0.0/10 or a ULA)",
clip(text)
)
}
fn good_name(s: &str) -> bool {
let n = s.chars().count();
(1..=100).contains(&n) && !s.chars().any(is_hidden_char) && s.trim() == s
@@ -173,11 +219,17 @@ pub fn is_hidden_char(c: char) -> bool {
|| matches!(c, '\u{2028}' | '\u{2029}' | '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2060}'..='\u{2069}' | '\u{feff}')
}
/// A parsed snapshot and the dangling references dropped from it (errors that do not stop plans).
pub type Parsed<T> = Result<(T, Vec<Problem>), Vec<Problem>>;
impl Directory {
pub fn parse(bytes: &[u8]) -> Result<Directory, Vec<Problem>> {
/// `Err`: a structural error, no directory. `Ok((dir, dangling))`: `dangling` lists the members left
/// out because they are not people in the directory.
pub fn parse(bytes: &[u8]) -> Parsed<Directory> {
let path = DIRECTORY_FILE;
let raw: RawDirectory = read_json(path, bytes)?;
let mut problems = Vec::new();
let mut dangling = Vec::new();
let mut e = |field: String, code, msg: String| {
problems.push(Problem::error(path, Some(&field), code, msg))
};
@@ -247,8 +299,8 @@ impl Directory {
}
let mut members = BTreeSet::new();
for (j, m) in g.members.iter().enumerate() {
match PersonId::new(m).filter(|m| dir.people.contains_key(m)) {
Some(m) => {
match PersonId::new(m) {
Some(m) if dir.people.contains_key(&m) => {
if !members.insert(m.clone()) {
e(
format!("groups[{i}].members[{j}]"),
@@ -257,10 +309,21 @@ impl Directory {
);
}
}
Some(m) => dangling.push(Problem::error(
path,
Some(&format!("groups[{i}].members[{j}]")),
r::DIRECTORY_MEMBER_UNKNOWN,
format!(
"`{m}` is not a person in the directory (groups are flat: members are people); left out of the group"
),
)),
None => e(
format!("groups[{i}].members[{j}]"),
r::DIRECTORY_MEMBER,
format!("`{}` is not a person in the directory", clip(m)),
format!(
"`{}` is not a person id: 1-64 of A-Z a-z 0-9 _ -",
clip(m)
),
),
}
}
@@ -284,7 +347,7 @@ impl Directory {
}
}
if problems.is_empty() {
Ok(dir)
Ok((dir, dangling))
} else {
Err(problems)
}
@@ -292,10 +355,13 @@ impl Directory {
}
impl Devices {
pub fn parse(bytes: &[u8], directory: Option<&Directory>) -> Result<Devices, Vec<Problem>> {
/// `Err`: a structural error, no device list. `Ok((devices, dangling))`: `dangling` lists the owners
/// dropped because they are not people in `directory`; those devices are ownerless.
pub fn parse(bytes: &[u8], directory: Option<&Directory>) -> Parsed<Devices> {
let path = DEVICES_FILE;
let raw: RawDevices = read_json(path, bytes)?;
let mut problems = Vec::new();
let mut dangling = Vec::new();
let mut e = |field: String, code, msg: String| {
problems.push(Problem::error(path, Some(&field), code, msg))
};
@@ -345,44 +411,42 @@ impl Devices {
}
let owner = match &d.owner {
None => None,
Some(o) => {
let known = directory.is_none_or(|dir| {
PersonId::new(o).is_some_and(|p| dir.people.contains_key(&p))
});
match PersonId::new(o).filter(|_| is_opaque_id(o) && known) {
Some(p) => Some(p),
Some(o) => match PersonId::new(o).filter(|_| is_opaque_id(o)) {
Some(p) if directory.is_none_or(|dir| dir.people.contains_key(&p)) => Some(p),
Some(p) => {
dangling.push(Problem::error(
path,
Some(&f("owner")),
r::DEVICES_OWNER_UNKNOWN,
format!(
"`{p}` is not a person in the directory; the device is ownerless until it gets an owner, and only `device:` roads reach it"
),
));
None
}
None => {
e(
f("owner"),
r::DEVICES_OWNER,
format!("`{}` is not a person in the directory", clip(o)),
format!("`{}` is not a person id: 1-64 of A-Z a-z 0-9 _ -", clip(o)),
);
None
}
}
}
},
};
let address = match d.address.parse::<std::net::IpAddr>() {
Ok(a)
if a.to_string() == d.address
&& !Net::host(a).is_special()
&& !Net::host(a).embeds_ipv4() =>
{
if !addresses.insert(a) {
let address = match mesh_address(&d.address) {
Some(a) => {
if !addresses.insert(a.0) {
e(
f("address"),
r::DEVICES_ADDRESS,
format!("{a} is used by two devices"),
format!("{a} is used twice"),
);
}
Some(Addr(a))
Some(a)
}
_ => {
e(
f("address"),
r::DEVICES_ADDRESS,
format!("`{}` is not one IP address", clip(&d.address)),
);
None => {
e(f("address"), r::DEVICES_ADDRESS, not_mesh(&d.address));
None
}
};
@@ -453,7 +517,29 @@ impl Devices {
"a service lists the ports it serves".into(),
);
}
services.push(Service { host, ports });
let field = format!("devices[{i}].services[{j}].address");
let address = match s.address.as_deref().map(mesh_address) {
None => None,
Some(Some(a)) => {
if !addresses.insert(a.0) {
e(field, r::DEVICES_ADDRESS, format!("{a} is used twice"));
}
Some(a)
}
Some(None) => {
e(
field,
r::DEVICES_ADDRESS,
not_mesh(s.address.as_deref().unwrap_or_default()),
);
None
}
};
services.push(Service {
host,
ports,
address,
});
}
services.sort_by(|a, b| a.host.cmp(&b.host));
let Some(address) = address else { continue };
@@ -492,21 +578,18 @@ impl Devices {
);
}
}
for d in out.devices.values() {
if na.contains_addr(&d.address.0) {
for (d, a) in out.mesh_addresses() {
if na.contains_addr(&a.0) {
e(
format!("devices.{}.address", d.name),
r::DEVICES_ADDRESS,
format!(
"{} of {} is inside the route {na} of {}",
d.address, d.name, da.name
),
format!("{a} of {} is inside the route {na} of {}", d.name, da.name),
);
}
}
}
if problems.is_empty() {
Ok(out)
Ok((out, dangling))
} else {
Err(problems)
}
+38 -3
View File
@@ -36,7 +36,10 @@ impl Store {
"missing",
)),
Some(b) => match Directory::parse(b) {
Ok(d) => store.directory = Some(d),
Ok((d, dangling)) => {
store.directory = Some(d);
store.problems.extend(dangling);
}
Err(p) => store.problems.extend(p),
},
}
@@ -48,7 +51,10 @@ impl Store {
"missing",
)),
Some(b) => match Devices::parse(b, store.directory.as_ref()) {
Ok(d) => store.devices = Some(d),
Ok((d, dangling)) => {
store.devices = Some(d);
store.problems.extend(dangling);
}
Err(p) => store.problems.extend(p),
},
}
@@ -104,7 +110,36 @@ impl Store {
let mut files = Vec::new();
let mut problems = Vec::new();
let roads = root.join(ROADS_DIR);
if roads.is_dir() {
// A missing roads/ folder means no road grants anything, kill switches included: say so (QA F-07). The
// folder itself is never followed through a symbolic link, like the entries inside it.
let readable = match std::fs::symlink_metadata(&roads) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
problems.push(Problem::error(
ROADS_DIR,
None,
r::STORE_ROADS,
"missing: there is no roads/ folder, so no road grants anything and no kill switch is on",
));
false
}
Err(e) => return Err(e),
Ok(m) if !m.file_type().is_dir() => {
let what = if m.file_type().is_symlink() {
"a symbolic link"
} else {
"not a folder"
};
problems.push(Problem::error(
ROADS_DIR,
None,
r::STORE_ROADS,
format!("{what}; roads/ must be a real folder, so no road was read"),
));
false
}
Ok(_) => true,
};
if readable {
for entry in std::fs::read_dir(&roads)? {
let entry = entry?;
let name = entry.file_name().to_string_lossy().into_owned();
+2 -2
View File
@@ -33,8 +33,8 @@ fn allowed_lists_exactly_the_allowing_roads() {
);
assert_eq!(
ids(&home, 3, &Place::Device(key(2))),
["7tq0mz", "k3f9q2"],
"a service road reaches part of the device"
["k3f9q2"],
"photos has its own address (QA F-01): its road reaches that, not the device's own address"
);
assert_eq!(ids(&home, 1, &subnet("192.168.100.0/24")), ["h2x8vd"]);
assert_eq!(
+1 -1
View File
@@ -5,7 +5,7 @@
{ "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true,
"routes": ["192.168.100.0/24"],
"services": [
{ "host": "photos.home.arpa", "ports": ["tcp/443"] },
{ "host": "photos.home.arpa", "ports": ["tcp/443"], "address": "100.96.1.2" },
{ "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] }
] },
{ "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" },
+2 -9
View File
@@ -3,6 +3,7 @@
"device": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY",
"name": "friend-node",
"address": "100.96.0.6",
"services": [],
"classic": false,
"expires": null,
"peers": [
@@ -38,14 +39,6 @@
"dns": [],
"exit": null,
"kill_switch": null,
"direct": [
{
"app": "steam",
"subnet": "0.0.0.0/0",
"roads": [
"e5yj1s"
]
}
],
"direct": [],
"custom": []
}
+70 -2
View File
@@ -3,6 +3,12 @@
"device": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI",
"name": "home-server",
"address": "100.96.0.2",
"services": [
{
"host": "photos.home.arpa",
"address": "100.96.1.2"
}
],
"classic": false,
"expires": "2026-11-29T22:59:59Z",
"peers": [
@@ -76,6 +82,16 @@
"k3f9q2"
]
},
{
"direction": "in",
"src": "100.96.0.1/32",
"dst": "100.96.1.2/32",
"proto": "any",
"ports": null,
"roads": [
"k3f9q2"
]
},
{
"direction": "in",
"src": "100.96.0.3/32",
@@ -89,7 +105,17 @@
{
"direction": "in",
"src": "100.96.0.3/32",
"dst": "100.96.0.2/32",
"dst": "100.96.1.2/32",
"proto": "any",
"ports": null,
"roads": [
"k3f9q2"
]
},
{
"direction": "in",
"src": "100.96.0.3/32",
"dst": "100.96.1.2/32",
"proto": "tcp",
"ports": [
443,
@@ -112,7 +138,17 @@
{
"direction": "in",
"src": "100.96.0.4/32",
"dst": "100.96.0.2/32",
"dst": "100.96.1.2/32",
"proto": "any",
"ports": null,
"roads": [
"k3f9q2"
]
},
{
"direction": "in",
"src": "100.96.0.4/32",
"dst": "100.96.1.2/32",
"proto": "tcp",
"ports": [
443,
@@ -148,6 +184,32 @@
"r8m2tg"
]
},
{
"direction": "in",
"src": "100.96.0.5/32",
"dst": "100.96.1.2/32",
"proto": "tcp",
"ports": [
22,
22
],
"roads": [
"r8m2tg"
]
},
{
"direction": "in",
"src": "100.96.0.5/32",
"dst": "100.96.1.2/32",
"proto": "udp",
"ports": [
53,
53
],
"roads": [
"r8m2tg"
]
},
{
"direction": "forward",
"src": "100.96.0.1/32",
@@ -177,6 +239,12 @@
{
"app": "steam",
"subnet": "0.0.0.0/0",
"except": [
"100.96.0.1/32",
"100.96.0.3/32",
"100.96.0.4/32",
"100.96.0.5/32"
],
"roads": [
"e5yj1s"
]
+5 -11
View File
@@ -3,6 +3,7 @@
"device": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ",
"name": "jana-laptop",
"address": "100.96.0.4",
"services": [],
"classic": false,
"expires": "2026-11-29T22:59:59Z",
"peers": [
@@ -12,7 +13,8 @@
"address": "100.96.0.2",
"classic": false,
"allowed_ips": [
"100.96.0.2/32"
"100.96.0.2/32",
"100.96.1.2/32"
],
"via": null,
"roads": [
@@ -28,7 +30,7 @@
"dns": [
{
"host": "photos.home.arpa",
"address": "100.96.0.2",
"address": "100.96.1.2",
"roads": [
"7tq0mz"
]
@@ -36,14 +38,6 @@
],
"exit": null,
"kill_switch": null,
"direct": [
{
"app": "steam",
"subnet": "0.0.0.0/0",
"roads": [
"e5yj1s"
]
}
],
"direct": [],
"custom": []
}
+5 -11
View File
@@ -3,6 +3,7 @@
"device": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM",
"name": "jana-phone",
"address": "100.96.0.3",
"services": [],
"classic": false,
"expires": "2026-11-29T22:59:59Z",
"peers": [
@@ -12,7 +13,8 @@
"address": "100.96.0.2",
"classic": false,
"allowed_ips": [
"100.96.0.2/32"
"100.96.0.2/32",
"100.96.1.2/32"
],
"via": null,
"roads": [
@@ -28,7 +30,7 @@
"dns": [
{
"host": "photos.home.arpa",
"address": "100.96.0.2",
"address": "100.96.1.2",
"roads": [
"7tq0mz"
]
@@ -36,14 +38,6 @@
],
"exit": null,
"kill_switch": null,
"direct": [
{
"app": "steam",
"subnet": "0.0.0.0/0",
"roads": [
"e5yj1s"
]
}
],
"direct": [],
"custom": []
}
@@ -3,6 +3,7 @@
"device": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE",
"name": "mark-pc",
"address": "100.96.0.1",
"services": [],
"classic": false,
"expires": null,
"peers": [
@@ -14,6 +15,7 @@
"allowed_ips": [
"0.0.0.0/0",
"100.96.0.2/32",
"100.96.1.2/32",
"192.168.100.0/24",
"::/0"
],
+2 -9
View File
@@ -3,6 +3,7 @@
"device": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc",
"name": "petr-phone",
"address": "100.96.0.7",
"services": [],
"classic": false,
"expires": null,
"peers": [
@@ -33,14 +34,6 @@
]
},
"kill_switch": null,
"direct": [
{
"app": "steam",
"subnet": "0.0.0.0/0",
"roads": [
"e5yj1s"
]
}
],
"direct": [],
"custom": []
}
+4 -10
View File
@@ -3,6 +3,7 @@
"device": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU",
"name": "router",
"address": "100.96.0.5",
"services": [],
"classic": true,
"expires": null,
"peers": [
@@ -12,7 +13,8 @@
"address": "100.96.0.2",
"classic": false,
"allowed_ips": [
"100.96.0.2/32"
"100.96.0.2/32",
"100.96.1.2/32"
],
"via": null,
"roads": [
@@ -27,15 +29,7 @@
"dns": [],
"exit": null,
"kill_switch": null,
"direct": [
{
"app": "steam",
"subnet": "0.0.0.0/0",
"roads": [
"e5yj1s"
]
}
],
"direct": [],
"custom": [
{
"road": "x1d7qa",
@@ -1,8 +1,9 @@
---
id: e5yj1s
subject: app:steam
on: person:mark
verb: goes-direct
object: subnet:0.0.0.0/0
created: 2026-11-21T18:30:00+01:00
---
Games do not go through the tunnel.
Mark's games do not go through the tunnel.
+20 -3
View File
@@ -43,25 +43,42 @@ road a00041-second-exit.md exit.conflict object
road a00042-direct-public.md direct.kill-switch object
road a00043-custom-object.md key.forbidden object
road a00044-tab.md yaml.refused -
road a00045-empty-until.md key.empty until
road a00046-until-comment.md key.empty until
road a00047-empty-ports.md key.empty ports
road a00048-direct-mesh.md direct.mesh object
road a00049-direct-tunnelled.md direct.tunnelled object
road a00050-app-everyone.md key.missing on
road a00051-on-not-app.md key.forbidden on
road a00052-on-nobody.md subject.unknown on
road a00053-on-service.md subject.kind on
directory unknown-field.directory.json snapshot.json -
directory format-two.directory.json snapshot.format format
directory bad-person-id.directory.json directory.id people[3].id
directory duplicate-person.directory.json directory.duplicate people[3].id
directory name-newline.directory.json directory.name people[3].name
directory name-bidi.directory.json directory.name people[3].name
directory member-unknown.directory.json directory.member groups[0].members[1]
directory member-group.directory.json directory.member groups[0].members[1]
directory member-unknown.directory.json directory.member-unknown groups[0].members[1]
directory member-group.directory.json directory.member-unknown groups[0].members[1]
directory member-bad-id.directory.json directory.member groups[0].members[1]
directory member-twice.directory.json directory.member groups[0].members[1]
devices unknown-field.devices.json snapshot.json -
devices bad-key.devices.json devices.key devices[0].key
devices duplicate-key.devices.json devices.duplicate devices[6].key
devices name-newline.devices.json devices.name devices[0].name
devices owner-unknown.devices.json devices.owner devices[6].owner
devices owner-unknown.devices.json devices.owner-unknown devices[6].owner
devices owner-bad-id.devices.json devices.owner devices[6].owner
devices address-twice.devices.json devices.address devices[6].address
devices address-in-route.devices.json devices.address devices.petr-phone.address
devices address-loopback.devices.json devices.address devices[6].address
devices address-public.devices.json devices.address devices[6].address
devices address-public-v6.devices.json devices.address devices[6].address
devices route-host-bits.devices.json devices.route devices[1].routes[0]
devices route-internet.devices.json devices.route devices[1].routes[0]
devices route-link-local.devices.json devices.route devices[1].routes[0]
devices route-overlap.devices.json devices.overlap devices.friend-node.routes
devices service-host.devices.json devices.service devices[1].services[0].host
devices service-no-ports.devices.json devices.ports devices[1].services[0].ports
devices service-address-twice.devices.json devices.address devices[1].services[0].address
devices service-address-public.devices.json devices.address devices[1].services[0].address
devices service-address-in-route.devices.json devices.address devices.home-server.address
@@ -0,0 +1,8 @@
---
id: a00045
subject: person:jana
verb: can-reach
object: service:photos.home.arpa
until:
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,8 @@
---
id: a00046
subject: person:jana
verb: can-reach
object: service:photos.home.arpa
until: # Sunday
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,8 @@
---
id: a00047
subject: person:jana
verb: can-reach
object: service:photos.home.arpa
ports:
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00048
subject: person:jana
verb: goes-direct
object: subnet:100.96.0.0/24
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00049
subject: person:mark
verb: goes-direct
object: subnet:192.168.100.0/25
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00050
subject: app:steam
verb: goes-direct
object: subnet:0.0.0.0/0
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,8 @@
---
id: a00051
subject: person:jana
on: person:mark
verb: goes-direct
object: subnet:0.0.0.0/0
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,8 @@
---
id: a00052
subject: app:steam
on: person:nobody
verb: goes-direct
object: subnet:0.0.0.0/0
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,8 @@
---
id: a00053
subject: app:steam
on: service:photos.home.arpa
verb: goes-direct
object: subnet:0.0.0.0/0
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,17 @@
{
"format": 1,
"devices": [
{ "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" },
{ "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true,
"routes": ["192.168.100.0/24"],
"services": [
{ "host": "photos.home.arpa", "ports": ["tcp/443"] },
{ "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] }
] },
{ "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" },
{ "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" },
{ "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true },
{ "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true },
{ "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "2a00:1450::7" }
]
}
@@ -0,0 +1,17 @@
{
"format": 1,
"devices": [
{ "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" },
{ "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true,
"routes": ["192.168.100.0/24"],
"services": [
{ "host": "photos.home.arpa", "ports": ["tcp/443"] },
{ "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] }
] },
{ "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" },
{ "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" },
{ "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true },
{ "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true },
{ "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "203.0.114.7" }
]
}
@@ -0,0 +1,12 @@
{
"format": 1,
"people": [
{ "id": "mark", "name": "Mark" },
{ "id": "jana", "name": "Jana" },
{ "id": "petr", "name": "Petr" },
{ "id": "eva", "name": "Eva" }
],
"groups": [
{ "id": "household", "name": "Household", "members": ["mark", "no body"] }
]
}
@@ -0,0 +1,12 @@
{
"format": 1,
"people": [
{ "id": "mark", "name": "Mark" },
{ "id": "jana", "name": "Jana" },
{ "id": "petr", "name": "Petr" },
{ "id": "eva", "name": "Eva" }
],
"groups": [
{ "id": "household", "name": "Household", "members": ["mark", "mark"] }
]
}
@@ -0,0 +1,17 @@
{
"format": 1,
"devices": [
{ "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" },
{ "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true,
"routes": ["192.168.100.0/24"],
"services": [
{ "host": "photos.home.arpa", "ports": ["tcp/443"] },
{ "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] }
] },
{ "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" },
{ "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" },
{ "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true },
{ "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true },
{ "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "no body", "address": "100.96.0.7" }
]
}
@@ -0,0 +1,17 @@
{
"format": 1,
"devices": [
{ "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" },
{ "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true,
"routes": ["192.168.100.0/24"],
"services": [
{ "host": "photos.home.arpa", "ports": ["tcp/443"], "address": "192.168.100.9" },
{ "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] }
] },
{ "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" },
{ "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" },
{ "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true },
{ "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true },
{ "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "100.96.0.7" }
]
}
@@ -0,0 +1,17 @@
{
"format": 1,
"devices": [
{ "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" },
{ "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true,
"routes": ["192.168.100.0/24"],
"services": [
{ "host": "photos.home.arpa", "ports": ["tcp/443"], "address": "203.0.114.9" },
{ "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] }
] },
{ "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" },
{ "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" },
{ "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true },
{ "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true },
{ "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "100.96.0.7" }
]
}
@@ -0,0 +1,17 @@
{
"format": 1,
"devices": [
{ "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" },
{ "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true,
"routes": ["192.168.100.0/24"],
"services": [
{ "host": "photos.home.arpa", "ports": ["tcp/443"], "address": "100.96.0.1" },
{ "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] }
] },
{ "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" },
{ "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" },
{ "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true },
{ "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true },
{ "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "100.96.0.7" }
]
}
+124 -5
View File
@@ -15,6 +15,12 @@
//! sending side is exactly what a road names (no supernet, QA R-02); every firewall source sits on its own
//! peer as a /32 (no spoofing, QA R-10); invalid and expired roads change no byte; removing a road or moving
//! `now` forward never adds a rule (P-3, P-4); `explain` agrees with the firewall (P-7).
//!
//! IPv6 (QA F-10): the oracle works in `u32`, so IPv6 is checked by embedding instead. P-6v6 writes the same
//! world with every IPv4 address `a` replaced by `fd00::a` and every prefix `/L` by `/(L+96)` (the default
//! route by `::/0`), compiles both, maps the IPv4 plans through the same embedding and requires them to be
//! equal to the IPv6 plans: so every IPv6 path (`/128` hosts, nesting, overlap, `except`, exits, the kill
//! switch) behaves exactly like the IPv4 one that P-1 checks against the oracle, plus the same problems.
use jiff::{SignedDuration, Timestamp as Instant};
use proptest::prelude::*;
@@ -68,7 +74,8 @@ enum Subj {
Person(usize),
Group(usize),
Device(usize),
App,
/// An app on a person's devices (QA B-3).
App(usize),
}
#[derive(Clone, Debug, PartialEq)]
@@ -145,7 +152,7 @@ fn world(bytes: &[u8]) -> World {
// Indices one past the end name things that do not exist.
let subject = match (s.n(4), &verb) {
(_, Verb::Custom) => Subj::Device(s.n(n_dev + 1)),
(3, Verb::Direct) => Subj::App,
(3, Verb::Direct) => Subj::App(s.n(people + 1)),
(0, _) | (3, _) => Subj::Person(s.n(people + 1)),
(1, _) => Subj::Group(s.n(3)),
_ => Subj::Device(s.n(n_dev + 1)),
@@ -248,6 +255,13 @@ fn ports_text(p: &[(&str, u16, u16)]) -> String {
/// The world as store bytes, written here without the library's writer.
fn to_store(w: &World, roads: &[(usize, &R)], when: Instant) -> Store {
let (files, directory, devices) = store_parts(w, roads, when);
Store::from_parts(&files, Some(directory.as_bytes()), Some(devices.as_bytes()))
}
type Parts = (Vec<(String, Vec<u8>)>, String, String);
fn store_parts(w: &World, roads: &[(usize, &R)], when: Instant) -> Parts {
let people: Vec<String> = (0..w.people)
.map(|p| format!(r#"{{"id":"p{p}","name":"P{p}"}}"#))
.collect();
@@ -302,7 +316,7 @@ fn to_store(w: &World, roads: &[(usize, &R)], when: Instant) -> Store {
Subj::Person(p) => format!("subject: person:p{p}\n"),
Subj::Group(g) => format!("subject: group:g{g}\n"),
Subj::Device(d) => format!("subject: device:{}\n", dev_key(*d)),
Subj::App => "subject: app:games\n".into(),
Subj::App(p) => format!("subject: app:games\non: person:p{p}\n"),
};
t += match r.verb {
Verb::Reach => "verb: can-reach\n",
@@ -341,7 +355,87 @@ fn to_store(w: &World, roads: &[(usize, &R)], when: Instant) -> Store {
})
.collect();
let _ = when;
Store::from_parts(&files, Some(directory.as_bytes()), Some(devices.as_bytes()))
(files, directory, devices)
}
// ------------------------------------------------------------------ IPv6 by embedding (QA F-10)
fn v6_of(a: std::net::Ipv4Addr) -> std::net::Ipv6Addr {
std::net::Ipv6Addr::from(0xfd00_u128 << 112 | u32::from(a) as u128)
}
/// One IPv4 address or network, embedded; anything else unchanged.
fn embed_token(t: &str) -> Option<String> {
let (a, len) = match t.split_once('/') {
Some((a, l)) => (a, Some(l.parse::<u8>().ok().filter(|l| *l <= 32)?)),
None => (t, None),
};
let a: std::net::Ipv4Addr = a.parse().ok()?;
if a.to_string() != t.split('/').next().unwrap() {
return None;
}
Some(match len {
None => v6_of(a).to_string(),
Some(0) if a.is_unspecified() => "::/0".to_string(),
Some(l) => format!("{}/{}", v6_of(a), l + 96),
})
}
/// Replaces every IPv4 address or network in `text` (a maximal run of digits, dots and one slash).
fn embed_text(text: &str) -> String {
let mut out = String::new();
let mut run = String::new();
let flush = |run: &mut String, out: &mut String| {
out.push_str(&embed_token(run).unwrap_or_else(|| run.clone()));
run.clear();
};
for c in text.chars() {
if c.is_ascii_digit() || c == '.' || (c == '/' && !run.is_empty() && !run.contains('/')) {
run.push(c);
} else {
flush(&mut run, &mut out);
out.push(c);
}
}
flush(&mut run, &mut out);
out
}
fn embed_parts((files, dir, devs): Parts) -> Parts {
(
files
.into_iter()
.map(|(n, b)| (n, embed_text(&String::from_utf8(b).unwrap()).into_bytes()))
.collect(),
dir,
embed_text(&devs),
)
}
/// A plan as JSON with IPv4 embedded (when `embed`), the two default routes made one spelling, and every
/// list sorted, so plans of the two families compare.
fn normal(plan: &roads::Plan, embed: bool) -> serde_json::Value {
fn walk(v: &mut serde_json::Value, embed: bool) {
match v {
serde_json::Value::String(s) => {
// Raw blocks are free text: embed inside them too, as the store's text was.
if embed {
*s = embed_text(s);
} else if s == "0.0.0.0/0" {
*s = "::/0".into();
}
}
serde_json::Value::Array(a) => {
a.iter_mut().for_each(|x| walk(x, embed));
a.sort_by_key(|x| x.to_string());
}
serde_json::Value::Object(m) => m.values_mut().for_each(|x| walk(x, embed)),
_ => {}
}
}
let mut v = serde_json::to_value(plan).unwrap();
walk(&mut v, embed);
v
}
// ------------------------------------------------------------------ the oracle (no roads code)
@@ -355,7 +449,7 @@ fn subj_devs(w: &World, s: &Subj) -> BTreeSet<usize> {
.get(*g)
.is_some_and(|m| w.devs[d].owner.is_some_and(|o| m.contains(&o))),
Subj::Device(x) => *x == d,
Subj::App => true,
Subj::App(p) => w.devs[d].owner == Some(*p),
})
.collect()
}
@@ -653,6 +747,31 @@ proptest! {
}
}
proptest! {
#![proptest_config(ProptestConfig { cases: 1_000, failure_persistence: None, .. ProptestConfig::default() })]
#[test]
fn p6v6_ipv6_compiles_like_ipv4(bytes in proptest::collection::vec(any::<u8>(), 64..400)) {
CASES.fetch_add(1, Ordering::Relaxed);
let w = world(&bytes);
let all: Vec<(usize, &R)> = w.roads.iter().enumerate().collect();
let v4 = store_parts(&w, &all, now());
let v6 = embed_parts(v4.clone());
prop_assert!(!v6.2.contains("\"100.96."), "the device list was not embedded");
let s4 = Store::from_parts(&v4.0, Some(v4.1.as_bytes()), Some(v4.2.as_bytes()));
let s6 = Store::from_parts(&v6.0, Some(v6.1.as_bytes()), Some(v6.2.as_bytes()));
let (c4, c6) = (compile(&s4, now()), compile(&s6, now()));
prop_assert!(c6.has_plans(), "the IPv6 snapshots are valid: {:?}", c6.problems.iter().filter(|p| !p.path.starts_with("roads/")).collect::<Vec<_>>());
let key = |p: &roads::Problem| (p.path.clone(), p.field.clone(), p.code, p.severity);
let k4: BTreeSet<_> = c4.problems.iter().map(key).collect();
let k6: BTreeSet<_> = c6.problems.iter().map(key).collect();
prop_assert_eq!(k4, k6, "IPv4 and IPv6 report different problems");
for (k, p4) in &c4.plans {
prop_assert_eq!(normal(p4, true), normal(&c6.plans[k], false), "{} compiles differently in IPv6", p4.name);
}
}
}
proptest! {
#![proptest_config(ProptestConfig { cases: 500, failure_persistence: None, .. ProptestConfig::default() })]
+140 -11
View File
@@ -29,7 +29,6 @@ fn with(parts: Parts, r: (String, String)) -> Parts {
/// only say "Jana's address may reach 100.96.0.2 on tcp/443", and photos and git both live there on tcp/443,
/// so "Jana can reach Photos" is also "Jana can reach Git"; `explain` admits it.
#[test]
#[ignore = "QA F-01 (blocker): a service road grants every service on the same host and port"]
fn f01_a_service_road_grants_only_that_service() {
// Without the household road, Jana's only road to the home server is 7tq0mz: photos, tcp/443.
let parts = Parts::home().without_road("k3f9q2");
@@ -48,11 +47,71 @@ fn f01_a_service_road_grants_only_that_service() {
);
}
/// F-01, the other half: without its own address, photos shares home-server:443 with git, and the road to
/// photos is refused, naming git, instead of opening both. A `ports:` that avoids the shared port is allowed.
#[test]
fn f01_a_service_that_shares_its_address_and_port_is_refused() {
let parts = Parts::home().edit_devices(|d| d.replace(r#", "address": "100.96.1.2""#, ""));
let c = parts.compile();
let p = c
.problems
.iter()
.find(|p| p.path.contains("7tq0mz") && p.code == roads::rules::SERVICE_SHARED);
assert!(
p.is_some_and(|p| p.is_error() && p.message.contains("git.home.arpa")),
"{:?}",
c.problems
);
assert!(
!c.plans[&key(3)]
.dns
.iter()
.any(|d| d.host.as_str() == "photos.home.arpa"),
"the refused road still granted"
);
// Git alone on tcp/22 shares nothing: a road narrowed to it compiles.
let narrowed = Parts::home()
.edit_devices(|d| d.replace(r#", "address": "100.96.1.2""#, ""))
.with_road(
"f01aaa-jana-git-ssh.md",
"---\nid: f01aaa\nsubject: person:jana\nverb: can-reach\nobject: service:git.home.arpa\nports: [tcp/22]\ncreated: 2026-11-25T10:00:00Z\n---\n",
)
.compile();
assert!(
!narrowed.problems.iter().any(|p| p.path.contains("f01aaa")),
"{:?}",
narrowed.problems
);
}
/// F-01: with its own address, photos is granted by itself: the rule's destination is that address, the
/// home server's plan answers on it, and Jana's DNS points there.
#[test]
fn f01_a_service_with_its_own_address_is_granted_alone() {
let c = Parts::home().without_road("k3f9q2").compile();
let server = &c.plans[&key(2)];
assert!(server.services.iter().any(|s| s.host.as_str() == "photos.home.arpa" && s.address.to_string() == "100.96.1.2"));
let to_photos: Vec<_> = server
.firewall
.rules
.iter()
.filter(|r| r.roads.iter().any(|id| id.as_str() == "7tq0mz"))
.collect();
assert!(!to_photos.is_empty());
assert!(
to_photos
.iter()
.all(|r| matches!(r.dst, Dst::Net(n) if n.to_string() == "100.96.1.2/32")),
"{to_photos:?}"
);
let phone = &c.plans[&key(3)];
assert!(phone.dns.iter().any(|d| d.host.as_str() == "photos.home.arpa" && d.address.to_string() == "100.96.1.2"));
}
/// F-02. `goes-direct` may name the mesh's own addresses or a subnet the mesh routes. Then traffic that the
/// plan also routes into the tunnel is told to bypass it, on whatever network the device is on, and the
/// kill switch does not stop it because the subnet is "private".
#[test]
#[ignore = "QA F-02 (major): goes-direct can take mesh addresses and tunnelled subnets out of the tunnel"]
fn f02_going_direct_never_overlaps_what_the_tunnel_carries() {
let mark_pc = key(1);
for subnet in ["100.96.0.0/16", "192.168.100.0/24", "192.168.0.0/16"] {
@@ -77,15 +136,28 @@ fn f02_going_direct_never_overlaps_what_the_tunnel_carries() {
.flat_map(|p| p.allowed_ips.iter())
.filter(|n| n.prefix_len() > 0)
.collect();
// Decision (owner session): a direct subnet that holds tunnelled nets keeps them in the tunnel, listed
// in `except`; one inside a tunnelled net is dropped; one holding a mesh address is refused. So every
// overlap must be covered by `except`.
for d in &plan.direct {
for n in &tunnelled {
assert!(
!d.subnet.overlaps(n),
!d.subnet.overlaps(n) || d.except.iter().any(|e| e.contains(n)),
"goes-direct {} overlaps {n}, which the plan sends through the tunnel",
d.subnet
);
}
}
let refused = c
.problems
.iter()
.any(|p| p.path.contains("f02aaa") && p.code == roads::rules::DIRECT_MESH);
assert_eq!(
refused,
subnet == "100.96.0.0/16",
"{subnet}: {:?}",
c.problems
);
}
}
@@ -93,7 +165,6 @@ fn f02_going_direct_never_overlaps_what_the_tunnel_carries() {
/// typo: the exit device stops offering itself as an exit (or leaves devices.json), and every kill switch
/// through it silently disappears while the rest of the plan compiles.
#[test]
#[ignore = "QA F-03 (major): an invalid kill-switch road fails open"]
fn f03_a_kill_switch_whose_exit_goes_away_fails_closed() {
let parts = Parts::home().edit_devices(|d| {
d.replace(
@@ -109,17 +180,54 @@ fn f03_a_kill_switch_whose_exit_goes_away_fails_closed() {
.any(|p| p.path.contains("w9c3ke") && p.is_error()),
"the kill-switch road is reported"
);
let ks = c.plans[&key(1)].kill_switch.as_ref();
assert!(
c.plans[&key(1)].kill_switch.is_some(),
ks.is_some(),
"mark-pc lost its kill switch because its exit stopped being one: it now fails open"
);
assert_eq!(
ks.unwrap().through,
None,
"closed means through no exit: only the mesh"
);
// Mutation guard: the same road made valid again keeps its exit.
assert_eq!(
Parts::home().compile().plans[&key(1)]
.kill_switch
.as_ref()
.unwrap()
.through,
Some(key(2))
);
}
/// F-03, the other references: an unknown exit, and an exit road that has expired, which ends as written.
#[test]
fn f03_an_unknown_exit_fails_closed_and_an_expired_kill_switch_ends() {
let text = Parts::home().road_text("w9c3ke");
let unknown = text.replace(
"exit:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI",
"exit:CQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk",
);
let c = Parts::home().replace_road("w9c3ke", &unknown).compile();
assert!(
c.problems
.iter()
.any(|p| p.path.contains("w9c3ke") && p.is_error())
);
assert_eq!(c.plans[&key(1)].kill_switch.as_ref().unwrap().through, None);
let expired = unknown.replace("created:", "until: 2026-11-01T00:00:00+01:00\ncreated:");
let c = Parts::home().replace_road("w9c3ke", &expired).compile();
assert!(
c.plans[&key(1)].kill_switch.is_none(),
"an expired kill switch ends as written"
);
}
/// F-04. Deleting a person from the directory (the upstream event, without also editing devices.json) leaves
/// a dangling `owner`, which is a snapshot error, which means no plan for anybody. Day 3 then has to choose
/// between the household offline and the deleted person keeping their access.
#[test]
#[ignore = "QA F-04 (major): one dangling owner means no plans for anybody"]
fn f04_deleting_a_person_revokes_them_and_nobody_else() {
let parts =
Parts::home().edit_directory(|d| d.replace(r#" { "id": "petr", "name": "Petr" },"#, ""));
@@ -139,7 +247,6 @@ fn f04_deleting_a_person_revokes_them_and_nobody_else() {
/// F-05. A custom road on a classic device is carried as `classic: false` unless the road says otherwise, so the
/// plan labels a classic peer's raw block as post-quantum (CLAUDE.md: classic peers are labelled everywhere).
#[test]
#[ignore = "QA F-05 (minor): plan.custom takes `classic` from the road, not from the device"]
fn f05_a_custom_block_on_a_classic_device_is_labelled_classic() {
let router = key(5);
let text = Parts::home()
@@ -162,7 +269,6 @@ fn f05_a_custom_block_on_a_classic_device_is_labelled_classic() {
/// other way round) compile cleanly into rules that can never match: a road that grants nothing, reported as
/// nothing.
#[test]
#[ignore = "QA F-06 (minor): a road across address families compiles into a rule that never matches"]
fn f06_a_road_across_address_families_is_reported() {
let parts = with(
Parts::home().edit_devices(|d| {
@@ -200,7 +306,6 @@ fn f06_a_road_across_address_families_is_reported() {
/// F-07. A store folder without `roads/` compiles to plans with no access and no problem at all, so pointing
/// `--store` one folder too high revokes everything, kill switches included, without a word.
#[test]
#[ignore = "QA F-07 (minor): a missing roads/ folder is not reported"]
fn f07_a_missing_roads_folder_is_reported() {
let dir = tempfile::tempdir().unwrap();
std::fs::copy(
@@ -224,7 +329,6 @@ fn f07_a_missing_roads_folder_is_reported() {
/// F-08. A device's mesh address may be a public address. The exit's forward rule to `internet` then covers
/// another device's mesh address, so "exit through the friend node" also reaches that device through the exit.
#[test]
#[ignore = "QA F-08 (minor): mesh addresses are not confined to private ranges"]
fn f08_mesh_addresses_are_never_internet_addresses() {
let parts = Parts::home()
.edit_devices(|d| d.replace(r#""address": "100.96.0.4""#, r#""address": "198.51.100.4""#));
@@ -239,7 +343,6 @@ fn f08_mesh_addresses_are_never_internet_addresses() {
/// is the widest value: `until:` left empty is a permanent grant and `ports:` left empty is all traffic, with no
/// problem reported. The same failure as QA R-35 (a misspelt `until`), reached by deleting the value instead.
#[test]
#[ignore = "QA F-09 (major): an emptied `until:` or `ports:` silently widens the road to its maximum"]
fn f09_an_emptied_narrowing_condition_is_an_error() {
for (from, to) in [
("until: 2026-11-29T23:59:59+01:00\n", "until:\n"),
@@ -261,3 +364,29 @@ fn f09_an_emptied_narrowing_condition_is_an_error() {
);
}
}
/// B-3. An `app:` road used to reach every device in the mesh, other people's included: `app:steam goes-direct
/// 0.0.0.0/0` changed the tunnel of Jana's phone, Petr's friend node and a classic router. An app road now names
/// whose devices it is for (`on:`), and reaches only those.
#[test]
fn b3_an_app_road_reaches_only_the_devices_it_is_on() {
let c = Parts::home().compile();
let steam = |k: u8| c.plans[&key(k)].direct.iter().any(|d| d.app.is_some());
assert!(steam(2), "mark's home server runs the road");
for (k, who) in [
(3, "jana-phone"),
(4, "jana-laptop"),
(5, "router"),
(6, "friend-node"),
(7, "petr-phone"),
] {
assert!(!steam(k), "{who} is not mark's, and its tunnel changed");
}
// The same road for Jana moves to Jana's devices.
let text = Parts::home()
.road_text("e5yj1s")
.replace("on: person:mark", "on: person:jana");
let c = Parts::home().replace_road("e5yj1s", &text).compile();
let steam = |k: u8| c.plans[&key(k)].direct.iter().any(|d| d.app.is_some());
assert!(steam(3) && steam(4) && !steam(2) && !steam(6));
}
+33 -1
View File
@@ -149,6 +149,31 @@ impl Renaming {
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 {
@@ -239,7 +264,7 @@ impl Renaming {
{
let v2 = match k {
"id" => self.new_of(v),
"subject" | "object" | "via" => self.reference(v),
"subject" | "on" | "object" | "via" => self.reference(v),
_ => v.to_string(),
};
out.push_str(&format!("{k}: {v2}\n"));
@@ -385,6 +410,13 @@ fn the_extra_roads_reach_the_order_sensitive_paths() {
);
}
/// 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();
+45 -2
View File
@@ -8,7 +8,8 @@ use common::{Parts, at, fw_accepts, key};
use roads::{Hostname, Place, compile, explain};
use std::net::IpAddr;
const PHOTOS_HOST: &str = "100.96.0.2";
/// photos.home.arpa's own address on the home server (QA F-01: a service road reaches only its service).
const PHOTOS_HOST: &str = "100.96.1.2";
fn home_server() -> IpAddr {
PHOTOS_HOST.parse().unwrap()
@@ -182,7 +183,8 @@ fn removing_a_person_from_a_group_removes_the_group_road_only() {
#[test]
fn a_person_deleted_from_the_directory_leaves_their_roads_reported_and_void() {
// QA R-20: the road naming petr is an error, and the device that petr owned fails the snapshot.
// QA R-20: the road naming petr is an error. The device petr owned is edited to have no owner here; QA
// F-04 (`qa_findings.rs`) covers the upstream-only edit, where the dangling owner leaves it ownerless.
let parts = Parts::home()
.edit_directory(|d| d.replace(r#" { "id": "petr", "name": "Petr" },"#, ""))
.edit_devices(|d| d.replace(r#""owner": "petr", "#, ""));
@@ -198,3 +200,44 @@ fn a_person_deleted_from_the_directory_leaves_their_roads_reported_and_void() {
"the friend node kept petr-phone as a peer"
);
}
/// Mark, 2026-11-25, "Leave classic out": a grant to a person or a group covers only their post-quantum
/// devices. A classic router that Mark owns is reached by none of Mark's or the household's roads, only by
/// its own `device:` road with `classic: true`, and that road keeps working.
#[test]
fn a_person_grant_never_covers_their_classic_device() {
let parts = Parts::home().edit_devices(|d| {
d.replace(
r#""name": "router", "address""#,
r#""name": "router", "owner": "mark", "address""#,
)
});
let c = parts.compile();
assert_eq!(c.errors().count(), 0, "{:?}", c.problems);
let router = &c.plans[&key(5)];
// h2x8vd (person:mark -> the home LAN) and k3f9q2 (group:household -> home-server) leave it out.
for p in &router.peers {
assert!(
p.roads.iter().all(|r| r.as_str() == "r8m2tg"),
"the router got a peer from a person or group road: {:?}",
p.roads
);
}
assert!(
!router
.peers
.iter()
.flat_map(|p| p.allowed_ips.iter())
.any(|n| n.to_string() == "192.168.100.0/24"),
"mark's LAN road reached his classic router"
);
// Its own classic road still gives it the home server on udp/53 and tcp/22.
assert!(fw_accepts(
&c,
&key(5),
"100.96.0.2".parse().unwrap(),
Some(("tcp", 22))
));
// And mark's post-quantum devices keep their access.
assert!(c.plans[&key(1)].peers.iter().any(|p| p.key == key(2)));
}
+81
View File
@@ -42,6 +42,17 @@ fn inactive_code(code: &str) -> bool {
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)
}
@@ -122,6 +133,13 @@ fn run(case: &Case, baseline: &[u8]) -> BTreeSet<String> {
"{}: 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(),
@@ -207,6 +225,69 @@ fn generated(baseline: &[u8]) -> BTreeSet<String> {
.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
}
+78 -13
View File
@@ -53,16 +53,25 @@ change.
|:--|:--|:--|:--|:--|
| `can-reach` | person, group, device | device, subnet, service | `until`, `ports`, `via`, `classic` | peers both ways, allowed IPs, an inbound or forward firewall rule on the far side, DNS for a service |
| `exits-through` | person, group, device | exit | `until`, `classic` | a peer with `0.0.0.0/0, ::/0`, a forward rule to the internet on the exit |
| `goes-direct` | person, group, device, app | subnet | `until` | nothing: the subnet (or the app) bypasses the tunnel |
| `goes-direct` | person, group, device, app (with `on`) | subnet | `until` | nothing: the subnet (or the app) bypasses the tunnel, except what the plan tunnels |
| `never-online-without` | person, group, device | exit | `until` | nothing: the kill switch |
| `custom` | device | — | `until`, `classic` | nothing the compiler checks: the raw block is carried, verbatim and labelled |
- A person's grant covers **every device whose owner is that person** in `devices.json`; a group's covers every
member's devices. Removing a device from a person removes its access on the next compile.
- A person's grant covers **every post-quantum device whose owner is that person** in `devices.json`; a group's
covers every member's post-quantum devices. Removing a device from a person removes its access on the next
compile. **Classic devices are left out** of person and group grants (Mark, 2026-11-25, "Leave classic
out"): a classic router is reached only by a `device:` road of its own, which says `classic: true`. So one
classic device no longer blocks its owner's roads (the builder's self-review #5).
- `classic` must be `true` on any road that would create a peer with a classic (not post-quantum) device. It is
the road saying out loud that this path is not post-quantum. Without it the road grants nothing.
- `until` is exclusive and compared with `now`, which is a parameter. Each plan carries `expires`, the earliest
`until` of the roads it was built from, so the engine knows when to compile again.
- An `app:` subject names whose devices it is for with `on:` (a person, group or device), and reaches only
those; without `on:` it is refused (QA B-3).
- A service is reached at its **own** mesh address when `devices.json` gives it one, else at its device's. A
road to a service that shares that address and a port with another service is refused (`service.shared`):
a firewall sees addresses and ports, never hostnames, so its rule would open the other service too (QA F-01).
A `device:` road reaches the whole device: its own address and its services' own addresses.
### The compiler
@@ -75,7 +84,10 @@ now ─────────────────────────
- **Deny by default.** A road with any error grants nothing. A road that is valid but expired, or whose subject
has no devices, grants nothing and is reported as *inactive* with its reason. If `directory.json` or
`devices.json` has an error, **no plan is produced at all**.
`devices.json` has a *structural* error, **no plan is produced at all**. A dangling reference (a group member
or a device owner that is no longer a person) is reported and removes only itself: the member leaves the
group, the device becomes ownerless (QA F-04). An empty `until:` or `ports:` is an error, never "absent",
because absent is their widest value (QA F-09). A store without `roads/` is an error too (QA F-07).
- **Allowed IPs** are cryptokey routing, not permission. The permission is the firewall rule on the far side:
a road from Jana's phone to the home server gives the phone a peer for the server's address, gives the server
a peer for the phone's address (so replies are accepted), and gives the server one inbound rule from the
@@ -84,7 +96,16 @@ now ─────────────────────────
everything except private, link-local, loopback, CGNAT and ULA ranges, so an exit user does not reach the
exit's LAN. A device with active exit roads to two different exits gets neither, and both are reported.
- **Kill switch fails closed.** Two kill-switch roads naming different exits on one device give a kill switch
through no exit at all (only the mesh), never none.
through no exit at all (only the mesh), never none. So does a kill-switch road with an error, for example
when its exit stops being one: it is reported, and still applied in the closed form (QA F-03). An expired
kill switch ends as written.
- **The tunnel wins over going direct.** A `goes-direct` subnet (other than `/0`) that holds a mesh address is
refused (`direct.mesh`). Per device, a direct subnet inside a net the plan tunnels is dropped
(`direct.tunnelled`); one that holds tunnelled nets keeps them in the tunnel, listed in `direct[].except`, so
no platform has to guess which route wins (QA F-02). A platform that cannot honour `except` (an app-level
bypass) must not apply the entry.
- **Mesh addresses are never internet addresses** (QA F-08), and a road from IPv4 devices to an IPv6 place (or
the other way) gives those devices nothing and says so (`road.family`, QA F-06).
- **Deterministic.** Every collection is a `BTreeMap`/`BTreeSet` or a sorted `Vec`; road files are read in file
name order; the same input gives byte-identical JSON and CBOR.
@@ -98,7 +119,9 @@ now ─────────────────────────
| A custom raw block widens access | an `AllowedIPs` line the compiler never checked | raw blocks are never merged into peers; they sit in `Plan.custom`, labelled; Day 3 must not apply them without an expert's confirmation |
| Non-determinism (hash order, file order, locale) | two compiles disagree; signatures do not match | no `HashMap` on any output path; byte-identical test with shuffled input; golden files |
| The YAML subset parser accepts a construct it should refuse | a road file means something other than it reads | Pensum's subset, refused constructs each have a fixture |
| A kill switch road with an error turns the kill switch off | traffic leaks when the tunnel drops | conflicting kill switches fail closed; an *invalid* kill-switch road is an open question below |
| A kill switch road with an error turns the kill switch off | traffic leaks when the tunnel drops | conflicting and erroneous kill-switch roads both fail closed (QA F-03); a kill-switch file that does not *parse* is not in the store and is only reported (gap below) |
| A service road opens a neighbour on the same host and port | "Jana can reach Photos" also reaches Git | services get their own mesh address, or the road is refused (`service.shared`, QA F-01) |
| Going direct pulls tunnelled traffic out of the tunnel | home-LAN or mesh traffic in the clear on a hostile network | `direct.mesh`, `direct.tunnelled`, `direct[].except` (QA F-02) |
| The people directory format changes | person ids no longer match | `PersonId` is one opaque newtype; changing it is one function |
## Gaps (what this day does not do)
@@ -106,14 +129,29 @@ now ─────────────────────────
- Plans are not signed: Day 3 signs them with Tessera; `proto` leaves room (a new message version).
- No people directory exists in Fundamentum; `directory.json` is our own snapshot format until it does.
- Groups are **flat**: members are people, never groups, so there is no nesting to resolve and no cycle
(QA R-13 to R-15 do not arise; a group id among the members is `directory.member`).
(QA R-13 to R-15 do not arise; a group id among the members is left out, `directory.member-unknown`).
- **Plans can be replayed (QA B-1).** Proto v1 has no serial and no `not_after`. Day 3's signed v2 must carry a
monotonic serial, which a device refuses at or below the last one it applied (persisted across restarts),
and `not_after`. Recorded here, not fixed: v1 is unsigned by design.
- **A kill-switch road that does not parse** (a typo in a key) is not in the store, so nothing applies its
restriction; `via check` reports it as an error. Failing closed would need the subject of a file that did not
parse. Day 4's editor must not save such a file.
- **An app-level `goes-direct` to `/0`** keeps only the plan's tunnelled nets in the tunnel (`except`); traffic
from that app to mesh addresses the device has no peer for goes direct. It could not have reached them
through the tunnel either.
- **Ids are case-sensitive** (QA F-12): `person:Jana` and `person:jana` are two people. Decide when the people
directory exists (open question 2).
- **Never run on Linux** (QA F-11): the `#[cfg(unix)]` symbolic-link case has not executed and the golden files
were produced on Windows. One Linux run is wanted before the tag; WSL did not start on this PC.
- Multi-hop exits (`via` on `exits-through`) are refused, not compiled: Day 6.
- `via` on `can-reach` is a path hint (relay or exit) carried in the peer; the engine decides what it means.
- No `via export` of a classic WireGuard config: Day 5. Its exporter must write no free text (road notes,
names) into the file; names here are already free of line breaks and hidden characters (QA R-42).
- No Custos approval field on roads: approvals are Day 4, and a new key is an *unknown key* to this build.
- `explain` and `check` answer as an administrator. A web view (Day 5) must scope them to the asker (QA R-49,
R-51): today they name every road.
- `explain` and `check` answer as an administrator (QA R-49, R-51, F-13): they name every road and every
problem. **This blocks the Day 5 web view**: before it ships, both must take the asker and answer only about
the asker's own devices and the roads whose subject or object covers them, with snapshot problems shown to
administrators only.
- Firewall rules are one per (source, destination, port range): a group of 1,000 people to 1,000 places is
10⁶ rules, not grouped into sets (QA R-59). Measured instead (QA R-56): 10,000 roads, 2,000 devices →
249,400 grants and 5,978 rules in 0.59 s (release) and 3.1 s (debug), `tests/attacks.rs`.
@@ -149,7 +187,34 @@ that reads the generated world with `u32` arithmetic and no `roads` code. Differ
without `classic: true`, which the oracle does not model. The fixtures check the positive cases instead;
- P-5 (permutations) and P-6 (revocation completeness) are fixture tests (`determinism.rs`, `revocation.rs`);
- P-3 and P-4 leave out exit rules: removing one of two conflicting exit roads is *meant* to let the other apply;
- R-55 (renaming every id gives an isomorphic plan) is not done.
- R-55 (renaming every id gives an isomorphic plan) was added by QA in review (`tests/rename.rs`);
- IPv6 is checked by embedding (QA F-10): P-6v6 writes the same world into `fd00::/96` and requires the same
plans, mapped, and the same problems.
## QA review of PR #1, and what changed
QA's review (`Via/qa/review-via-core-pr1.md`, PR comments 49910–49925) found one blocker and five majors in the
model. Each finding had a failing test in `tests/qa_findings.rs`; every one now passes, un-ignored in the
commit that fixed it.
| # | Finding | Resolution |
|:--|:--|:--|
| F-01 | a service road opened every service on the same host and port | services may have their own mesh address; a shared address and port is `service.shared` |
| F-02 | goes-direct could take mesh or tunnelled subnets out of the tunnel | `direct.mesh`, `direct.tunnelled`, `direct[].except` |
| F-03 | an invalid kill-switch road failed open | fails closed, through no exit |
| F-04 | one dangling owner gave no plans for anybody | dangling owners and members drop only themselves |
| F-09 | an emptied `until:` or `ports:` widened the road | `key.empty` |
| B-3 | `app:` roads reached every device | `on:` is required and scopes the road |
| F-05 | a custom block on a classic device was labelled post-quantum | the device's flag counts |
| F-06 | cross-family roads compiled into dead rules | `road.family` |
| F-07 | a missing `roads/` was silent | `store.roads` |
| F-08 | mesh addresses could be public | refused |
| F-10 | the property had no IPv6 | P-6v6 |
| B-1, F-11, F-12, F-13 | replay, Linux, case, explain as admin | recorded under Gaps |
QA's R-55 property itself failed about once in four runs: a group renamed to `in` turned every firewall
`"direction": "in"` into the group's old name. The renaming now reserves every word of the output, and the seed
is a fixed test.
## Tests
@@ -160,7 +225,7 @@ commits, and the history shows that.
|:--|:--|:--|
| 1 | Validation: every rule has a failing fixture naming the file and the field; a meta-test fails if a rule has none; a failing road changes no plan byte | `crates/roads/tests/validation.rs`, fixtures in `crates/roads/tests/fixtures/invalid/` (`expect.txt`) |
| 2 | Revocation: deleting a road, expiring it, moving or removing a device, or a person from a group, removes the access on both sides | `crates/roads/tests/revocation.rs` |
| 3 | Least privilege: proptest, 5,000 cases for P-1 and 500 each for the invalid/expired and P-3/P-4 properties | `crates/roads/tests/least_privilege.rs` |
| 3 | Least privilege: proptest, 5,000 cases for P-1, 1,000 for P-6v6 (IPv6 by embedding) and 500 each for the invalid/expired and P-3/P-4 properties | `crates/roads/tests/least_privilege.rs` |
| 4 | Determinism: byte-identical twice, with shuffled input, with CRLF files, against golden plans; CBOR twice and decode → encode, a pinned digest | `crates/roads/tests/determinism.rs`, `crates/proto/tests/roundtrip.rs` |
| 5 | `explain` returns exactly the allowing roads, each one enough alone, and nothing when denied | `crates/roads/tests/explain.rs` |
| 6 | Custom roads round-trip unchanged: file → render, through the plan and through CBOR | `crates/roads/tests/custom.rs`, `crates/proto/tests/roundtrip.rs` |
@@ -171,8 +236,8 @@ and the binary in `crates/via-cli/tests/cli.rs`. Dates use `jiff`: `chrono` is f
## Open questions
1. Should an *invalid* `never-online-without` road fail closed (kill switch on through no exit), since "grants
nothing" turns the protection off? This build reports it and does not apply it.
1. ~~Should an invalid `never-online-without` road fail closed?~~ Answered: yes (QA F-03, and Mark's "nothing
leaks when the tunnel drops"). It is reported and applied through no exit.
2. Does the people directory key people by a Tessera root key, a random id, or a name? `PersonId` waits.
3. Where does a service's hosting device come from: Ianitor's upstreams name hosts and ports, not Tessera keys.
This build takes it from `devices.json`.
+29 -12
View File
@@ -14,7 +14,10 @@ versioned; a change that an older build would misread bumps the version.
`roads/` holds only regular files named `<id>-<slug>.md`. Anything else in it — a folder, a symbolic link, a
file with another name — is an error (`file.kind`), so the folder can never hold something the compiler does
not read. Files are read in byte order of their names. At most 10,000 road files.
not read. Files are read in byte order of their names. At most 10,000 road files. A store without a `roads/`
folder, or whose `roads/` is a file or a symbolic link, is `store.roads`: nothing is read, nothing is granted,
and it is said out loud, because pointing `--store` one folder too high would otherwise revoke everything,
kill switches included, without a word (QA F-07).
## Road files
@@ -39,7 +42,7 @@ The same strict subset of YAML as Pensum's tickets (Fabrica `core/docs/FORMATS.m
| a single-quoted string, `''` for a quote | `subject: 'person:jana'` |
| a flow list of scalars | `ports: [tcp/443, udp/53]` |
| a block list of scalars, indented under its key | `ports:` then ` - tcp/443` |
| an empty value, meaning *absent* | `until:` |
| an empty value, meaning *absent*; for `until` and `ports` it is an error (`key.empty`) | `via:` |
| comment lines, blank lines, a trailing ` # comment` after a plain value or list | `# moved from the router` |
Refused, each with an error naming the file, the line and the field (`yaml.refused`): anchors (`&a`), aliases
@@ -53,8 +56,9 @@ is not `key: value`, or a bad quoted string, is `yaml.syntax`.
|:--|:--|:--|:--|
| `id` | yes | 6 characters of `0123456789abcdefghjkmnpqrstvwxyz` (no `i l o u`), random | `id.format`; must equal the file name's prefix (`id.file-name`); unique in the store (`id.duplicate`, both files grant nothing) |
| `subject` | yes | a reference (below): `person:`, `group:`, `device:` or `app:` | `ref.format`, `subject.kind` (not allowed for the verb), `subject.unknown` (not in the snapshots) |
| `on` | yes for an `app:` subject, not allowed otherwise | a reference: `person:`, `group:` or `device:`: whose devices the app road applies to | `key.missing`, `key.forbidden`, `ref.format`, `subject.kind`, `subject.unknown`. Without it an app road would change the tunnel of every device in the mesh, other people's included (QA B-3) |
| `verb` | yes | `can-reach`, `exits-through`, `goes-direct`, `never-online-without`, `custom` | `verb.unknown` |
| `object` | yes, except `custom` (where it is not allowed) | a reference: `device:`, `subnet:`, `service:` or `exit:` | `ref.format`, `object.kind`, `object.unknown`, `object.not-exit`, `subnet.not-canonical`, `subnet.unrouted` |
| `object` | yes, except `custom` (where it is not allowed) | a reference: `device:`, `subnet:`, `service:` or `exit:` | `ref.format`, `object.kind`, `object.unknown`, `object.not-exit`, `subnet.not-canonical`, `subnet.unrouted`, `service.shared` (a service that shares its address and a port with another: its rule would open both, QA F-01); a `goes-direct` subnet other than `/0` that holds a mesh address is `direct.mesh` (mesh traffic never goes direct, QA F-02) |
| `until` | no | RFC 3339 with an offset: `2026-11-29T23:59:59+01:00` or `…Z`; exclusive | `until.format`; `until <= now` makes the road *inactive* (`road.expired`) |
| `ports` | no; only `can-reach` | a list of `tcp/443`, `udp/53`, `tcp/8000-8100`, `tcp`, `udp`, `icmp`; absent means all traffic | `ports.format`; for a service, every port must be one it serves (`ports.not-served`) |
| `via` | no; only `can-reach` | `device:<key>` of a device with `relay` or `exit` | `via.format`, `via.unknown`, `via.not-relay` |
@@ -63,16 +67,18 @@ is not `key: value`, or a bad quoted string, is `yaml.syntax`.
Any other key is `key.unknown`. A key that the verb does not take is `key.forbidden`. A list where a single value
belongs, or a single value where a list belongs, is `key.type`. A required key that is missing or empty is
`key.missing`.
`key.missing`. `until` and `ports` narrow a road, and absent is their widest value (no end, all traffic), so
either key present with an empty value (`until:`, `until: # Sunday`, `ports:`) is `key.empty`: clearing a field
never widens a road (QA F-09). `ports: []` is `ports.format`.
### References
| Form | Meaning | Id rules |
|:--|:--|:--|
| `person:<id>` | a person in `directory.json` | opaque: 1–64 of `[A-Za-z0-9_-]` (no people directory exists in Fundamentum yet) |
| `person:<id>` | a person in `directory.json`: their post-quantum devices (classic devices are never covered by a person or group, only by their own `device:` road) | opaque: 1–64 of `[A-Za-z0-9_-]` (no people directory exists in Fundamentum yet) |
| `group:<id>` | a group in `directory.json` | as a person id |
| `device:<key>` | a device in `devices.json` | the Tessera device subkey: 32-byte Ed25519 public key, base64url without padding, 43 characters, canonical |
| `app:<id>` | a Domi app on every device | the Tessera id: 1–32 of `[a-z0-9-]`, not starting or ending with `-` |
| `app:<id>` | a Domi app, on the devices its road's `on` names (QA B-3) | the Tessera id: 1–32 of `[a-z0-9-]`, not starting or ending with `-` |
| `subnet:<cidr>` | an IPv4 or IPv6 network | canonical: host bits zero (`192.168.100.0/24`, not `192.168.100.7/24`) and in the usual text form; IPv6 that embeds IPv4 (`::ffff:0:0/96`, `::/96`, `64:ff9b::/96`, `64:ff9b:1::/48`, `2002::/16`) is `ref.format`: write the IPv4 subnet |
| `service:<hostname>` | an Ianitor host, served by a device in `devices.json` | Ianitor's hostname rules: lowercase, labels of `[a-z0-9-]` not starting or ending with `-`, at most 63 per label and 253 in all, no wildcard, no trailing dot, not an IP address |
| `exit:<key>` | a device with `exit: true` | a device key |
@@ -92,7 +98,7 @@ Everything after the closing `---`.
### Canonical form
The form `via` writes, and which reads back byte for byte: `---`, then the keys in the order `id, subject, verb,
The form `via` writes, and which reads back byte for byte: `---`, then the keys in the order `id, subject, on, verb,
object, until, ports, via, classic, created`, absent keys left out, scalars plain when they read back unchanged
and double-quoted otherwise, `ports` as a flow list, LF line endings, `---`, then the body. A custom road's body
is ```` ```raw\n ```` + raw + ```` ```\n ````.
@@ -120,6 +126,8 @@ Valid roads that grant nothing right now, reported with their reason (not errors
| `road.no-devices` | the subject has no devices |
| `road.self` | every subject device is the object's own device |
| `exit.conflict` | for one device: active `exits-through` roads to two different exits (that device gets neither; reported per road, naming the device) |
| `direct.tunnelled` | for one device: a `goes-direct` subnet inside a net its plan sends through the tunnel (a route it reaches, a peer's address); the tunnel wins and the entry is dropped (reported per road, naming the device, QA F-02) |
| `road.family` | a `can-reach` road from devices whose mesh address is IPv4 to an IPv6 place, or the other way: those devices get nothing (a rule that could never match), reported naming them (QA F-06) |
| `direct.kill-switch` | for one device with a kill switch: a `goes-direct` road to a subnet that reaches the internet; the kill switch wins and the subnet stays in the tunnel (reported per road, naming the device). Going direct to a private subnet stays allowed |
## `directory.json` — the people directory snapshot
@@ -139,10 +147,17 @@ Valid roads that grant nothing right now, reported with their reason (not errors
| `people[].name` | 1–100 characters, no leading or trailing space, and none of: control characters (CR, LF, U+0085 included), U+2028, U+2029, zero-width characters U+200B–U+200F and U+2060–U+2069, bidi controls U+202A–U+202E, U+FEFF (`directory.name`) — so a name can never carry a line into an exported config |
| `groups[].id` | a group id, unique among groups |
| `groups[].name` | as a person's name |
| `groups[].members` | person ids that exist, no repeats (`directory.member`) |
| `groups[].members` | person ids, no repeats (`directory.member`); a well-formed id that is not a person in `people` is left out of the group (`directory.member-unknown`) |
Unknown fields, bad JSON and a missing file are `snapshot.json`.
**Structural errors and dangling references (QA F-04).** Any error in either snapshot means no plan at all,
with two exceptions: a group member and a device owner that are well-formed ids but not people in the
directory. That is what deleting a person upstream leaves behind, before anybody edits `devices.json`. Each
is still an error and is reported, but it removes only itself: the member leaves the group, and the device
becomes ownerless, so only `device:` roads reach it. Everybody else keeps their plans. "No plans" is kept for
what makes the snapshot unreadable: bad JSON, a wrong format, a malformed or duplicate id, key or address.
## `devices.json` — the device list
```json
@@ -162,14 +177,15 @@ Unknown fields, bad JSON and a missing file are `snapshot.json`.
| `format` | — | `1` |
| `key` | — | a device key (`devices.key`), unique (`devices.duplicate`) |
| `name` | — | 1–64 characters of `[a-z0-9-]`, unique (`devices.name`) |
| `owner` | none | a person id in the directory (`devices.owner`); a device with no owner is reached only by `device:` roads |
| `address` | — | the device's mesh address, one IPv4 or IPv6 address, unique, not inside any device's routes, not loopback, link-local, multicast or IPv4-embedding IPv6 (`devices.address`) |
| `owner` | none | a person id (`devices.owner`). One that is not in the directory leaves the device ownerless (`devices.owner-unknown`, reported). A device with no owner is reached only by `device:` roads |
| `address` | — | the device's mesh address, one IPv4 or IPv6 address, unique, not inside any device's routes, not loopback, link-local, multicast or IPv4-embedding IPv6, and never an internet address, so an exit's `internet` rule can never cover a mesh device (QA F-08): use `100.64.0.0/10` or a ULA (`devices.address`) |
| `classic` | `false` | a classic WireGuard peer, **not post-quantum** |
| `exit` | `false` | offers itself as an exit |
| `relay` | `false` | may be named by `via` |
| `routes` | `[]` | canonical subnets this device routes for the mesh: private only, so not `/0`, nothing that reaches the internet (use an exit), nothing loopback, link-local, multicast, reserved or IPv4-embedding; no overlap with another device's (`devices.route`, `devices.overlap`). This is also why two peers of one device can never hold the same prefix |
| `services[].host` | — | an Ianitor hostname, unique across devices (`devices.service`) |
| `services[].ports` | — | a non-empty port list (`devices.ports`) |
| `services[].address` | none | the service's own mesh address on this device, under the same rules as a device `address` and unique among all of them (`devices.address`). A firewall sees addresses and ports, not hostnames: a road to a service compiles to its own address when it has one, else to the device's, and a road to a service that shares that address **and** a port with another service is refused (`service.shared`, QA F-01), because its rule would open the other one too |
## The plan
@@ -181,14 +197,15 @@ entry.
|:--|:--|
| `format` | `1` |
| `device`, `name`, `address`, `classic` | this device |
| `services[]` | `{host, address}`: the services this device hosts on an address of their own; it must answer on each (QA F-01). A road to such a service reaches that address only; a `device:` road reaches the device's address and all of these |
| `expires` | the earliest `until` (UTC, `Z`) of every road this plan was built from, on the subject's plan and on the serving device's alike; the engine must stop applying the plan at that instant even if nothing recompiles (QA R-26); `null` if none |
| `peers[]` | `key`, `name`, `address`, `classic` (*not post-quantum* when true), `allowed_ips` (sorted CIDRs), `via` (a path hint or `null`), `roads` |
| `firewall.default` | always `"deny"` |
| `firewall.rules[]` | `direction` (`in`: to this device's address; `forward`: to a subnet it routes, or to the internet as an exit), `src` (CIDR), `dst` (CIDR or `"internet"`), `proto` (`any`, `tcp`, `udp`, `icmp`), `ports` (`[lo, hi]` or `null`), `roads` |
| `dns[]` | `host`, `address`, `roads`: names this device may resolve to a mesh address |
| `exit` | `{through, roads}` or `null` |
| `kill_switch` | `{through, roads}` (`through` is `null` when two kill-switch roads disagree: only the mesh) or `null` |
| `direct[]` | `{app, subnet, roads}`: traffic to `subnet` bypasses the tunnel (split tunnelling); `app` is `null` for all traffic, or the one app whose traffic goes direct |
| `kill_switch` | `{through, roads}` or `null`. `through` is `null` (only the mesh) when two kill-switch roads disagree, or when a kill-switch road has an error: a restriction fails closed, it is never dropped (QA F-03). `roads` lists the erroneous road too |
| `direct[]` | `{app, subnet, except, roads}`: traffic to `subnet` bypasses the tunnel (split tunnelling); `app` is `null` for all traffic, or the one app whose traffic goes direct. `except` lists the nets inside `subnet` that this plan sends through the tunnel (its peers' non-default allowed IPs): they stay in the tunnel, whatever the platform's route order. A platform that cannot keep them in (an app-level bypass) must not apply the entry (QA F-02) |
| `custom[]` | `{road, classic, raw}`: the raw block verbatim, **never checked by the compiler** |
`internet` is every address except `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10`, `127.0.0.0/8`, `169.254.0.0/16`,
Generated
+27
View File
@@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1793865203,
"narHash": "sha256-/cpdPHaySDIyCgZI6EWngiM6jK3YLUNzv1b7lTzy6Bk=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "c56a87d8e41ce69bd2af57eb35dcc117a9dfca33",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-26.05",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
+17
View File
@@ -0,0 +1,17 @@
{
description = "The Linux test shell for Fabrica's NixOS runner (.fabrica/artifex/linux.yaml)";
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-26.05";
outputs =
{ self, nixpkgs }:
let
pkgs = nixpkgs.legacyPackages.x86_64-linux;
in
{
# nix develop .#ci -c cargo test : the toolchain only; the tests fetch crates from crates.io.
devShells.x86_64-linux.ci = pkgs.mkShell {
packages = with pkgs; [ cargo rustc clippy rustfmt git ];
};
};
}
+38 -1
View File
@@ -6,7 +6,9 @@
//! 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.
//! 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`.
//!
@@ -80,6 +82,17 @@ fn baseline() -> &'static Vec<String> {
})
}
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)
@@ -142,6 +155,30 @@ fuzz_target!(|data: &[u8]| {
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");
}
}
});