[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
+758
View File
@@ -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<Vec<PortSpec>>,
dns: Option<Hostname>,
via: Option<DeviceKey>,
},
/// `from` sends its internet traffic through `exit`.
Exit {
road: RoadId,
from: DeviceKey,
exit: DeviceKey,
},
}
impl Grant {
pub fn road(&self) -> &RoadId {
match self {
Grant::Reach { road, .. } | Grant::Exit { road, .. } => road,
}
}
pub fn from(&self) -> &DeviceKey {
match self {
Grant::Reach { from, .. } | Grant::Exit { from, .. } => from,
}
}
}
/// The compiler's output.
#[derive(Debug, Clone, Default)]
pub struct Compiled {
/// One plan per device in `devices.json`; empty when a snapshot has an error.
pub plans: BTreeMap<DeviceKey, Plan>,
/// The store's problems and the compiler's, sorted.
pub problems: Vec<Problem>,
/// What the active roads grant, in road order.
pub grants: Vec<Grant>,
}
impl Compiled {
pub fn errors(&self) -> impl Iterator<Item = &Problem> {
self.problems.iter().filter(|p| p.is_error())
}
/// Whether the snapshots were good enough to produce plans.
pub fn has_plans(&self) -> bool {
!self.plans.is_empty()
}
}
type DirectKey = (Option<AppId>, Net);
type RuleKey = (Direction, Net, Dst, Proto, Option<[u16; 2]>);
#[derive(Default)]
struct Extras {
direct: BTreeMap<DirectKey, BTreeSet<RoadId>>,
kill: BTreeMap<DeviceKey, BTreeSet<RoadId>>,
custom: Vec<plan::Custom>,
}
/// 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<DeviceKey> {
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<crate::ids::PersonId, BTreeSet<DeviceKey>>,
}
impl Index {
fn new(devs: &Devices) -> Index {
let mut by_owner: BTreeMap<_, BTreeSet<DeviceKey>> = BTreeMap::new();
for d in devs.devices.values() {
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<DeviceKey> {
match subject {
Subject::Person(p) => self.by_owner.get(p).cloned().unwrap_or_default(),
Subject::Group(g) => dir
.groups
.get(g)
.map(|g| {
g.members
.iter()
.filter_map(|m| self.by_owner.get(m))
.flatten()
.cloned()
.collect()
})
.unwrap_or_default(),
Subject::Device(k) => devs
.devices
.contains_key(k)
.then(|| k.clone())
.into_iter()
.collect(),
Subject::App(_) => 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<DeviceKey>,
) -> Vec<Problem> {
let mut out = Vec::new();
let p = |field: &str, code, msg: String| {
Problem::error(&road.path, Some(field), code, msg).at(road.line_of(field))
};
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<String> = 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<DeviceKey, Extras> = BTreeMap::new();
let mut expiry: BTreeMap<DeviceKey, Instant> = BTreeMap::new();
let mut touch = |k: &DeviceKey, road: &Road| {
if let Some(u) = &road.until {
let at = u.at();
expiry
.entry(k.clone())
.and_modify(|e| *e = (*e).min(at))
.or_insert(at);
}
};
let index = Index::new(devs);
let mut roads: Vec<&Road> = store.roads.iter().collect();
roads.sort_by(|a, b| a.id.cmp(&b.id));
for road in roads {
let subject = index.devices_of(&road.subject, 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<DeviceKey, BTreeMap<DeviceKey, BTreeSet<RoadId>>> = BTreeMap::new();
for g in &out.grants {
if let Grant::Exit { road, from, exit } = g {
exits
.entry(from.clone())
.or_default()
.entry(exit.clone())
.or_default()
.insert(road.clone());
}
}
let mut conflicted: BTreeSet<DeviceKey> = BTreeSet::new();
for (from, by_exit) in &exits {
if by_exit.len() < 2 {
continue;
}
conflicted.insert(from.clone());
let all: BTreeSet<&RoadId> = by_exit.values().flatten().collect();
for id in &all {
let road = store
.roads
.iter()
.find(|r| &r.id == *id)
.expect("a granting road");
let others: Vec<String> = all
.iter()
.filter(|o| o != &id)
.map(|o| o.to_string())
.collect();
out.problems.push(
Problem::inactive(
&road.path,
Some("object"),
r::EXIT_CONFLICT,
format!(
"for {}: conflicts with road {} (two different exits); that device exits through neither",
name(from),
others.join(", ")
),
)
.at(road.line_of("object")),
);
}
}
out.grants
.retain(|g| !matches!(g, Grant::Exit { from, .. } if conflicted.contains(from)));
// The kill switch wins over going direct to the internet: a device with a kill switch never sends internet
// traffic outside the tunnel, whatever a goes-direct road says (QA R-47). Going direct to a private subnet
// (the local network) stays allowed.
for (key, ex) in extras.iter_mut() {
if ex.kill.is_empty() {
continue;
}
let kill_roads: Vec<String> = ex.kill.values().flatten().map(|r| r.to_string()).collect();
let dropped: Vec<(DirectKey, BTreeSet<RoadId>)> = ex
.direct
.iter()
.filter(|((_, n), _)| n.reaches_internet())
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
for ((app, subnet), roads) in dropped {
ex.direct.remove(&(app, subnet));
for id in roads {
let road = store
.roads
.iter()
.find(|r| r.id == id)
.expect("a granting road");
out.problems.push(
Problem::inactive(
&road.path,
Some("object"),
r::DIRECT_KILL_SWITCH,
format!(
"for {}: the kill switch (road {}) wins; {subnet} does not go direct",
name(key),
kill_roads.join(", ")
),
)
.at(road.line_of("object")),
);
}
}
}
// Each device's plan reads only the grants that name it.
let mut by_device: BTreeMap<&DeviceKey, Vec<&Grant>> = BTreeMap::new();
for g in &out.grants {
let other = match g {
Grant::Reach { host, .. } => host,
Grant::Exit { exit, .. } => exit,
};
by_device.entry(g.from()).or_default().push(g);
by_device.entry(other).or_default().push(g);
}
for (key, dev) in &devs.devices {
let mine = by_device.remove(key).unwrap_or_default();
out.plans.insert(
key.clone(),
build_plan(key, dev, devs, &mine, extras.remove(key), expiry.get(key)),
);
}
out.problems.sort();
out
}
#[derive(Default)]
struct PeerAcc {
allowed: BTreeSet<Net>,
roads: BTreeSet<RoadId>,
vias: BTreeSet<Option<DeviceKey>>,
}
fn build_plan(
me: &DeviceKey,
dev: &crate::snapshot::Device,
devs: &Devices,
grants: &[&Grant],
extras: Option<Extras>,
expiry: Option<&Instant>,
) -> Plan {
let mut peers: BTreeMap<DeviceKey, PeerAcc> = BTreeMap::new();
let mut rules: BTreeMap<RuleKey, BTreeSet<RoadId>> = BTreeMap::new();
let mut dns: BTreeMap<Hostname, (crate::net::Addr, BTreeSet<RoadId>)> = BTreeMap::new();
let mut exit: BTreeMap<DeviceKey, BTreeSet<RoadId>> = BTreeMap::new();
let addr = |k: &DeviceKey| devs.devices[k].address;
for g in grants {
match g {
Grant::Reach {
road,
from,
host,
dst,
forward,
ports,
dns: host_name,
via,
} => {
if from == me {
let p = peers.entry(host.clone()).or_default();
p.allowed.insert(*dst);
p.roads.insert(road.clone());
p.vias.insert(via.clone());
if let Some(h) = host_name {
dns.entry(h.clone())
.or_insert_with(|| (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::<BTreeSet<_>>()
.into_iter()
.collect(),
});
let mut custom = extras.custom;
custom.sort_by(|a, b| a.road.cmp(&b.road));
Plan {
format: plan::FORMAT,
device: me.clone(),
name: dev.name.clone(),
address: dev.address,
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,
}
}
+78
View File
@@ -0,0 +1,78 @@
//! `explain`: which roads let this device reach that place. Read from the compiler's own grants, so the
//! answer and the plans cannot drift apart.
use crate::compile::{Compiled, Grant};
use crate::id::RoadId;
use crate::ids::DeviceKey;
use crate::net::Net;
use crate::ports::{self, PortSpec};
use crate::road::Place;
use crate::snapshot::Devices;
use std::collections::BTreeSet;
/// The roads that let `device` reach (some of) `place`, sorted; empty when access is denied.
///
/// A road counts when one of its grants from `device` overlaps the place: the same network or a part of it,
/// and at least one shared port. An exit road counts for `exit:<that exit>`, and for a subnet that reaches
/// the internet unless that subnet goes direct on this device.
pub fn explain(
compiled: &Compiled,
devs: &Devices,
device: &DeviceKey,
place: &Place,
) -> Vec<RoadId> {
let (dst, want_ports): (Option<Net>, Option<Vec<PortSpec>>) = match place {
Place::Device(k) => (devs.devices.get(k).map(|d| Net::host(d.address.0)), None),
Place::Service(h) => match devs.service(h) {
Some((d, s)) => (Some(Net::host(d.address.0)), Some(s.ports.clone())),
None => (None, None),
},
Place::Subnet(n) => (Some(*n), None),
Place::Exit(_) => (None, None),
};
let direct: Vec<Net> = compiled
.plans
.get(device)
.map(|p| {
p.direct
.iter()
.filter(|d| d.app.is_none())
.map(|d| d.subnet)
.collect()
})
.unwrap_or_default();
let mut out = BTreeSet::new();
for g in &compiled.grants {
if g.from() != device {
continue;
}
match g {
Grant::Reach {
road,
dst: gdst,
ports: gports,
..
} => {
if let Some(dst) = &dst
&& gdst.overlaps(dst)
&& ports::overlaps(gports.as_deref(), want_ports.as_deref())
{
out.insert(road.clone());
}
}
Grant::Exit { road, exit, .. } => {
let counts = match place {
Place::Exit(k) => k == exit,
Place::Subnet(n) => {
n.reaches_internet() && !direct.iter().any(|d| d.contains(n))
}
_ => false,
};
if counts {
out.insert(road.clone());
}
}
}
}
out.into_iter().collect()
}
+464
View File
@@ -0,0 +1,464 @@
//! The strict YAML subset of road headers: Pensum's header subset (Fabrica `core/docs/FORMATS.md`, "The header
//! subset"). Every header this accepts is valid YAML; most of YAML is refused, each refusal naming the line and
//! the field.
use crate::rules;
/// A field's value. Plain scalars are always strings: `true` is text, the field's reader decides.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Value {
/// `key:` with nothing after it: the field is not set.
Absent,
Str(String),
List(Vec<String>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Field {
pub key: String,
/// 1-based line in the file.
pub line: usize,
pub value: Value,
}
/// The first problem in a header: line (1-based in the file), field, rule code, message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeaderError {
pub line: usize,
pub field: Option<String>,
pub code: &'static str,
pub message: String,
}
fn refused(line: usize, field: Option<&str>, message: impl Into<String>) -> HeaderError {
HeaderError {
line,
field: field.map(String::from),
code: rules::YAML_REFUSED,
message: message.into(),
}
}
fn syntax(line: usize, field: Option<&str>, message: impl Into<String>) -> HeaderError {
HeaderError {
line,
field: field.map(String::from),
code: rules::YAML_SYNTAX,
message: message.into(),
}
}
/// Parses header lines (without their line endings). `first_line` is the file line of `lines[0]`.
pub fn parse(lines: &[&str], first_line: usize) -> Result<Vec<Field>, HeaderError> {
let mut fields: Vec<Field> = Vec::new();
let mut i = 0;
while i < lines.len() {
let line = lines[i];
let no = first_line + i;
if line.starts_with('\t') {
return Err(refused(no, None, "tab indentation is not allowed"));
}
let trimmed = line.trim_start_matches(' ');
if trimmed.is_empty() || trimmed.starts_with('#') {
i += 1;
continue;
}
if line.starts_with(' ') {
return Err(refused(
no,
None,
"unexpected indentation: keys start at column 0",
));
}
if line.starts_with('%') {
return Err(refused(no, None, "YAML directives are not allowed"));
}
if line == "..." {
return Err(refused(
no,
None,
"the document end marker `...` is not allowed",
));
}
let Some((key, rest)) = split_key(line) else {
return Err(syntax(
no,
None,
format!("expected `key: value`, found `{}`", crate::ids::clip(line)),
));
};
if fields.iter().any(|f| f.key == key) {
return Err(HeaderError {
line: no,
field: Some(key.to_string()),
code: rules::KEY_DUPLICATE,
message: "duplicate key".into(),
});
}
let rest = rest.trim_start_matches(' ');
let value = if rest.is_empty() || rest.starts_with('#') {
let mut list = Vec::new();
while i + 1 < lines.len() {
let next = lines[i + 1];
if next.starts_with('\t') {
return Err(refused(no + 1, Some(key), "tab indentation is not allowed"));
}
let t = next.trim_start_matches(' ');
if t.len() == next.len() || !(t == "-" || t.starts_with("- ")) {
break;
}
let item_line = first_line + i + 1;
let item = t[1..].trim_start_matches(' ');
if item.starts_with('[') || item.starts_with('-') || item.starts_with('{') {
return Err(refused(
item_line,
Some(key),
"nested lists and mappings are not allowed",
));
}
let (s, after) = scalar(item, false, item_line, key)?;
end_of_value(after, item_line, key)?;
list.push(s);
i += 1;
}
if list.is_empty() {
Value::Absent
} else {
Value::List(list)
}
} else {
inline(rest, no, key)?
};
fields.push(Field {
key: key.to_string(),
line: no,
value,
});
i += 1;
}
Ok(fields)
}
/// `key: rest` with `key` = `[A-Za-z][A-Za-z0-9]*`, the colon followed by a space or the end of the line.
fn split_key(line: &str) -> Option<(&str, &str)> {
let colon = line.find(':')?;
let key = &line[..colon];
let rest = &line[colon + 1..];
let mut b = key.bytes();
let ok =
b.next().is_some_and(|c| c.is_ascii_alphabetic()) && b.all(|c| c.is_ascii_alphanumeric());
(ok && (rest.is_empty() || rest.starts_with(' '))).then_some((key, rest))
}
fn inline(rest: &str, line: usize, key: &str) -> Result<Value, HeaderError> {
if let Some(mut s) = rest.strip_prefix('[') {
let mut items = Vec::new();
loop {
s = s.trim_start_matches(' ');
if let Some(after) = s.strip_prefix(']') {
if !items.is_empty() {
return Err(syntax(line, Some(key), "an empty item in a list"));
}
end_of_value(after, line, key)?;
return Ok(Value::List(items));
}
if s.starts_with('[') || s.starts_with('{') {
return Err(refused(
line,
Some(key),
"nested lists and mappings are not allowed",
));
}
let (item, after) = scalar(s, true, line, key)?;
items.push(item);
let after = after.trim_start_matches(' ');
if let Some(a) = after.strip_prefix(',') {
s = a;
} else if let Some(a) = after.strip_prefix(']') {
end_of_value(a, line, key)?;
return Ok(Value::List(items));
} else {
return Err(syntax(
line,
Some(key),
"a list is `[a, b]`, closed on the same line",
));
}
}
}
let (s, after) = scalar(rest, false, line, key)?;
end_of_value(after, line, key)?;
Ok(Value::Str(s))
}
/// After a value: nothing, or spaces and a ` # comment`.
fn end_of_value(after: &str, line: usize, key: &str) -> Result<(), HeaderError> {
let t = after.trim_start_matches(' ');
if t.is_empty() || (t.starts_with('#') && t.len() < after.len()) {
Ok(())
} else {
Err(syntax(
line,
Some(key),
format!("unexpected `{}` after the value", crate::ids::clip(t)),
))
}
}
/// One scalar at the start of `s`; returns it and what follows.
fn scalar<'a>(
s: &'a str,
in_flow: bool,
line: usize,
key: &str,
) -> Result<(String, &'a str), HeaderError> {
match s.chars().next() {
Some('&') => Err(refused(line, Some(key), "anchors (`&`) are not allowed")),
Some('*') => Err(refused(line, Some(key), "aliases (`*`) are not allowed")),
Some('!') => Err(refused(line, Some(key), "tags (`!`) are not allowed")),
Some('|') | Some('>') => Err(refused(
line,
Some(key),
"block scalars (`|`, `>`) are not allowed",
)),
Some('{') => Err(refused(
line,
Some(key),
"flow mappings (`{}`) are not allowed",
)),
Some('%') | Some('@') | Some('`') | Some('?') | Some(',') | Some(']') | Some('}') => {
Err(syntax(
line,
Some(key),
"a value may not start with this character; quote it",
))
}
Some('"') => double_quoted(&s[1..], line, key),
Some('\'') => single_quoted(&s[1..], line, key),
_ => {
let mut end = s.len();
for (i, c) in s.char_indices() {
if in_flow && matches!(c, ',' | ']') {
end = i;
break;
}
if in_flow && matches!(c, '[' | '{' | '}') {
return Err(syntax(
line,
Some(key),
"quote a list item that holds brackets",
));
}
if c == '#' && i > 0 && s.as_bytes()[i - 1] == b' ' {
end = i;
break;
}
}
let v = s[..end].trim_end_matches(' ');
if v.contains(": ") || v.ends_with(':') {
return Err(syntax(
line,
Some(key),
"a plain value may not contain `: `; quote it",
));
}
if v.is_empty() && in_flow {
return Err(syntax(line, Some(key), "an empty item in a list"));
}
Ok((v.to_string(), &s[v.len()..]))
}
}
}
fn double_quoted<'a>(s: &'a str, line: usize, key: &str) -> Result<(String, &'a str), HeaderError> {
let mut out = String::new();
let mut chars = s.char_indices();
while let Some((i, c)) = chars.next() {
match c {
'"' => return Ok((out, &s[i + 1..])),
'\\' => match chars.next().map(|(_, c)| c) {
Some('"') => out.push('"'),
Some('\\') => out.push('\\'),
Some('n') => out.push('\n'),
Some('t') => out.push('\t'),
Some('r') => out.push('\r'),
Some('u') => {
let hex: String = (0..4)
.filter_map(|_| chars.next().map(|(_, c)| c))
.collect();
let ch = (hex.len() == 4 && hex.bytes().all(|b| b.is_ascii_hexdigit()))
.then(|| u32::from_str_radix(&hex, 16).ok())
.flatten()
.and_then(char::from_u32);
match ch {
Some(ch) => out.push(ch),
None => {
return Err(syntax(
line,
Some(key),
"`\\u` takes 4 hex digits of a character",
));
}
}
}
_ => {
return Err(syntax(
line,
Some(key),
"unknown escape; use \\\" \\\\ \\n \\t \\r \\uXXXX",
));
}
},
c => out.push(c),
}
}
Err(syntax(line, Some(key), "unclosed double-quoted string"))
}
fn single_quoted<'a>(s: &'a str, line: usize, key: &str) -> Result<(String, &'a str), HeaderError> {
let mut out = String::new();
let b = s.as_bytes();
let mut i = 0;
let mut start = 0;
while i < b.len() {
if b[i] == b'\'' {
out.push_str(&s[start..i]);
if b.get(i + 1) == Some(&b'\'') {
out.push('\'');
i += 2;
start = i;
continue;
}
return Ok((out, &s[i + 1..]));
}
i += 1;
}
Err(syntax(line, Some(key), "unclosed single-quoted string"))
}
/// Whether `s` reads back unchanged as a plain scalar in a header value or flow list item.
pub fn is_plain_safe(s: &str, in_flow: bool) -> bool {
let Some(first) = s.chars().next() else {
return false;
};
if "&*!|>{}[]%@`?,#'\"-:".contains(first) || s.ends_with(' ') || s.ends_with(':') {
return false;
}
if s.contains(": ") || s.contains(" #") || s.chars().any(|c| c.is_control()) {
return false;
}
if in_flow && s.contains([',', '[', ']', '{', '}']) {
return false;
}
true
}
/// `s` as a double-quoted scalar.
pub fn quote(s: &str) -> String {
let mut out = String::from("\"");
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'\r' => out.push_str("\\r"),
c if c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
#[cfg(test)]
mod tests {
use super::*;
fn one(line: &str) -> Result<Value, HeaderError> {
parse(&[line], 1).map(|f| f[0].value.clone())
}
#[test]
fn values() {
assert_eq!(one("a: b"), Ok(Value::Str("b".into())));
assert_eq!(one("a: b # note"), Ok(Value::Str("b".into())));
assert_eq!(one("a: b#c"), Ok(Value::Str("b#c".into())));
assert_eq!(one("a: \"x: y\""), Ok(Value::Str("x: y".into())));
assert_eq!(one("a: 'it''s'"), Ok(Value::Str("it's".into())));
assert_eq!(
one("a: [tcp/443, \"udp/53\"] # c"),
Ok(Value::List(vec!["tcp/443".into(), "udp/53".into()]))
);
assert_eq!(one("a: []"), Ok(Value::List(vec![])));
assert_eq!(one("a:"), Ok(Value::Absent));
assert_eq!(
one("a: subnet:fd00::/64"),
Ok(Value::Str("subnet:fd00::/64".into()))
);
assert_eq!(
parse(&["a:", " - x", " - 'y'", "b: c"], 1).unwrap()[0].value,
Value::List(vec!["x".into(), "y".into()])
);
}
#[test]
fn refusals_name_the_line_and_field() {
for (line, code) in [
("a: &x b", rules::YAML_REFUSED),
("a: *x", rules::YAML_REFUSED),
("a: !tag b", rules::YAML_REFUSED),
("a: |", rules::YAML_REFUSED),
("a: >", rules::YAML_REFUSED),
("a: {b: c}", rules::YAML_REFUSED),
("a: [[b]]", rules::YAML_REFUSED),
("a: x: y", rules::YAML_SYNTAX),
("a: \"open", rules::YAML_SYNTAX),
("a: \"\\q\"", rules::YAML_SYNTAX),
("a: [b, ]", rules::YAML_SYNTAX),
("a: [b", rules::YAML_SYNTAX),
("a: \"b\" c", rules::YAML_SYNTAX),
] {
let e = one(line).unwrap_err();
assert_eq!(
(e.code, e.field.as_deref(), e.line),
(code, Some("a"), 1),
"{line}"
);
}
for (lines, code) in [
(&["\ta: b"][..], rules::YAML_REFUSED),
(&[" a: b"][..], rules::YAML_REFUSED),
(&["%YAML 1.2"][..], rules::YAML_REFUSED),
(&["..."][..], rules::YAML_REFUSED),
(&["a: b", "a: c"][..], rules::KEY_DUPLICATE),
(&["a:", " - - b"][..], rules::YAML_REFUSED),
(&["just text"][..], rules::YAML_SYNTAX),
(&["a:b"][..], rules::YAML_SYNTAX),
] {
assert_eq!(parse(lines, 1).unwrap_err().code, code, "{lines:?}");
}
}
#[test]
fn plain_safety_round_trips() {
for s in [
"person:jana",
"tcp/443",
"2026-11-29T23:59:59+01:00",
"subnet:fd00::/64",
"true",
] {
assert!(is_plain_safe(s, true), "{s}");
assert_eq!(one(&format!("a: {s}")), Ok(Value::Str(s.into())));
}
for s in ["", "-x", "a: b", "a #b", "[x", "x ", "'q"] {
assert!(!is_plain_safe(s, false), "{s}");
assert_eq!(
one(&format!("a: {}", quote(s))),
Ok(Value::Str(s.into())),
"{s}"
);
}
}
}
+116
View File
@@ -0,0 +1,116 @@
//! Road ids and file names, in Pensum's style (Fabrica `core/crates/pensum/src/id.rs`).
use std::collections::BTreeSet;
use std::fmt;
/// Lowercase Crockford base32: no `i l o u`.
pub const ALPHABET: &[u8; 32] = b"0123456789abcdefghjkmnpqrstvwxyz";
pub const LEN: usize = 6;
pub const SLUG_MAX: usize = 40;
/// A road id: 6 random characters of [`ALPHABET`].
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize)]
#[serde(transparent)]
pub struct RoadId(String);
impl RoadId {
pub fn new(s: &str) -> Option<RoadId> {
is_valid(s).then(|| RoadId(s.to_string()))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for RoadId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl fmt::Debug for RoadId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "RoadId({})", self.0)
}
}
impl<'de> serde::Deserialize<'de> for RoadId {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
RoadId::new(&s).ok_or_else(|| serde::de::Error::custom(format!("`{s}` is not a road id")))
}
}
pub fn is_valid(s: &str) -> bool {
s.len() == LEN && s.bytes().all(|b| ALPHABET.contains(&b))
}
/// A random id not in `existing`, from `fill` (the caller's random source: this crate does no I/O).
/// Each byte picks one character (256 / 32: no bias).
pub fn generate_with(existing: &BTreeSet<RoadId>, mut fill: impl FnMut(&mut [u8])) -> RoadId {
loop {
let mut buf = [0u8; LEN];
fill(&mut buf);
let id: String = buf
.iter()
.map(|b| ALPHABET[(b & 31) as usize] as char)
.collect();
let id = RoadId(id);
if !existing.contains(&id) {
return id;
}
}
}
/// Whether a file-name slug is well formed: `[a-z0-9]+(-[a-z0-9]+)*`, at most 40 characters.
pub fn is_valid_slug(s: &str) -> bool {
!s.is_empty()
&& s.len() <= SLUG_MAX
&& s.split('-').all(|part| {
!part.is_empty()
&& part
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
})
}
/// Splits `<id>-<slug>.md` into the id text and the slug, if the name has that shape.
pub fn split_file_name(name: &str) -> Option<(&str, &str)> {
let stem = name.strip_suffix(".md")?;
let (id, slug) = stem.split_once('-')?;
(is_valid(id) && is_valid_slug(slug)).then_some((id, slug))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids_and_names() {
assert!(is_valid("k3f9q2"));
assert!(!is_valid("k3f9qi"), "i is not in the alphabet");
assert!(!is_valid("K3F9Q2"));
assert!(!is_valid("k3f9q"));
assert_eq!(
split_file_name("k3f9q2-jana-photos.md"),
Some(("k3f9q2", "jana-photos"))
);
assert_eq!(split_file_name("k3f9q2.md"), None);
assert_eq!(split_file_name("k3f9q2-Jana.md"), None);
assert_eq!(split_file_name("k3f9q2-jana--photos.md"), None);
}
#[test]
fn generate_skips_existing() {
let mut existing = BTreeSet::new();
existing.insert(RoadId::new("000000").unwrap());
let mut calls = 0;
let id = generate_with(&existing, |buf| {
calls += 1;
buf.fill(if calls == 1 { 0 } else { 1 });
});
assert_eq!(id.as_str(), "111111");
assert_eq!(calls, 2);
}
}
+170
View File
@@ -0,0 +1,170 @@
//! The ids roads point at, matching the formats of the code that owns them (docs/02_via-core.md, "The ids").
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use std::fmt;
macro_rules! string_id {
($name:ident, $check:path, $what:literal) => {
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize)]
#[serde(transparent)]
pub struct $name(String);
impl $name {
pub fn new(s: &str) -> Option<$name> {
$check(s).then(|| $name(s.to_string()))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl fmt::Debug for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}({})", stringify!($name), self.0)
}
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
$name::new(&s).ok_or_else(|| {
serde::de::Error::custom(format!("`{}` is not {}", clip(&s), $what))
})
}
}
};
}
string_id!(PersonId, is_opaque_id, "a person id");
string_id!(GroupId, is_opaque_id, "a group id");
string_id!(AppId, is_tessera_id, "an app id");
string_id!(Hostname, is_hostname, "a hostname");
string_id!(DeviceKey, is_device_key, "a device key");
/// A person or group id. **No people directory exists in Fundamentum yet**, so this is an opaque newtype:
/// 1–64 of `[A-Za-z0-9_-]`, wide enough for a base64url Tessera root public key.
pub fn is_opaque_id(s: &str) -> bool {
(1..=64).contains(&s.len())
&& s.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}
/// Tessera's id (Fundamentum `crates/tessera/src/id.rs`): 1–32 of `[a-z0-9-]`, not starting or ending with `-`.
pub fn is_tessera_id(s: &str) -> bool {
(1..=32).contains(&s.len())
&& s.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
&& !s.starts_with('-')
&& !s.ends_with('-')
}
/// A Tessera device subkey (Fundamentum `docs/TESSERA.md` §2 and §4): a 32-byte Ed25519 public key in
/// base64url without padding, in its one canonical encoding.
pub fn is_device_key(s: &str) -> bool {
if s.len() != 43 {
return false;
}
match URL_SAFE_NO_PAD.decode(s) {
Ok(bytes) => bytes.len() == 32 && URL_SAFE_NO_PAD.encode(&bytes) == s,
Err(_) => false,
}
}
impl DeviceKey {
/// The key of 32 public-key bytes. Tests use it with made-up bytes: there are no real keys in this crate.
pub fn from_bytes(bytes: &[u8; 32]) -> DeviceKey {
DeviceKey(URL_SAFE_NO_PAD.encode(bytes))
}
/// The first 8 characters, for people to tell keys apart.
pub fn short(&self) -> &str {
&self.0[..8]
}
}
/// Ianitor's hostname rules (`crates/core/src/validate.rs`, `check_hostname`), written again here: lowercase,
/// at most 253 characters, labels of 1–63 `[a-z0-9-]` not starting or ending with `-`, no wildcard, no
/// trailing dot, not an IP address.
pub fn is_hostname(h: &str) -> bool {
if h.is_empty() || h.len() > 253 || h.parse::<std::net::IpAddr>().is_ok() || h.ends_with('.') {
return false;
}
h.split('.').all(|label| {
(1..=63).contains(&label.len())
&& label
.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
&& !label.starts_with('-')
&& !label.ends_with('-')
})
}
/// At most 40 characters of `s`, for messages.
pub(crate) fn clip(s: &str) -> String {
let mut out: String = s.chars().take(40).collect();
if out.len() < s.len() {
out.push('…');
}
out.escape_debug().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn device_keys_are_canonical_43_character_base64url() {
let k = DeviceKey::from_bytes(&[1; 32]);
assert_eq!(k.as_str(), "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE");
assert!(is_device_key(k.as_str()));
// Non-zero trailing bits: decodes to the same bytes, but is not the canonical encoding.
assert!(!is_device_key(
"AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQF"
));
assert!(!is_device_key(
"AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE="
));
assert!(!is_device_key(
"AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ+"
));
}
#[test]
fn hostnames_follow_ianitor() {
assert!(is_hostname("photos.home.arpa"));
assert!(is_hostname("localhost"));
for bad in [
"",
"Photos.home.arpa",
"*.home.arpa",
"photos.home.arpa.",
"-a.b",
"a-.b",
"a..b",
"10.0.0.1",
"a b",
] {
assert!(!is_hostname(bad), "{bad}");
}
assert!(!is_hostname(&format!("{}.a", "x".repeat(64))));
}
#[test]
fn opaque_and_tessera_ids() {
assert!(is_opaque_id("jana"));
assert!(is_opaque_id("AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE"));
assert!(!is_opaque_id("jana novak"));
assert!(!is_opaque_id(&"a".repeat(65)));
assert!(is_tessera_id("steam"));
assert!(!is_tessera_id("-steam"));
assert!(!is_tessera_id("Steam"));
}
}
+30
View File
@@ -0,0 +1,30 @@
//! Via Domi's road model, its validator and the compiler from roads to per-device plans.
//!
//! Pure: the only I/O is [`Store::load_dir`] reading the store; no network, no clock (`now` is a parameter),
//! no randomness (ids take a random source as a parameter). See `docs/02_via-core.md` and `docs/FORMATS.md`.
#![forbid(unsafe_code)]
pub mod compile;
pub mod explain;
pub mod header;
pub mod id;
pub mod ids;
pub mod net;
pub mod plan;
pub mod ports;
pub mod problem;
pub mod road;
pub mod rules;
pub mod snapshot;
pub mod store;
pub use compile::{Compiled, Grant, compile};
pub use explain::explain;
pub use id::RoadId;
pub use ids::{AppId, DeviceKey, GroupId, Hostname, PersonId};
pub use plan::Plan;
pub use problem::{Problem, Severity};
pub use road::{Body, Place, Road, Subject, Verb};
pub use snapshot::{Devices, Directory};
pub use store::Store;
+228
View File
@@ -0,0 +1,228 @@
//! Networks: canonical CIDRs, host networks, overlap, and what `internet` means.
use ipnet::IpNet;
use std::fmt;
use std::net::IpAddr;
use std::str::FromStr;
/// A canonical network (host bits zero), serialised as its text in every format.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Net(IpNet);
impl Net {
/// Parses `a.b.c.d/n` or `x::/n`; `Err(true)` when it parses but has host bits set.
pub fn parse_canonical(s: &str) -> Result<Net, bool> {
let n = IpNet::from_str(s).map_err(|_| false)?;
if n.trunc() != n || n.to_string() != s {
return Err(true);
}
Ok(Net(n))
}
/// The `/32` or `/128` of one address.
pub fn host(addr: IpAddr) -> Net {
Net(IpNet::from(addr))
}
pub fn v4_default() -> Net {
Net(IpNet::from_str("0.0.0.0/0").expect("literal"))
}
pub fn v6_default() -> Net {
Net(IpNet::from_str("::/0").expect("literal"))
}
pub fn inner(&self) -> IpNet {
self.0
}
pub fn prefix_len(&self) -> u8 {
self.0.prefix_len()
}
pub fn contains(&self, other: &Net) -> bool {
self.0.contains(&other.0)
}
pub fn contains_addr(&self, addr: &IpAddr) -> bool {
self.0.contains(addr)
}
pub fn overlaps(&self, other: &Net) -> bool {
self.contains(other) || other.contains(self)
}
/// Whether any part of this network is on the internet: it is not wholly inside one of [`NOT_INTERNET`].
pub fn reaches_internet(&self) -> bool {
!NOT_INTERNET
.iter()
.any(|s| Net::parse_canonical(s).expect("literal").contains(self))
}
/// An IPv6 network that carries IPv4 addresses inside it (mapped, compatible, NAT64, 6to4). Refused
/// everywhere: write the IPv4 network, so the two families are never compared apart (QA R-07).
pub fn embeds_ipv4(&self) -> bool {
matches!(self.0, IpNet::V6(_))
&& EMBEDS_IPV4
.iter()
.any(|s| Net::parse_canonical(s).expect("literal").contains(self))
}
/// Loopback, link-local (cloud metadata lives there), multicast, broadcast and "this network": never a
/// place to reach or route (QA R-08).
pub fn is_special(&self) -> bool {
SPECIAL
.iter()
.any(|s| self.overlaps(&Net::parse_canonical(s).expect("literal")))
}
}
const EMBEDS_IPV4: &[&str] = &[
"::/96",
"::ffff:0.0.0.0/96",
"64:ff9b::/96",
"64:ff9b:1::/48",
"2002::/16",
];
const SPECIAL: &[&str] = &[
"0.0.0.0/8",
"127.0.0.0/8",
"169.254.0.0/16",
"224.0.0.0/4",
"240.0.0.0/4",
"::1/128",
"fe80::/10",
"ff00::/8",
];
/// What `internet` excludes (docs/FORMATS.md, "The plan").
pub const NOT_INTERNET: &[&str] = &[
"0.0.0.0/8",
"10.0.0.0/8",
"100.64.0.0/10",
"127.0.0.0/8",
"169.254.0.0/16",
"172.16.0.0/12",
"192.168.0.0/16",
"::1/128",
"fc00::/7",
"fe80::/10",
];
impl fmt::Display for Net {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl fmt::Debug for Net {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Net({})", self.0)
}
}
impl serde::Serialize for Net {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.collect_str(&self.0)
}
}
impl<'de> serde::Deserialize<'de> for Net {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
Net::parse_canonical(&s)
.map_err(|_| serde::de::Error::custom(format!("`{s}` is not a canonical network")))
}
}
/// A mesh address, serialised as text in every format.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Addr(pub IpAddr);
impl fmt::Display for Addr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl serde::Serialize for Addr {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.collect_str(&self.0)
}
}
impl<'de> serde::Deserialize<'de> for Addr {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
match s.parse::<IpAddr>() {
Ok(a) if a.to_string() == s => Ok(Addr(a)),
_ => Err(serde::de::Error::custom(format!(
"`{s}` is not an IP address in its usual form"
))),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn canonical_networks() {
assert!(Net::parse_canonical("192.168.100.0/24").is_ok());
assert_eq!(Net::parse_canonical("192.168.100.7/24"), Err(true));
assert_eq!(
Net::parse_canonical("fd00:0::/64"),
Err(true),
"not the usual text form"
);
assert!(Net::parse_canonical("fd00::/64").is_ok());
assert_eq!(Net::parse_canonical("192.168.100.0"), Err(false));
assert_eq!(Net::parse_canonical("nonsense"), Err(false));
}
#[test]
fn internet() {
assert!(
Net::parse_canonical("8.8.8.0/24")
.unwrap()
.reaches_internet()
);
assert!(Net::v4_default().reaches_internet());
assert!(
!Net::parse_canonical("192.168.100.0/24")
.unwrap()
.reaches_internet()
);
assert!(
!Net::parse_canonical("100.96.0.0/16")
.unwrap()
.reaches_internet()
);
}
#[test]
fn embedded_ipv4_and_special_ranges() {
let n = |s: &str| Net::parse_canonical(s).unwrap();
assert!(n("::ffff:10.0.0.0/120").embeds_ipv4());
assert!(n("64:ff9b::/96").embeds_ipv4());
assert!(n("2002::/16").embeds_ipv4());
assert!(n("::1/128").embeds_ipv4());
assert!(!n("2000::/3").embeds_ipv4());
assert!(!n("::/0").embeds_ipv4());
assert!(!n("fd00::/64").embeds_ipv4());
for s in [
"127.0.0.0/8",
"169.254.169.254/32",
"224.0.0.0/4",
"255.255.255.255/32",
"fe80::/10",
"ff02::1/128",
"0.0.0.0/1",
] {
assert!(n(s).is_special(), "{s}");
}
assert!(!n("192.168.100.0/24").is_special());
}
}
+164
View File
@@ -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<String>,
pub peers: Vec<Peer>,
pub firewall: Firewall,
pub dns: Vec<Dns>,
pub exit: Option<Exit>,
pub kill_switch: Option<KillSwitch>,
pub direct: Vec<Direct>,
pub custom: Vec<Custom>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Peer {
pub key: DeviceKey,
pub name: String,
pub address: Addr,
/// A classic WireGuard peer: **not post-quantum**.
pub classic: bool,
pub allowed_ips: Vec<Net>,
/// A path hint (a relay or an exit) when every road to this peer names the same one.
pub via: Option<DeviceKey>,
pub roads: Vec<RoadId>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Firewall {
/// Always `deny`: only the rules below let traffic in or through.
pub default: Action,
pub rules: Vec<Rule>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Action {
Deny,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Direction {
/// To this device's own address.
In,
/// Through this device: to a subnet it routes, or to the internet as an exit.
Forward,
}
/// Where a rule lets traffic go.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Dst {
Net(Net),
/// Every address except the private ranges (`net::NOT_INTERNET`).
Internet,
}
impl Serialize for Dst {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match self {
Dst::Net(n) => n.serialize(s),
Dst::Internet => s.serialize_str("internet"),
}
}
}
impl<'de> Deserialize<'de> for Dst {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
if s == "internet" {
return Ok(Dst::Internet);
}
Net::parse_canonical(&s)
.map(Dst::Net)
.map_err(|_| serde::de::Error::custom(format!("`{s}` is not a network or `internet`")))
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Rule {
pub direction: Direction,
pub src: Net,
pub dst: Dst,
pub proto: Proto,
pub ports: Option<[u16; 2]>,
pub roads: Vec<RoadId>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Dns {
pub host: Hostname,
pub address: Addr,
pub roads: Vec<RoadId>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Exit {
pub through: DeviceKey,
pub roads: Vec<RoadId>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct KillSwitch {
/// `None` when kill-switch roads disagree: nothing leaves but the mesh (fails closed).
pub through: Option<DeviceKey>,
pub roads: Vec<RoadId>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Direct {
/// `None`: all traffic to `subnet`; `Some`: only that app's.
pub app: Option<AppId>,
pub subnet: Net,
pub roads: Vec<RoadId>,
}
#[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<Item = (&DeviceKey, &Net)> {
self.peers
.iter()
.flat_map(|p| p.allowed_ips.iter().map(move |n| (&p.key, n)))
}
/// Pretty JSON, two spaces, fields in wire order, a final newline: the same input, the same bytes.
pub fn to_json(&self) -> String {
let mut s = serde_json::to_string_pretty(self).expect("a plan always serialises");
s.push('\n');
s
}
}
+216
View File
@@ -0,0 +1,216 @@
//! Port lists: `tcp/443`, `udp/53`, `tcp/8000-8100`, `tcp`, `udp`, `icmp` (docs/FORMATS.md).
use std::fmt;
#[derive(
Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, serde::Serialize, serde::Deserialize,
)]
#[serde(rename_all = "kebab-case")]
pub enum Proto {
Any,
Tcp,
Udp,
Icmp,
}
/// One entry of a port list. `range` is `None` for the whole protocol.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct PortSpec {
pub proto: Proto,
pub range: Option<(u16, u16)>,
}
impl PortSpec {
pub fn parse(s: &str) -> Result<PortSpec, String> {
let (proto, rest) = match s.split_once('/') {
Some((p, r)) => (p, Some(r)),
None => (s, None),
};
let proto = match proto {
"tcp" => Proto::Tcp,
"udp" => Proto::Udp,
"icmp" => Proto::Icmp,
_ => return Err(format!("`{s}`: the protocol is tcp, udp or icmp")),
};
let Some(rest) = rest else {
return Ok(PortSpec { proto, range: None });
};
if proto == Proto::Icmp {
return Err(format!("`{s}`: icmp has no ports"));
}
let (lo, hi) = match rest.split_once('-') {
Some((a, b)) => (port(a, s)?, port(b, s)?),
None => {
let p = port(rest, s)?;
(p, p)
}
};
if rest.contains('-') && lo >= hi {
return Err(format!(
"`{s}`: a range goes from a lower port to a higher one"
));
}
Ok(PortSpec {
proto,
range: Some((lo, hi)),
})
}
fn covers_range(&self) -> (u16, u16) {
self.range.unwrap_or((1, 65535))
}
}
fn port(t: &str, whole: &str) -> Result<u16, String> {
let ok = !t.is_empty()
&& t.len() <= 5
&& t.bytes().all(|b| b.is_ascii_digit())
&& !t.starts_with('0');
match t.parse::<u16>() {
Ok(p) if ok && p > 0 => Ok(p),
_ => Err(format!(
"`{whole}`: a port is a number from 1 to 65535, without leading zeros"
)),
}
}
impl fmt::Display for PortSpec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let p = match self.proto {
Proto::Any => "any",
Proto::Tcp => "tcp",
Proto::Udp => "udp",
Proto::Icmp => "icmp",
};
match self.range {
None => f.write_str(p),
Some((lo, hi)) if lo == hi => write!(f, "{p}/{lo}"),
Some((lo, hi)) => write!(f, "{p}/{lo}-{hi}"),
}
}
}
/// Whether every spec in `inner` is covered by the union of `outer`.
pub fn is_subset(inner: &[PortSpec], outer: &[PortSpec]) -> bool {
inner.iter().all(|a| {
let mut ranges: Vec<(u32, u32)> = outer
.iter()
.filter(|b| b.proto == a.proto)
.map(|b| {
let (lo, hi) = b.covers_range();
(lo as u32, hi as u32)
})
.collect();
if a.proto == Proto::Icmp {
return !ranges.is_empty();
}
ranges.sort();
let (lo, hi) = a.covers_range();
let (mut need, hi) = (lo as u32, hi as u32);
for (l, h) in ranges {
if l > need {
break;
}
if h >= need {
need = h + 1;
}
if need > hi {
return true;
}
}
need > hi
})
}
/// Whether two port sets share any traffic. `None` means all traffic.
pub fn overlaps(a: Option<&[PortSpec]>, b: Option<&[PortSpec]>) -> bool {
match (a, b) {
(None, _) | (_, None) => true,
(Some(a), Some(b)) => a.iter().any(|x| {
b.iter().any(|y| {
x.proto == y.proto && {
let (xl, xh) = x.covers_range();
let (yl, yh) = y.covers_range();
xl <= yh && yl <= xh
}
})
}),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn specs(s: &[&str]) -> Vec<PortSpec> {
s.iter().map(|x| PortSpec::parse(x).unwrap()).collect()
}
#[test]
fn parse_and_print() {
for s in [
"tcp/443",
"udp/53",
"tcp/8000-8100",
"tcp",
"udp",
"icmp",
"tcp/65535",
] {
assert_eq!(PortSpec::parse(s).unwrap().to_string(), s);
}
for bad in [
"tcp/0",
"tcp/0443",
"tcp/65536",
"tcp/443-443",
"tcp/500-400",
"icmp/8",
"sctp/1",
"tcp/",
"tcp/a",
"TCP/443",
"",
] {
assert!(PortSpec::parse(bad).is_err(), "{bad}");
}
}
#[test]
fn subsets() {
assert!(is_subset(
&specs(&["tcp/443"]),
&specs(&["tcp/443", "tcp/22"])
));
assert!(!is_subset(&specs(&["tcp/80"]), &specs(&["tcp/443"])));
assert!(!is_subset(&specs(&["udp/443"]), &specs(&["tcp/443"])));
assert!(is_subset(
&specs(&["tcp/8000-8100"]),
&specs(&["tcp/8000-8050", "tcp/8051-8100"])
));
assert!(!is_subset(
&specs(&["tcp/8000-8100"]),
&specs(&["tcp/8000-8050", "tcp/8052-8100"])
));
assert!(is_subset(&specs(&["tcp/1-10"]), &specs(&["tcp"])));
assert!(!is_subset(&specs(&["tcp"]), &specs(&["tcp/1-65534"])));
assert!(is_subset(
&specs(&["tcp"]),
&specs(&["tcp/1-100", "tcp/101-65535"])
));
assert!(is_subset(&specs(&["icmp"]), &specs(&["icmp"])));
}
#[test]
fn overlap() {
assert!(overlaps(None, Some(&specs(&["tcp/1"]))));
assert!(overlaps(
Some(&specs(&["tcp/400-500"])),
Some(&specs(&["tcp/443"]))
));
assert!(!overlaps(
Some(&specs(&["tcp/400-500"])),
Some(&specs(&["udp/443"]))
));
}
}
+85
View File
@@ -0,0 +1,85 @@
//! Problems: what `via check` reports (docs/FORMATS.md).
//!
//! One line per problem, as Pensum does it: `<path>[:<line>]: [<field>: ]<message> [<code>]`.
use std::fmt;
/// Whether a problem is an error (the file is wrong) or a valid road that grants nothing right now.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Severity {
Error,
Inactive,
}
/// One validation problem. `path` is store-relative, with `/`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
pub struct Problem {
pub path: String,
pub line: Option<usize>,
pub field: Option<String>,
/// A rule code from [`crate::rules::ALL`].
pub code: &'static str,
pub message: String,
pub severity: Severity,
}
impl Problem {
pub fn error(
path: &str,
field: Option<&str>,
code: &'static str,
message: impl Into<String>,
) -> Self {
debug_assert!(
crate::rules::ALL.contains(&code),
"unlisted rule code {code}"
);
Problem {
path: path.to_string(),
line: None,
field: field.map(String::from),
code,
message: message.into(),
severity: Severity::Error,
}
}
pub fn inactive(
path: &str,
field: Option<&str>,
code: &'static str,
message: impl Into<String>,
) -> Self {
Problem {
severity: Severity::Inactive,
..Problem::error(path, field, code, message)
}
}
/// Sets the 1-based line; 0 means unknown.
pub fn at(mut self, line: usize) -> Self {
self.line = (line > 0).then_some(line);
self
}
pub fn is_error(&self) -> bool {
self.severity == Severity::Error
}
}
impl fmt::Display for Problem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.severity == Severity::Inactive {
f.write_str("inactive: ")?;
}
f.write_str(&self.path)?;
if let Some(line) = self.line {
write!(f, ":{line}")?;
}
if let Some(field) = &self.field {
write!(f, ": {field}")?;
}
write!(f, ": {} [{}]", self.message, self.code)
}
}
+862
View File
@@ -0,0 +1,862 @@
//! Road files: `roads/<id>-<slug>.md`, a strict header and a body (docs/FORMATS.md, "Road files").
use crate::header::{self, Value};
use crate::id::{self, RoadId};
use crate::ids::{AppId, DeviceKey, GroupId, Hostname, PersonId, clip};
use crate::net::Net;
use crate::ports::PortSpec;
use crate::problem::Problem;
use crate::rules as r;
use jiff::Timestamp as Instant;
use std::collections::BTreeMap;
use std::fmt;
/// Largest road file accepted.
pub const MAX_FILE: usize = 256 * 1024;
pub const REQUIRED: [&str; 4] = ["id", "subject", "verb", "created"];
pub const OPTIONAL: [&str; 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> {
Verb::ALL.into_iter().find(|v| v.as_str() == s)
}
fn subject_kinds(self) -> &'static [Kind] {
match self {
Verb::GoesDirect => &[Kind::Person, Kind::Group, Kind::Device, Kind::App],
Verb::Custom => &[Kind::Device],
_ => &[Kind::Person, Kind::Group, Kind::Device],
}
}
fn object_kinds(self) -> &'static [Kind] {
match self {
Verb::CanReach => &[Kind::Device, Kind::Subnet, Kind::Service],
Verb::ExitsThrough | Verb::NeverOnlineWithout => &[Kind::Exit],
Verb::GoesDirect => &[Kind::Subnet],
Verb::Custom => &[],
}
}
/// Whether this verb takes `key` at all.
fn takes(self, key: &str) -> bool {
match key {
"object" => self != Verb::Custom,
"ports" | "via" => self == Verb::CanReach,
"classic" => matches!(self, Verb::CanReach | Verb::ExitsThrough | Verb::Custom),
_ => true,
}
}
}
impl fmt::Display for Verb {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
Person,
Group,
Device,
App,
Subnet,
Service,
Exit,
}
impl Kind {
fn name(self) -> &'static str {
match self {
Kind::Person => "person",
Kind::Group => "group",
Kind::Device => "device",
Kind::App => "app",
Kind::Subnet => "subnet",
Kind::Service => "service",
Kind::Exit => "exit",
}
}
}
/// Who a road is for.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Subject {
Person(PersonId),
Group(GroupId),
Device(DeviceKey),
App(AppId),
}
/// What a road points at.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Place {
Device(DeviceKey),
Subnet(Net),
Service(Hostname),
Exit(DeviceKey),
}
impl fmt::Display for Subject {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Subject::Person(p) => write!(f, "person:{p}"),
Subject::Group(g) => write!(f, "group:{g}"),
Subject::Device(d) => write!(f, "device:{d}"),
Subject::App(a) => write!(f, "app:{a}"),
}
}
}
impl fmt::Display for Place {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Place::Device(d) => write!(f, "device:{d}"),
Place::Subnet(n) => write!(f, "subnet:{n}"),
Place::Service(h) => write!(f, "service:{h}"),
Place::Exit(d) => write!(f, "exit:{d}"),
}
}
}
enum Ref {
S(Subject),
P(Place),
}
impl Ref {
fn kind(&self) -> Kind {
match self {
Ref::S(Subject::Person(_)) => Kind::Person,
Ref::S(Subject::Group(_)) => Kind::Group,
Ref::S(Subject::Device(_)) | Ref::P(Place::Device(_)) => Kind::Device,
Ref::S(Subject::App(_)) => Kind::App,
Ref::P(Place::Subnet(_)) => Kind::Subnet,
Ref::P(Place::Service(_)) => Kind::Service,
Ref::P(Place::Exit(_)) => Kind::Exit,
}
}
}
/// Parses `<kind>:<id>`. The error is a rule code and a message.
fn parse_ref(s: &str) -> Result<Ref, (&'static str, String)> {
let bad = |what: &str| (r::REF_FORMAT, format!("`{}` is not {what}", clip(s)));
let Some((kind, v)) = s.split_once(':') else {
return Err((
r::REF_FORMAT,
format!(
"`{}` is not a reference like `person:<id>` or `device:<key>`",
clip(s)
),
));
};
Ok(match kind {
"person" => Ref::S(Subject::Person(
PersonId::new(v).ok_or_else(|| bad("a person: 1-64 of A-Z a-z 0-9 _ -"))?,
)),
"group" => Ref::S(Subject::Group(
GroupId::new(v).ok_or_else(|| bad("a group: 1-64 of A-Z a-z 0-9 _ -"))?,
)),
"device" => Ref::P(Place::Device(DeviceKey::new(v).ok_or_else(|| {
bad("a device: a Tessera key, 43 characters of base64url")
})?)),
"app" => Ref::S(Subject::App(
AppId::new(v).ok_or_else(|| bad("an app: 1-32 of a-z 0-9 -"))?,
)),
"subnet" => match Net::parse_canonical(v) {
Ok(n) if n.embeds_ipv4() => {
return Err((
r::REF_FORMAT,
format!(
"`{}` embeds IPv4 addresses in IPv6; write the IPv4 subnet",
clip(v)
),
));
}
Ok(n) => Ref::P(Place::Subnet(n)),
Err(true) => {
return Err((
r::SUBNET_NOT_CANONICAL,
format!(
"`{}` has host bits set or an unusual form; write the network itself",
clip(v)
),
));
}
Err(false) => return Err(bad("a subnet like 192.168.100.0/24")),
},
"service" => Ref::P(Place::Service(
Hostname::new(v).ok_or_else(|| bad("a service: a lowercase hostname"))?,
)),
"exit" => Ref::P(Place::Exit(DeviceKey::new(v).ok_or_else(|| {
bad("an exit: a Tessera key, 43 characters of base64url")
})?)),
_ => {
return Err((
r::REF_FORMAT,
format!(
"`{}`: the kind is person, group, device, app, subnet, service or exit",
clip(s)
),
));
}
})
}
/// An RFC 3339 time with an offset, kept as written.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Timestamp {
text: String,
at: Instant,
}
impl Timestamp {
pub fn parse(s: &str) -> Option<Timestamp> {
let b = s.as_bytes();
let shape = b.len() >= 20
&& b[10] == b'T'
&& (s.ends_with('Z') || matches!(b[b.len() - 6], b'+' | b'-'));
let at: Instant = s.parse().ok()?;
shape.then(|| Timestamp {
text: s.to_string(),
at,
})
}
pub fn as_str(&self) -> &str {
&self.text
}
pub fn at(&self) -> Instant {
self.at
}
}
/// What follows the header.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Body {
/// A free-text note, never interpreted.
Note(String),
/// A custom road's raw block, byte for byte, never interpreted.
Raw(String),
}
/// A road whose file parsed and whose fields are well formed. Whether it compiles depends on the snapshots.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Road {
pub path: String,
pub id: RoadId,
pub subject: Subject,
pub verb: Verb,
pub object: Option<Place>,
pub until: Option<Timestamp>,
pub ports: Option<Vec<PortSpec>>,
pub via: Option<DeviceKey>,
pub classic: Option<bool>,
pub created: Timestamp,
pub body: Body,
lines: BTreeMap<String, usize>,
}
impl Road {
/// The file line of `key`, or 0.
pub fn line_of(&self, key: &str) -> usize {
self.lines.get(key).copied().unwrap_or(0)
}
pub fn is_classic(&self) -> bool {
self.classic == Some(true)
}
/// The road as one line: `person:jana can-reach service:photos.home.arpa until …`.
pub fn sentence(&self, name: &dyn Fn(&DeviceKey) -> Option<String>) -> String {
let dev = |k: &DeviceKey| name(k).unwrap_or_else(|| k.short().to_string());
let subject = match &self.subject {
Subject::Device(k) => format!("device:{}", dev(k)),
s => s.to_string(),
};
let mut out = 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<String> = p.iter().map(|p| p.to_string()).collect();
out.push_str(&format!(" ports [{}]", list.join(", ")));
}
if let Some(v) = &self.via {
out.push_str(&format!(" via {}", dev(v)));
}
if self.is_classic() {
out.push_str(" (classic, not post-quantum)");
}
out
}
/// The canonical file text (docs/FORMATS.md, "Canonical form").
pub fn render(&self) -> String {
let mut out = String::from("---\n");
let mut field = |k: &str, v: String| {
out.push_str(k);
out.push_str(": ");
out.push_str(&v);
out.push('\n');
};
let scalar = |s: String| {
if header::is_plain_safe(&s, false) {
s
} else {
header::quote(&s)
}
};
field("id", self.id.to_string());
field("subject", scalar(self.subject.to_string()));
field("verb", self.verb.to_string());
if let Some(o) = &self.object {
field("object", scalar(o.to_string()));
}
if let Some(u) = &self.until {
field("until", scalar(u.as_str().to_string()));
}
if let Some(p) = &self.ports {
let items: Vec<String> = p
.iter()
.map(|p| {
let s = p.to_string();
if header::is_plain_safe(&s, true) {
s
} else {
header::quote(&s)
}
})
.collect();
field("ports", format!("[{}]", items.join(", ")));
}
if let Some(v) = &self.via {
field("via", scalar(format!("device:{v}")));
}
if let Some(c) = self.classic {
field("classic", c.to_string());
}
field("created", scalar(self.created.as_str().to_string()));
out.push_str("---\n");
match &self.body {
Body::Note(n) => out.push_str(n),
Body::Raw(raw) => {
out.push_str("```raw\n");
out.push_str(raw);
out.push_str("```\n");
}
}
out
}
/// Parses one road file. `path` is store-relative (`roads/<name>`); every problem names it.
pub fn parse(path: &str, bytes: &[u8]) -> Result<Road, Vec<Problem>> {
let err = |field: Option<&str>, code, msg: String| Problem::error(path, field, code, msg);
if bytes.len() > MAX_FILE {
return Err(vec![err(
None,
r::FILE_SIZE,
format!("larger than {} KiB", MAX_FILE / 1024),
)]);
}
if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
return Err(vec![err(
None,
r::FILE_ENCODING,
"starts with a byte order mark; save it as UTF-8 without one".into(),
)]);
}
let Ok(text) = std::str::from_utf8(bytes) else {
return Err(vec![err(None, r::FILE_ENCODING, "is not UTF-8".into())]);
};
let mut problems = Vec::new();
let name = path.rsplit('/').next().unwrap_or(path);
let name_id = id::split_file_name(name).map(|(i, _)| i);
if name_id.is_none() {
problems.push(err(
None,
r::FILE_NAME,
format!("the file name must be <id>-<slug>.md with a slug of a-z, 0-9 and -, at most {} characters", id::SLUG_MAX),
));
}
// Split into lines, keeping where each one ends.
let mut lines: Vec<&str> = Vec::new();
let mut ends: Vec<usize> = Vec::new();
let mut start = 0;
for (i, b) in text.bytes().enumerate() {
if b == b'\n' {
lines.push(text[start..i].strip_suffix('\r').unwrap_or(&text[start..i]));
ends.push(i + 1);
start = i + 1;
}
}
if start < text.len() {
lines.push(text[start..].strip_suffix('\r').unwrap_or(&text[start..]));
ends.push(text.len());
}
if lines.first() != Some(&"---") {
problems.push(err(None, r::FILE_HEADER, "the first line must be `---`".into()).at(1));
return Err(problems);
}
let Some(close) = lines
.iter()
.skip(1)
.position(|l| *l == "---")
.map(|p| p + 1)
else {
problems.push(err(
None,
r::FILE_HEADER,
"the header is not closed by a `---` line".into(),
));
return Err(problems);
};
let body_text = &text[ends[close]..];
let fields = match header::parse(&lines[1..close], 2) {
Ok(f) => f,
Err(e) => {
problems
.push(Problem::error(path, e.field.as_deref(), e.code, e.message).at(e.line));
return Err(problems);
}
};
let line_of: BTreeMap<String, usize> =
fields.iter().map(|f| (f.key.clone(), f.line)).collect();
let at = |k: &str| line_of.get(k).copied().unwrap_or(0);
let p = |k: &str, code: &'static str, msg: String| {
Problem::error(path, Some(k), code, msg).at(at(k))
};
let get = |k: &str| {
fields
.iter()
.find(|f| f.key == k)
.map(|f| &f.value)
.filter(|v| **v != Value::Absent)
};
for f in &fields {
if !REQUIRED.contains(&f.key.as_str()) && !OPTIONAL.contains(&f.key.as_str()) {
problems.push(p(&f.key, r::KEY_UNKNOWN, "unknown key".into()));
}
}
for k in REQUIRED {
if get(k).is_none() {
problems.push(
Problem::error(path, Some(k), r::KEY_MISSING, "missing required key").at(at(k)),
);
}
}
let single = |k: &str, problems: &mut Vec<Problem>| -> Option<String> {
match get(k) {
Some(Value::Str(s)) => Some(s.clone()),
Some(Value::List(_)) => {
problems.push(p(
k,
r::KEY_TYPE,
"must be a single value, not a list".into(),
));
None
}
_ => None,
}
};
let id = single("id", &mut problems).and_then(|s| match RoadId::new(&s) {
Some(id) => {
if name_id.is_some_and(|n| n != id.as_str()) {
problems.push(p(
"id",
r::ID_FILE_NAME,
format!("id {id} does not match the file name {name}"),
));
}
Some(id)
}
None => {
problems.push(p(
"id",
r::ID_FORMAT,
format!(
"`{}` is not a road id: 6 characters of 0-9 a-z without i l o u",
clip(&s)
),
));
None
}
});
let verb = single("verb", &mut problems).and_then(|s| {
let v = Verb::parse(&s);
if v.is_none() {
problems.push(p(
"verb",
r::VERB_UNKNOWN,
format!(
"`{}` is not a verb: can-reach, exits-through, goes-direct, never-online-without or custom",
clip(&s)
),
));
}
v
});
let subject = single("subject", &mut problems).and_then(|s| match parse_ref(&s) {
Err((code, m)) => {
problems.push(p("subject", code, m));
None
}
Ok(rf) => {
let kind = rf.kind();
let subject = match rf {
Ref::S(s) => Some(s),
Ref::P(Place::Device(d)) => Some(Subject::Device(d)),
Ref::P(_) => None,
};
let allowed = verb.map_or(
&[Kind::Person, Kind::Group, Kind::Device, Kind::App][..],
|v| v.subject_kinds(),
);
if subject.is_none() || !allowed.contains(&kind) {
problems.push(p(
"subject",
r::SUBJECT_KIND,
kind_message(kind, verb, allowed),
));
None
} else {
subject
}
}
});
if let Some(v) = verb {
for k in OPTIONAL {
if !v.takes(k) && line_of.contains_key(k) {
problems.push(p(k, r::KEY_FORBIDDEN, format!("a {v} road takes no `{k}`")));
}
}
if v != Verb::Custom && get("object").is_none() {
problems.push(
Problem::error(path, Some("object"), r::KEY_MISSING, "missing required key")
.at(at("object")),
);
}
}
let takes = |k: &str| verb.is_none_or(|v| v.takes(k));
let object = if takes("object") {
single("object", &mut problems).and_then(|s| match parse_ref(&s) {
Err((code, m)) => {
problems.push(p("object", code, m));
None
}
Ok(rf) => {
let kind = rf.kind();
let allowed = verb.map_or(
&[Kind::Device, Kind::Subnet, Kind::Service, Kind::Exit][..],
|v| v.object_kinds(),
);
match rf {
Ref::P(place) if allowed.contains(&kind) => Some(place),
_ => {
problems.push(p(
"object",
r::OBJECT_KIND,
kind_message(kind, verb, allowed),
));
None
}
}
}
})
} else {
None
};
let until = single("until", &mut problems).and_then(|s| {
let t = Timestamp::parse(&s);
if t.is_none() {
problems.push(p(
"until",
r::UNTIL_FORMAT,
format!("`{}` is not an RFC 3339 time with an offset", clip(&s)),
));
}
t
});
let created = single("created", &mut problems).and_then(|s| {
let t = Timestamp::parse(&s);
if t.is_none() {
problems.push(p(
"created",
r::CREATED_FORMAT,
format!("`{}` is not an RFC 3339 time with an offset", clip(&s)),
));
}
t
});
let ports = if takes("ports") {
match get("ports") {
Some(Value::Str(_)) => {
problems.push(p(
"ports",
r::KEY_TYPE,
"must be a list, like [tcp/443]".into(),
));
None
}
Some(Value::List(items)) => {
let mut out = Vec::new();
for it in items {
match PortSpec::parse(it) {
Ok(s) => out.push(s),
Err(m) => problems.push(p("ports", r::PORTS_FORMAT, m)),
}
}
if items.is_empty() {
problems.push(p(
"ports",
r::PORTS_FORMAT,
"an empty list grants nothing; leave `ports` out for all traffic"
.into(),
));
}
Some(out)
}
_ => None,
}
} else {
None
};
let via = if takes("via") {
single("via", &mut problems).and_then(|s| {
match s.strip_prefix("device:").and_then(DeviceKey::new) {
Some(k) => Some(k),
None => {
problems.push(p(
"via",
r::VIA_FORMAT,
format!("`{}` is not `device:<key>`", clip(&s)),
));
None
}
}
})
} else {
None
};
let classic = if takes("classic") {
single("classic", &mut problems).and_then(|s| match s.as_str() {
"true" => Some(true),
"false" => Some(false),
_ => {
problems.push(p(
"classic",
r::CLASSIC_FORMAT,
format!("`{}` is not true or false", clip(&s)),
));
None
}
})
} else {
None
};
let body = if verb == Some(Verb::Custom) {
match raw_block(body_text) {
Some(raw) => {
for (i, key) in raw_hooks(raw) {
problems.push(
Problem::error(
path,
None,
r::BODY_RAW_HOOK,
format!("`{key}` runs commands or rewrites routing when wg-quick brings the config up; it is not allowed in a raw block"),
)
.at(close + 3 + i),
);
}
Some(Body::Raw(raw.to_string()))
}
None => {
problems.push(
Problem::error(
path,
None,
r::BODY_RAW_MISSING,
"a custom road's body is one ```raw block: a ```raw line, the raw lines, a ``` line",
)
.at(close + 2),
);
None
}
}
} else {
if body_text
.split('\n')
.any(|l| l.strip_suffix('\r').unwrap_or(l) == "```raw")
{
problems.push(
Problem::error(
path,
None,
r::BODY_RAW_OUTSIDE_CUSTOM,
"a ```raw block belongs only in a custom road",
)
.at(close + 2),
);
}
Some(Body::Note(body_text.to_string()))
};
if !problems.is_empty() {
problems.sort_by_key(|p| p.line);
return Err(problems);
}
match (id, subject, verb, created, body) {
(Some(id), Some(subject), Some(verb), Some(created), Some(body)) => Ok(Road {
path: path.to_string(),
id,
subject,
verb,
object,
until,
ports,
via,
classic,
created,
body,
lines: line_of,
}),
_ => unreachable!("a missing field always leaves a problem"),
}
}
}
fn kind_message(kind: Kind, verb: Option<Verb>, allowed: &[Kind]) -> String {
let names: Vec<&str> = allowed.iter().map(|k| k.name()).collect();
match verb {
Some(v) if names.is_empty() => format!("a {v} road takes no {}", kind.name()),
Some(v) => format!("a {v} road takes {}, not {}", names.join(", "), kind.name()),
None => format!("{} is not allowed here", kind.name()),
}
}
/// wg-quick keys that run shell commands as root or change host routing (wg-quick(8)); QA R-41.
pub const RAW_HOOKS: [&str; 7] = [
"preup",
"postup",
"predown",
"postdown",
"saveconfig",
"table",
"fwmark",
];
/// The (0-based line, key) of every hook key in a raw block, in any case and spacing.
pub fn raw_hooks(raw: &str) -> Vec<(usize, String)> {
raw.split('\n')
.enumerate()
.filter_map(|(i, l)| {
let key = l
.split('=')
.next()?
.trim_matches(|c: char| c.is_whitespace());
(l.contains('=') && RAW_HOOKS.contains(&key.to_ascii_lowercase().as_str()))
.then(|| (i, key.to_string()))
})
.collect()
}
/// The raw bytes of a body that is exactly one ```` ```raw ```` block.
fn raw_block(body: &str) -> Option<&str> {
let rest = body
.strip_prefix("```raw\n")
.or_else(|| body.strip_prefix("```raw\r\n"))?;
let without_end = rest
.strip_suffix("\r\n")
.or_else(|| rest.strip_suffix('\n'))
.unwrap_or(rest);
let raw = without_end.strip_suffix("```")?;
(raw.is_empty() || raw.ends_with('\n')).then_some(raw)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn raw_blocks() {
assert_eq!(
raw_block("```raw\n[Peer]\nA = b\n```\n"),
Some("[Peer]\nA = b\n")
);
assert_eq!(raw_block("```raw\n```"), Some(""));
assert_eq!(raw_block("```raw\r\nx\r\n```\r\n"), Some("x\r\n"));
assert_eq!(
raw_block("```raw\nx\n```\ny\n"),
None,
"text after the block"
);
assert_eq!(
raw_block("```raw\nx```\n"),
None,
"the fence must start a line"
);
assert_eq!(raw_block("note\n"), None);
}
#[test]
fn timestamps() {
assert!(Timestamp::parse("2026-11-29T23:59:59+01:00").is_some());
assert!(Timestamp::parse("2026-11-29T22:59:59Z").is_some());
assert!(Timestamp::parse("2026-11-29 23:59:59+01:00").is_none());
assert!(Timestamp::parse("2026-11-29").is_none());
assert!(Timestamp::parse("2026-02-30T00:00:00Z").is_none());
}
}
+125
View File
@@ -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,
];
+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)
}
}
}
+161
View File
@@ -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<Road>,
pub directory: Option<Directory>,
pub devices: Option<Devices>,
pub problems: Vec<Problem>,
}
impl Store {
/// Builds a store from bytes: `(file name inside roads/, contents)`, and the two snapshots (`None`: missing).
pub fn from_parts(
road_files: &[(String, Vec<u8>)],
directory: Option<&[u8]>,
devices: Option<&[u8]>,
) -> Store {
let mut store = Store::default();
match directory {
None => store.problems.push(Problem::error(
DIRECTORY_FILE,
None,
r::SNAPSHOT_JSON,
"missing",
)),
Some(b) => match Directory::parse(b) {
Ok(d) => 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<u8>)> = road_files.iter().collect();
files.sort_by(|a, b| a.0.cmp(&b.0));
if files.len() > MAX_ROADS {
store.problems.push(Problem::error(
ROADS_DIR,
None,
r::FILE_COUNT,
format!("more than {MAX_ROADS} road files"),
));
return store;
}
let mut by_id: BTreeMap<RoadId, Vec<Road>> = BTreeMap::new();
for (name, bytes) in files {
let path = format!("{ROADS_DIR}/{name}");
match Road::parse(&path, bytes) {
Ok(road) => by_id.entry(road.id.clone()).or_default().push(road),
Err(p) => store.problems.extend(p),
}
}
for (id, roads) in by_id {
if roads.len() == 1 {
store.roads.extend(roads);
continue;
}
let paths: Vec<&str> = roads.iter().map(|r| r.path.as_str()).collect();
for road in &roads {
store.problems.push(
Problem::error(
&road.path,
Some("id"),
r::ID_DUPLICATE,
format!(
"id {id} is used by {}; none of them grants anything",
paths.join(" and ")
),
)
.at(road.line_of("id")),
);
}
}
store
}
/// Reads a store folder. Only the three names are read; anything that is not a regular `.md` file inside
/// `roads/` is a problem and is not read.
pub fn load_dir(root: &Path) -> std::io::Result<Store> {
let directory = read_optional(&root.join(DIRECTORY_FILE))?;
let devices = read_optional(&root.join(DEVICES_FILE))?;
let mut files = Vec::new();
let mut problems = Vec::new();
let roads = root.join(ROADS_DIR);
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<Option<Vec<u8>>> {
match std::fs::read(path) {
Ok(b) => Ok(Some(b)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e),
}
}