[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:
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "via-cli"
|
||||
description = "Via Domi: the via command: check, compile, explain"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "via"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
roads.workspace = true
|
||||
proto.workspace = true
|
||||
jiff.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,248 @@
|
||||
//! `via`: check, compile and explain a road store (docs/02_via-core.md).
|
||||
//!
|
||||
//! ```text
|
||||
//! via [--store DIR] [--now RFC3339] check
|
||||
//! via [--store DIR] [--now RFC3339] compile --device <name|key|device:key> [--format json|cbor]
|
||||
//! via [--store DIR] [--now RFC3339] explain <device> <place>
|
||||
//! ```
|
||||
//!
|
||||
//! Exit codes: 0 fine (and, for explain, allowed), 1 problems found (or denied), 2 usage or I/O error.
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
use jiff::Timestamp as Instant;
|
||||
use roads::{Compiled, DeviceKey, Place, Store, compile, explain};
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
const USAGE: &str = "usage:
|
||||
via [--store DIR] [--now RFC3339] check
|
||||
via [--store DIR] [--now RFC3339] compile --device <name|key> [--format json|cbor]
|
||||
via [--store DIR] [--now RFC3339] explain <device> <place>
|
||||
|
||||
<place> is device:<name|key>, exit:<name|key>, subnet:<cidr> or service:<hostname>.
|
||||
--now defaults to this computer's clock; --store to the current folder.";
|
||||
|
||||
struct Args {
|
||||
store: PathBuf,
|
||||
now: Instant,
|
||||
command: Vec<String>,
|
||||
}
|
||||
|
||||
fn parse_args(raw: Vec<String>) -> Result<Args, String> {
|
||||
let mut store = PathBuf::from(".");
|
||||
let mut now = None;
|
||||
let mut command = Vec::new();
|
||||
let mut it = raw.into_iter();
|
||||
while let Some(a) = it.next() {
|
||||
match a.as_str() {
|
||||
"--store" => store = PathBuf::from(it.next().ok_or("--store needs a folder")?),
|
||||
"--now" => {
|
||||
let v = it.next().ok_or("--now needs a time")?;
|
||||
let t = roads::road::Timestamp::parse(&v).ok_or(format!(
|
||||
"--now: `{v}` is not an RFC 3339 time with an offset"
|
||||
))?;
|
||||
now = Some(t.at());
|
||||
}
|
||||
"-h" | "--help" => return Err(String::new()),
|
||||
_ => command.push(a),
|
||||
}
|
||||
}
|
||||
let now = match now {
|
||||
Some(n) => n,
|
||||
None => {
|
||||
let secs = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_err(|_| "this computer's clock is before 1970; pass --now")?
|
||||
.as_secs();
|
||||
Instant::from_second(secs as i64)
|
||||
.map_err(|_| "this computer's clock is out of range; pass --now")?
|
||||
}
|
||||
};
|
||||
Ok(Args {
|
||||
store,
|
||||
now,
|
||||
command,
|
||||
})
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args = match parse_args(std::env::args().skip(1).collect()) {
|
||||
Ok(a) => a,
|
||||
Err(m) => {
|
||||
if !m.is_empty() {
|
||||
eprintln!("via: {m}");
|
||||
}
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
match run(&args) {
|
||||
Ok(code) => ExitCode::from(code),
|
||||
Err(m) => {
|
||||
eprintln!("via: {m}");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run(args: &Args) -> Result<u8, String> {
|
||||
let store = Store::load_dir(&args.store)
|
||||
.map_err(|e| format!("cannot read the store {}: {e}", args.store.display()))?;
|
||||
let compiled = compile(&store, args.now);
|
||||
let cmd: Vec<&str> = args.command.iter().map(String::as_str).collect();
|
||||
match cmd.as_slice() {
|
||||
["check"] => Ok(check(&store, &compiled)),
|
||||
["compile", rest @ ..] => compile_cmd(&store, &compiled, rest),
|
||||
["explain", device, place] => explain_cmd(&store, &compiled, device, place),
|
||||
_ => Err(format!("unknown command `{}`\n{USAGE}", cmd.join(" "))),
|
||||
}
|
||||
}
|
||||
|
||||
fn check(store: &Store, c: &Compiled) -> u8 {
|
||||
for p in &c.problems {
|
||||
println!("{p}");
|
||||
}
|
||||
let errors = c.errors().count();
|
||||
let inactive = c.problems.len() - errors;
|
||||
let bad_files: std::collections::BTreeSet<&str> = c
|
||||
.errors()
|
||||
.filter(|p| p.path.starts_with("roads/"))
|
||||
.map(|p| p.path.as_str())
|
||||
.collect();
|
||||
let unparsed = bad_files
|
||||
.iter()
|
||||
.filter(|p| !store.roads.iter().any(|r| r.path == **p))
|
||||
.count();
|
||||
println!(
|
||||
"{} road files, {} with errors; {errors} errors and {inactive} inactive in all",
|
||||
store.roads.len() + unparsed,
|
||||
bad_files.len(),
|
||||
);
|
||||
if !c.has_plans() {
|
||||
println!("no plans: the snapshots have errors, so nothing compiles");
|
||||
}
|
||||
if errors > 0 { 1 } else { 0 }
|
||||
}
|
||||
|
||||
fn find_device(store: &Store, s: &str) -> Result<DeviceKey, String> {
|
||||
let devs = store
|
||||
.devices
|
||||
.as_ref()
|
||||
.ok_or("devices.json has errors; run `via check`")?;
|
||||
let s = s.strip_prefix("device:").unwrap_or(s);
|
||||
if let Some(k) = DeviceKey::new(s).filter(|k| devs.devices.contains_key(k)) {
|
||||
return Ok(k);
|
||||
}
|
||||
devs.by_name(s)
|
||||
.map(|d| d.key.clone())
|
||||
.ok_or(format!("no device `{s}` in devices.json"))
|
||||
}
|
||||
|
||||
fn compile_cmd(store: &Store, c: &Compiled, rest: &[&str]) -> Result<u8, String> {
|
||||
let mut device = None;
|
||||
let mut format = "json";
|
||||
let mut it = rest.iter();
|
||||
while let Some(a) = it.next() {
|
||||
match *a {
|
||||
"--device" => device = Some(*it.next().ok_or("--device needs a device")?),
|
||||
"--format" => format = it.next().ok_or("--format needs json or cbor")?,
|
||||
other => return Err(format!("compile: unexpected `{other}`")),
|
||||
}
|
||||
}
|
||||
let device = device.ok_or("compile needs --device <name|key>")?;
|
||||
if !c.has_plans() {
|
||||
for p in c.errors() {
|
||||
eprintln!("{p}");
|
||||
}
|
||||
eprintln!("via: no plans: the snapshots have errors, so nothing compiles");
|
||||
return Ok(1);
|
||||
}
|
||||
let key = find_device(store, device)?;
|
||||
let plan = &c.plans[&key];
|
||||
let errors = c.errors().filter(|p| p.path.starts_with("roads/")).count();
|
||||
if errors > 0 {
|
||||
eprintln!("via: {errors} road problems: those roads grant nothing (see `via check`)");
|
||||
}
|
||||
let mut out = std::io::stdout().lock();
|
||||
match format {
|
||||
"json" => out.write_all(plan.to_json().as_bytes()),
|
||||
"cbor" => out.write_all(&proto::Envelope::plan(plan.clone()).encode()),
|
||||
f => return Err(format!("--format `{f}`: json or cbor")),
|
||||
}
|
||||
.map_err(|e| format!("cannot write the plan: {e}"))?;
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
fn parse_place(store: &Store, s: &str) -> Result<Place, String> {
|
||||
let (kind, v) = s.split_once(':').ok_or(format!(
|
||||
"`{s}` is not a place like service:<host> or device:<name>"
|
||||
))?;
|
||||
match kind {
|
||||
"device" => Ok(Place::Device(find_device(store, v)?)),
|
||||
"exit" => Ok(Place::Exit(find_device(store, v)?)),
|
||||
"subnet" => roads::net::Net::parse_canonical(v)
|
||||
.map(Place::Subnet)
|
||||
.map_err(|_| format!("`{v}` is not a canonical subnet")),
|
||||
"service" => roads::Hostname::new(v)
|
||||
.map(Place::Service)
|
||||
.ok_or(format!("`{v}` is not a hostname")),
|
||||
_ => Err(format!(
|
||||
"`{kind}`: a place is device:, exit:, subnet: or service:"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn explain_cmd(store: &Store, c: &Compiled, device: &str, place: &str) -> Result<u8, String> {
|
||||
if !c.has_plans() {
|
||||
eprintln!("via: no plans: the snapshots have errors, so nothing compiles");
|
||||
return Ok(1);
|
||||
}
|
||||
let devs = store.devices.as_ref().expect("plans exist");
|
||||
let key = find_device(store, device)?;
|
||||
let target = parse_place(store, place)?;
|
||||
let name = |k: &DeviceKey| devs.devices.get(k).map(|d| d.name.clone());
|
||||
let who = name(&key).unwrap_or_default();
|
||||
let roads = explain(c, devs, &key, &target);
|
||||
if roads.is_empty() {
|
||||
println!("{who} cannot reach {place}: no road allows it.");
|
||||
let mentioning: Vec<&roads::Road> = store
|
||||
.roads
|
||||
.iter()
|
||||
.filter(|r| r.object.as_ref() == Some(&target))
|
||||
.collect();
|
||||
if !mentioning.is_empty() {
|
||||
println!("Roads about {place} that grant {who} nothing:");
|
||||
for r in mentioning {
|
||||
let why: Vec<String> = c
|
||||
.problems
|
||||
.iter()
|
||||
.filter(|p| p.path == r.path)
|
||||
.map(|p| format!("{} [{}]", p.message, p.code))
|
||||
.collect();
|
||||
let why = if why.is_empty() {
|
||||
format!("{who} is not its subject")
|
||||
} else {
|
||||
why.join("; ")
|
||||
};
|
||||
println!(" {} {} ({why})", r.id, r.sentence(&name));
|
||||
}
|
||||
}
|
||||
return Ok(1);
|
||||
}
|
||||
println!(
|
||||
"{who} can reach {place} because of {} road{}:",
|
||||
roads.len(),
|
||||
if roads.len() == 1 { "" } else { "s" }
|
||||
);
|
||||
for id in &roads {
|
||||
let r = store
|
||||
.roads
|
||||
.iter()
|
||||
.find(|r| &r.id == id)
|
||||
.expect("a granting road");
|
||||
println!(" {} {} {}", r.id, r.sentence(&name), r.path);
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//! The `via` binary on the fixture store: check, compile, explain, exit codes, and byte-identical output
|
||||
//! across separate processes (QA R-52).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Output};
|
||||
|
||||
const NOW: &str = "2026-11-25T12:00:00+01:00";
|
||||
|
||||
fn home() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../roads/tests/fixtures/home")
|
||||
}
|
||||
|
||||
fn via(store: &std::path::Path, args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_via"))
|
||||
.arg("--store")
|
||||
.arg(store)
|
||||
.args(["--now", NOW])
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn text(o: &Output) -> String {
|
||||
String::from_utf8_lossy(&o.stdout).into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_passes_on_the_home_store_and_reports_the_inactive_roads() {
|
||||
let o = via(&home(), &["check"]);
|
||||
assert_eq!(o.status.code(), Some(0), "{}", text(&o));
|
||||
let out = text(&o);
|
||||
assert!(out.contains("inactive: roads/m6v0hp-petr-git-expired.md:6: until: expired at 2026-11-01T00:00:00+01:00 [road.expired]"), "{out}");
|
||||
assert!(out.contains("10 road files, 0 with errors"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_fails_on_a_bad_road_and_names_file_and_field() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
copy_store(tmp.path());
|
||||
std::fs::write(
|
||||
tmp.path().join("roads/a00005-untill.md"),
|
||||
std::fs::read(home().join("../invalid/roads/a00005-untill.md")).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let o = via(tmp.path(), &["check"]);
|
||||
assert_eq!(o.status.code(), Some(1));
|
||||
assert!(
|
||||
text(&o).contains("roads/a00005-untill.md:6: untill: unknown key [key.unknown]"),
|
||||
"{}",
|
||||
text(&o)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compile_prints_the_golden_plan_and_the_same_bytes_in_every_process() {
|
||||
let want = std::fs::read_to_string(home().join("expected/jana-phone.json")).unwrap();
|
||||
let first = via(&home(), &["compile", "--device", "jana-phone"]);
|
||||
assert_eq!(first.status.code(), Some(0));
|
||||
assert_eq!(text(&first), want);
|
||||
for _ in 0..4 {
|
||||
assert_eq!(
|
||||
via(&home(), &["compile", "--device", "jana-phone"]).stdout,
|
||||
first.stdout
|
||||
);
|
||||
}
|
||||
let by_key = via(
|
||||
&home(),
|
||||
&[
|
||||
"compile",
|
||||
"--device",
|
||||
"device:AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM",
|
||||
],
|
||||
);
|
||||
assert_eq!(by_key.stdout, first.stdout);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compile_cbor_is_a_valid_plan_message() {
|
||||
let o = via(
|
||||
&home(),
|
||||
&["compile", "--device", "router", "--format", "cbor"],
|
||||
);
|
||||
assert_eq!(o.status.code(), Some(0));
|
||||
let env = proto::Envelope::decode(&o.stdout).unwrap();
|
||||
let proto::Body::Plan { plan, .. } = env.body else {
|
||||
panic!("not a plan message")
|
||||
};
|
||||
assert_eq!(plan.name, "router");
|
||||
assert!(plan.classic);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explain_allowed_and_denied() {
|
||||
let o = via(
|
||||
&home(),
|
||||
&["explain", "jana-phone", "service:photos.home.arpa"],
|
||||
);
|
||||
assert_eq!(o.status.code(), Some(0));
|
||||
let out = text(&o);
|
||||
assert!(
|
||||
out.starts_with("jana-phone can reach service:photos.home.arpa because of 2 roads:"),
|
||||
"{out}"
|
||||
);
|
||||
assert!(out.contains("7tq0mz") && out.contains("k3f9q2"));
|
||||
|
||||
let o = via(&home(), &["explain", "petr-phone", "service:git.home.arpa"]);
|
||||
assert_eq!(o.status.code(), Some(1));
|
||||
let out = text(&o);
|
||||
assert!(
|
||||
out.starts_with("petr-phone cannot reach service:git.home.arpa: no road allows it."),
|
||||
"{out}"
|
||||
);
|
||||
assert!(
|
||||
out.contains("m6v0hp") && out.contains("[road.expired]"),
|
||||
"the expired road is shown as granting nothing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_and_unknown_devices_exit_2() {
|
||||
assert_eq!(via(&home(), &["frobnicate"]).status.code(), Some(2));
|
||||
assert_eq!(
|
||||
via(&home(), &["compile", "--device", "nobody"])
|
||||
.status
|
||||
.code(),
|
||||
Some(2)
|
||||
);
|
||||
assert_eq!(
|
||||
via(&home(), &["explain", "jana-phone", "photos"])
|
||||
.status
|
||||
.code(),
|
||||
Some(2)
|
||||
);
|
||||
let o = Command::new(env!("CARGO_BIN_EXE_via"))
|
||||
.args(["--now", "tomorrow", "check"])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(o.status.code(), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_snapshot_compiles_nothing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
copy_store(tmp.path());
|
||||
std::fs::write(
|
||||
tmp.path().join("devices.json"),
|
||||
"{\"format\": 1, \"devices\": [], \"extra\": 1}",
|
||||
)
|
||||
.unwrap();
|
||||
let o = via(tmp.path(), &["compile", "--device", "jana-phone"]);
|
||||
assert_eq!(o.status.code(), Some(1));
|
||||
assert!(o.stdout.is_empty(), "no plan is printed");
|
||||
assert!(String::from_utf8_lossy(&o.stderr).contains("nothing compiles"));
|
||||
}
|
||||
|
||||
fn copy_store(to: &std::path::Path) {
|
||||
std::fs::create_dir_all(to.join("roads")).unwrap();
|
||||
for f in ["directory.json", "devices.json"] {
|
||||
std::fs::copy(home().join(f), to.join(f)).unwrap();
|
||||
}
|
||||
for e in std::fs::read_dir(home().join("roads")).unwrap() {
|
||||
let e = e.unwrap();
|
||||
std::fs::copy(e.path(), to.join("roads").join(e.file_name())).unwrap();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user