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.