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