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