[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,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)
|
||||
}
|
||||
Reference in New Issue
Block a user