[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.
This commit is contained in:
2026-11-25 07:55:38 +01:00
parent f134ec652c
commit 38a2fea043
119 changed files with 9123 additions and 0 deletions
+514
View File
@@ -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<PersonId>,
}
/// The people directory snapshot, validated.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Directory {
pub people: BTreeMap<PersonId, Person>,
pub groups: BTreeMap<GroupId, Group>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Service {
pub host: Hostname,
pub ports: Vec<PortSpec>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Device {
pub key: DeviceKey,
pub name: String,
pub owner: Option<PersonId>,
pub address: Addr,
/// A classic WireGuard peer: **not post-quantum**.
pub classic: bool,
pub exit: bool,
pub relay: bool,
pub routes: Vec<Net>,
pub services: Vec<Service>,
}
/// The device list, validated.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Devices {
pub devices: BTreeMap<DeviceKey, Device>,
}
impl Devices {
pub fn by_name(&self, name: &str) -> Option<&Device> {
self.devices.values().find(|d| d.name == name)
}
/// The device serving `host`.
pub fn service(&self, host: &Hostname) -> Option<(&Device, &Service)> {
self.devices
.values()
.find_map(|d| d.services.iter().find(|s| &s.host == host).map(|s| (d, s)))
}
/// The one device whose routes cover `net`.
pub fn router_of(&self, net: &Net) -> Option<&Device> {
self.devices
.values()
.find(|d| d.routes.iter().any(|r| r.contains(net)))
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawDirectory {
format: u32,
people: Vec<RawPerson>,
#[serde(default)]
groups: Vec<RawGroup>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawPerson {
id: String,
name: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawGroup {
id: String,
name: String,
members: Vec<String>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawDevices {
format: u32,
devices: Vec<RawDevice>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawDevice {
key: String,
name: String,
#[serde(default)]
owner: Option<String>,
address: String,
#[serde(default)]
classic: bool,
#[serde(default)]
exit: bool,
#[serde(default)]
relay: bool,
#[serde(default)]
routes: Vec<String>,
#[serde(default)]
services: Vec<RawService>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawService {
host: String,
ports: Vec<String>,
}
fn read_json<T: for<'de> Deserialize<'de>>(path: &str, bytes: &[u8]) -> Result<T, Vec<Problem>> {
if bytes.len() > MAX_SNAPSHOT {
return Err(vec![Problem::error(
path,
None,
r::SNAPSHOT_JSON,
"larger than 4 MiB",
)]);
}
serde_json::from_slice(bytes).map_err(|e| {
vec![
Problem::error(
path,
None,
r::SNAPSHOT_JSON,
format!("not a valid snapshot: {e}"),
)
.at(e.line()),
]
})
}
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<Directory, Vec<Problem>> {
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<Devices, Vec<Problem>> {
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::<std::net::IpAddr>() {
Ok(a)
if a.to_string() == d.address
&& !Net::host(a).is_special()
&& !Net::host(a).embeds_ipv4() =>
{
if !addresses.insert(a) {
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)
}
}
}