Files
via-core/crates/proto/tests/roundtrip.rs
T
mnovak 38a2fea043 [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.
2026-11-25 07:55:38 +01:00

249 lines
7.4 KiB
Rust

//! 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);
}
}