[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,21 @@
|
||||
[package]
|
||||
name = "proto"
|
||||
description = "Via Domi: the control-plane messages, CBOR, versioned"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
roads.workspace = true
|
||||
serde.workspace = true
|
||||
ciborium.workspace = true
|
||||
sha2.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
jiff.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,208 @@
|
||||
//! Via Domi's control-plane messages: CBOR (RFC 8949), versioned (docs/FORMATS.md, "The control protocol").
|
||||
//!
|
||||
//! Decoding reads the version first and refuses anything else before the body is looked at; then it refuses
|
||||
//! unknown fields, missing fields, trailing bytes and messages over 1 MiB. Encoding is deterministic.
|
||||
//! Version 1 carries no signatures: Day 3 adds them with the device's Tessera key, as version 2.
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
use roads::{DeviceKey, Plan};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest as _, Sha256};
|
||||
use std::fmt;
|
||||
|
||||
pub const VERSION: u16 = 1;
|
||||
pub const MAX_MESSAGE: usize = 1024 * 1024;
|
||||
/// Deepest CBOR nesting decoded; a plan is about 6 levels deep.
|
||||
pub const MAX_DEPTH: usize = 32;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Envelope {
|
||||
pub v: u16,
|
||||
pub body: Body,
|
||||
}
|
||||
|
||||
// A message lives for one send or receive; boxing the plan would buy nothing.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
|
||||
pub enum Body {
|
||||
/// A device asks for its plan; `have` is the digest it already holds.
|
||||
PlanRequest {
|
||||
device: DeviceKey,
|
||||
have: Option<Digest>,
|
||||
},
|
||||
/// The plan and the digest of its CBOR encoding.
|
||||
Plan {
|
||||
digest: Digest,
|
||||
plan: Plan,
|
||||
},
|
||||
/// The device applied the plan with this digest.
|
||||
PlanAck {
|
||||
device: DeviceKey,
|
||||
digest: Digest,
|
||||
},
|
||||
Refused {
|
||||
code: RefusalCode,
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum RefusalCode {
|
||||
UnknownDevice,
|
||||
BadRequest,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
/// SHA-256, as 64 lowercase hex characters.
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
pub struct Digest([u8; 32]);
|
||||
|
||||
impl Digest {
|
||||
pub fn of(bytes: &[u8]) -> Digest {
|
||||
Digest(Sha256::digest(bytes).into())
|
||||
}
|
||||
|
||||
pub fn to_hex(&self) -> String {
|
||||
self.0.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
pub fn from_hex(s: &str) -> Option<Digest> {
|
||||
if s.len() != 64
|
||||
|| !s
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut out = [0u8; 32];
|
||||
for (i, chunk) in s.as_bytes().chunks(2).enumerate() {
|
||||
out[i] = u8::from_str_radix(std::str::from_utf8(chunk).ok()?, 16).ok()?;
|
||||
}
|
||||
Some(Digest(out))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Digest {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "Digest({})", self.to_hex())
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for Digest {
|
||||
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&self.to_hex())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Digest {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let s = String::deserialize(d)?;
|
||||
Digest::from_hex(&s)
|
||||
.ok_or_else(|| serde::de::Error::custom("a digest is 64 lowercase hex characters"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
TooLarge(usize),
|
||||
/// Not one well-formed CBOR item, or nested deeper than [`MAX_DEPTH`].
|
||||
Malformed(String),
|
||||
TrailingBytes(usize),
|
||||
/// No `v`, or `v` is not an unsigned integer.
|
||||
NoVersion,
|
||||
UnsupportedVersion(u64),
|
||||
/// The body does not match version 1: an unknown or missing field, a bad key or digest.
|
||||
Invalid(String),
|
||||
/// A `plan` whose digest is not the digest of its plan.
|
||||
DigestMismatch,
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Error::TooLarge(n) => write!(f, "a message of {n} bytes is larger than {MAX_MESSAGE}"),
|
||||
Error::Malformed(m) => write!(f, "not one CBOR item: {m}"),
|
||||
Error::TrailingBytes(n) => write!(f, "{n} bytes after the message"),
|
||||
Error::NoVersion => f.write_str("no protocol version"),
|
||||
Error::UnsupportedVersion(v) => write!(
|
||||
f,
|
||||
"protocol version {v} is not supported (this build speaks {VERSION})"
|
||||
),
|
||||
Error::Invalid(m) => write!(f, "not a version {VERSION} message: {m}"),
|
||||
Error::DigestMismatch => f.write_str("the plan's digest does not match the plan"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
fn to_cbor<T: Serialize>(value: &T) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
ciborium::into_writer(value, &mut out).expect("writing CBOR to a Vec cannot fail");
|
||||
out
|
||||
}
|
||||
|
||||
/// The CBOR encoding of a plan, which its digest covers.
|
||||
pub fn plan_cbor(plan: &Plan) -> Vec<u8> {
|
||||
to_cbor(plan)
|
||||
}
|
||||
|
||||
pub fn plan_digest(plan: &Plan) -> Digest {
|
||||
Digest::of(&plan_cbor(plan))
|
||||
}
|
||||
|
||||
impl Envelope {
|
||||
pub fn new(body: Body) -> Envelope {
|
||||
Envelope { v: VERSION, body }
|
||||
}
|
||||
|
||||
/// A `plan` message, its digest computed here.
|
||||
pub fn plan(plan: Plan) -> Envelope {
|
||||
Envelope::new(Body::Plan {
|
||||
digest: plan_digest(&plan),
|
||||
plan,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn encode(&self) -> Vec<u8> {
|
||||
to_cbor(self)
|
||||
}
|
||||
|
||||
pub fn decode(bytes: &[u8]) -> Result<Envelope, Error> {
|
||||
if bytes.len() > MAX_MESSAGE {
|
||||
return Err(Error::TooLarge(bytes.len()));
|
||||
}
|
||||
let mut reader = bytes;
|
||||
let value: ciborium::Value =
|
||||
ciborium::de::from_reader_with_recursion_limit(&mut reader, MAX_DEPTH)
|
||||
.map_err(|e| Error::Malformed(e.to_string()))?;
|
||||
if !reader.is_empty() {
|
||||
return Err(Error::TrailingBytes(reader.len()));
|
||||
}
|
||||
let ciborium::Value::Map(entries) = &value else {
|
||||
return Err(Error::NoVersion);
|
||||
};
|
||||
let v = entries
|
||||
.iter()
|
||||
.find(|(k, _)| k.as_text() == Some("v"))
|
||||
.and_then(|(_, v)| v.as_integer())
|
||||
.ok_or(Error::NoVersion)?;
|
||||
let v = u64::try_from(v).map_err(|_| Error::NoVersion)?;
|
||||
if v != VERSION as u64 {
|
||||
return Err(Error::UnsupportedVersion(v));
|
||||
}
|
||||
let env: Envelope = value
|
||||
.deserialized()
|
||||
.map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
if let Body::Plan { digest, plan } = &env.body
|
||||
&& plan_digest(plan) != *digest
|
||||
{
|
||||
return Err(Error::DigestMismatch);
|
||||
}
|
||||
Ok(env)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
da086f1cc965aee30351547c6ac466939c627e2f915d5c67314a73357f38f68a
|
||||
@@ -0,0 +1,248 @@
|
||||
//! The control protocol: plans survive CBOR byte for byte (custom raw blocks and the classic flag included,
|
||||
//! QA R-44), encoding is deterministic, and decoding refuses what version 1 does not say.
|
||||
|
||||
use proto::{Body, Digest, Envelope, Error, MAX_MESSAGE, RefusalCode, plan_cbor};
|
||||
use roads::{DeviceKey, Plan, Store, compile};
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn plans() -> Vec<Plan> {
|
||||
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../roads/tests/fixtures/home");
|
||||
let store = Store::load_dir(&dir).unwrap();
|
||||
let now: jiff::Timestamp = "2026-11-25T12:00:00+01:00".parse().unwrap();
|
||||
compile(&store, now).plans.into_values().collect()
|
||||
}
|
||||
|
||||
fn router() -> Plan {
|
||||
plans().into_iter().find(|p| p.name == "router").unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_plan_round_trips_and_encodes_the_same_twice() {
|
||||
let all = plans();
|
||||
assert_eq!(all.len(), 7);
|
||||
for plan in all {
|
||||
let env = Envelope::plan(plan.clone());
|
||||
let a = env.encode();
|
||||
assert_eq!(
|
||||
a,
|
||||
Envelope::plan(plan.clone()).encode(),
|
||||
"{}: two encodings differ",
|
||||
plan.name
|
||||
);
|
||||
let back = Envelope::decode(&a).unwrap();
|
||||
assert_eq!(back, env);
|
||||
assert_eq!(
|
||||
back.encode(),
|
||||
a,
|
||||
"{}: decode → encode changed bytes",
|
||||
plan.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_custom_block_and_the_classic_flag_survive_cbor() {
|
||||
let plan = router();
|
||||
assert!(plan.classic);
|
||||
assert_eq!(plan.custom.len(), 1);
|
||||
let raw = plan.custom[0].raw.clone();
|
||||
assert!(raw.contains("MTU = 1380 \n"), "trailing spaces kept");
|
||||
let Body::Plan { plan: back, .. } = Envelope::decode(&Envelope::plan(plan.clone()).encode())
|
||||
.unwrap()
|
||||
.body
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(back.custom[0].raw, raw);
|
||||
assert!(back.classic && back.custom[0].classic);
|
||||
let server = plans()
|
||||
.into_iter()
|
||||
.find(|p| p.name == "home-server")
|
||||
.unwrap();
|
||||
let Body::Plan { plan: back, .. } = Envelope::decode(&Envelope::plan(server).encode())
|
||||
.unwrap()
|
||||
.body
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
assert!(
|
||||
back.peers
|
||||
.iter()
|
||||
.find(|p| p.name == "router")
|
||||
.unwrap()
|
||||
.classic,
|
||||
"the router peer lost its classic mark"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_plan_digest_is_pinned() {
|
||||
// A change in the CBOR library or the plan's field order shows here first. Update only on purpose, with a
|
||||
// protocol version change if it alters what is on the wire.
|
||||
let plan = plans()
|
||||
.into_iter()
|
||||
.find(|p| p.name == "jana-phone")
|
||||
.unwrap();
|
||||
let d = Digest::of(&plan_cbor(&plan)).to_hex();
|
||||
assert_eq!(
|
||||
d,
|
||||
include_str!("jana-phone.digest").trim(),
|
||||
"jana-phone's plan encodes differently"
|
||||
);
|
||||
}
|
||||
|
||||
fn cbor(v: &ciborium::Value) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
ciborium::into_writer(v, &mut out).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
fn value_of(env: &Envelope) -> ciborium::Value {
|
||||
ciborium::de::from_reader(&env.encode()[..]).unwrap()
|
||||
}
|
||||
|
||||
fn set(v: &mut ciborium::Value, key: &str, to: ciborium::Value) {
|
||||
let ciborium::Value::Map(m) = v else { panic!() };
|
||||
match m.iter_mut().find(|(k, _)| k.as_text() == Some(key)) {
|
||||
Some(e) => e.1 = to,
|
||||
None => m.push((ciborium::Value::Text(key.into()), to)),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoding_refuses_what_version_1_does_not_say() {
|
||||
let ack = Envelope::new(Body::PlanAck {
|
||||
device: DeviceKey::from_bytes(&[3; 32]),
|
||||
digest: Digest::of(b"x"),
|
||||
});
|
||||
assert_eq!(Envelope::decode(&ack.encode()).unwrap(), ack);
|
||||
|
||||
// Another version is refused before the body is read, even when the body is nonsense.
|
||||
let mut v = value_of(&ack);
|
||||
set(&mut v, "v", ciborium::Value::Integer(2.into()));
|
||||
set(&mut v, "body", ciborium::Value::Text("anything".into()));
|
||||
assert_eq!(
|
||||
Envelope::decode(&cbor(&v)),
|
||||
Err(Error::UnsupportedVersion(2))
|
||||
);
|
||||
|
||||
// No version, or not a map at all.
|
||||
let ciborium::Value::Map(m) = value_of(&ack) else {
|
||||
panic!()
|
||||
};
|
||||
let no_v = ciborium::Value::Map(
|
||||
m.into_iter()
|
||||
.filter(|(k, _)| k.as_text() != Some("v"))
|
||||
.collect(),
|
||||
);
|
||||
assert_eq!(Envelope::decode(&cbor(&no_v)), Err(Error::NoVersion));
|
||||
assert_eq!(
|
||||
Envelope::decode(&cbor(&ciborium::Value::Integer(1.into()))),
|
||||
Err(Error::NoVersion)
|
||||
);
|
||||
|
||||
// An unknown field at the top and deep inside a plan.
|
||||
let mut v = value_of(&ack);
|
||||
set(&mut v, "signature", ciborium::Value::Bytes(vec![0; 64]));
|
||||
assert!(matches!(
|
||||
Envelope::decode(&cbor(&v)),
|
||||
Err(Error::Invalid(_))
|
||||
));
|
||||
let mut v = value_of(&Envelope::plan(router()));
|
||||
if let ciborium::Value::Map(m) = &mut v {
|
||||
let body = &mut m
|
||||
.iter_mut()
|
||||
.find(|(k, _)| k.as_text() == Some("body"))
|
||||
.unwrap()
|
||||
.1;
|
||||
let ciborium::Value::Map(b) = body else {
|
||||
panic!()
|
||||
};
|
||||
let ciborium::Value::Map(inner) = &mut b[0].1 else {
|
||||
panic!()
|
||||
};
|
||||
let plan = &mut inner
|
||||
.iter_mut()
|
||||
.find(|(k, _)| k.as_text() == Some("plan"))
|
||||
.unwrap()
|
||||
.1;
|
||||
set(plan, "allowed_everything", ciborium::Value::Bool(true));
|
||||
}
|
||||
assert!(matches!(
|
||||
Envelope::decode(&cbor(&v)),
|
||||
Err(Error::Invalid(_))
|
||||
));
|
||||
|
||||
// A malformed key, trailing bytes, garbage, oversize, deep nesting.
|
||||
let mut v = value_of(&ack);
|
||||
if let ciborium::Value::Map(m) = &mut v {
|
||||
let body = &mut m
|
||||
.iter_mut()
|
||||
.find(|(k, _)| k.as_text() == Some("body"))
|
||||
.unwrap()
|
||||
.1;
|
||||
let ciborium::Value::Map(b) = body else {
|
||||
panic!()
|
||||
};
|
||||
set(
|
||||
&mut b[0].1,
|
||||
"device",
|
||||
ciborium::Value::Text("AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQF".into()),
|
||||
);
|
||||
}
|
||||
assert!(matches!(
|
||||
Envelope::decode(&cbor(&v)),
|
||||
Err(Error::Invalid(_))
|
||||
));
|
||||
let mut bytes = ack.encode();
|
||||
bytes.push(0);
|
||||
assert_eq!(Envelope::decode(&bytes), Err(Error::TrailingBytes(1)));
|
||||
assert!(matches!(
|
||||
Envelope::decode(&[0xff, 0x00, 0x13]),
|
||||
Err(Error::Malformed(_))
|
||||
));
|
||||
assert!(matches!(Envelope::decode(&[]), Err(Error::Malformed(_))));
|
||||
assert_eq!(
|
||||
Envelope::decode(&vec![0u8; MAX_MESSAGE + 1]),
|
||||
Err(Error::TooLarge(MAX_MESSAGE + 1))
|
||||
);
|
||||
let deep = [vec![0x81u8; 10_000], vec![0x01]].concat();
|
||||
assert!(
|
||||
matches!(Envelope::decode(&deep), Err(Error::Malformed(_))),
|
||||
"deep nesting must be refused, not overflow"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plan_whose_digest_does_not_match_is_refused() {
|
||||
let plan = router();
|
||||
let wrong = Envelope::new(Body::Plan {
|
||||
digest: Digest::of(b"another plan"),
|
||||
plan,
|
||||
});
|
||||
assert_eq!(
|
||||
Envelope::decode(&wrong.encode()),
|
||||
Err(Error::DigestMismatch)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refusals_and_requests_round_trip() {
|
||||
for body in [
|
||||
Body::PlanRequest {
|
||||
device: DeviceKey::from_bytes(&[1; 32]),
|
||||
have: None,
|
||||
},
|
||||
Body::PlanRequest {
|
||||
device: DeviceKey::from_bytes(&[1; 32]),
|
||||
have: Some(Digest::of(b"old")),
|
||||
},
|
||||
Body::Refused {
|
||||
code: RefusalCode::UnknownDevice,
|
||||
message: "no such device".into(),
|
||||
},
|
||||
] {
|
||||
let env = Envelope::new(body);
|
||||
assert_eq!(Envelope::decode(&env.encode()).unwrap(), env);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user