[protocol] F20: ids, tokens and bodies with one wire spelling each; parsers hammered by property tests

This commit is contained in:
2026-11-11 21:11:30 +01:00
parent a4404428ea
commit 51158216ca
4 changed files with 1541 additions and 2 deletions
Generated
+1019
View File
File diff suppressed because it is too large Load Diff
+7
View File
@@ -7,6 +7,13 @@ edition.workspace = true
publish.workspace = true
[dependencies]
base64 = "0.22"
serde = { version = "1", features = ["derive"] }
sha2 = "0.10"
[dev-dependencies]
proptest = "1.11"
serde_json = "1"
[lints]
workspace = true
+329 -2
View File
@@ -1,2 +1,329 @@
//! Wire types for the Tabellarius protocol (`docs/PROTOCOL.md`).
//! Empty until the protocol review is approved.
//! Wire types for the Tabellarius protocol v0 (`docs/PROTOCOL.md`, approved 2026-11-08).
//!
//! No I/O. Every value that crosses the wire has exactly one spelling: ids and tokens are unpadded
//! base64url of a fixed number of bytes, and parsing refuses anything else with a [`ParseError`].
//! The HTTP routes that carry these types are listed in `.agents/features/relay.md` §2.
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sha2::{Digest, Sha256};
use std::borrow::Cow;
use std::fmt;
/// The protocol version, as it appears in every path (`/v0/...`).
pub const VERSION: &str = "v0";
/// The largest blob (one MLS message) the relay accepts.
pub const MAX_BLOB_BYTES: usize = 256 * 1024;
/// The largest KeyPackage an invite may carry.
pub const MAX_KEY_PACKAGE_BYTES: usize = 16 * 1024;
/// At most this many blobs come back from one fetch; the rest wait for the next.
pub const MAX_BLOBS_PER_FETCH: usize = 100;
/// A blob not acknowledged is deleted after this many seconds (30 days, `PROTOCOL.md` §5).
pub const BLOB_TTL_SECS: i64 = 30 * 24 * 3600;
/// An unclaimed invite expires after this many seconds (7 days, `PROTOCOL.md` §4).
pub const INVITE_TTL_SECS: i64 = 7 * 24 * 3600;
/// Why a value from the wire was refused. Carries no part of the input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseError {
/// Not unpadded base64url, or not its one canonical spelling.
Encoding,
/// Decoded to the wrong number of bytes.
Length { expected: usize, got: usize },
/// The bearer header is missing its `Bearer ` prefix.
Scheme,
/// More bytes than the protocol allows.
TooLarge { max: usize },
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseError::Encoding => write!(f, "not canonical unpadded base64url"),
ParseError::Length { expected, got } => {
write!(f, "expected {expected} bytes, got {got}")
}
ParseError::Scheme => write!(f, "expected 'Bearer <token>'"),
ParseError::TooLarge { max } => write!(f, "more than {max} bytes"),
}
}
}
impl std::error::Error for ParseError {}
fn is_base64url(text: &str) -> bool {
text.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
/// Decodes canonical unpadded base64url: refuses other alphabets, padding, and spellings whose
/// unused trailing bits are not zero (those would give one value a second spelling).
fn decode_canonical(text: &str) -> Result<Vec<u8>, ParseError> {
if !is_base64url(text) {
return Err(ParseError::Encoding);
}
let bytes = URL_SAFE_NO_PAD
.decode(text)
.map_err(|_| ParseError::Encoding)?;
if URL_SAFE_NO_PAD.encode(&bytes) != text {
return Err(ParseError::Encoding);
}
Ok(bytes)
}
fn decode_exact<const N: usize>(text: &str) -> Result<[u8; N], ParseError> {
// A cheap bound first: anything longer than N bytes' worth of characters is refused unread.
if text.len() > N.div_ceil(3) * 4 {
return Err(ParseError::Length {
expected: N,
got: text.len() / 4 * 3,
});
}
let bytes = decode_canonical(text)?;
let got = bytes.len();
bytes
.try_into()
.map_err(|_| ParseError::Length { expected: N, got })
}
macro_rules! fixed_bytes {
($(#[$doc:meta])* $name:ident, $len:expr) => {
$(#[$doc])*
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct $name([u8; $len]);
impl $name {
pub const LEN: usize = $len;
pub fn from_bytes(bytes: [u8; $len]) -> Self {
Self(bytes)
}
pub fn as_bytes(&self) -> &[u8; $len] {
&self.0
}
/// Parses the wire spelling: unpadded base64url of exactly `LEN` bytes.
pub fn parse(text: &str) -> Result<Self, ParseError> {
decode_exact::<$len>(text).map(Self)
}
pub fn to_wire(&self) -> String {
URL_SAFE_NO_PAD.encode(self.0)
}
}
impl Serialize for $name {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&self.to_wire())
}
}
impl<'de> Deserialize<'de> for $name {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let text = Cow::<'de, str>::deserialize(d)?;
Self::parse(&text).map_err(serde::de::Error::custom)
}
}
};
}
fixed_bytes!(
/// A mailbox: 16 random bytes made by its owner. One per contact (`PROTOCOL.md` §3).
MailboxId,
16
);
fixed_bytes!(
/// An invite: 16 random bytes made by the inviter (`PROTOCOL.md` §4).
InviteId,
16
);
fixed_bytes!(
/// SHA-256 of a token, or of a blob when it is acknowledged. The relay stores token hashes only.
Sha256Hash,
32
);
fixed_bytes!(
/// A capability: a post token, a fetch token or an invite's one-time secret. 32 random bytes.
/// Never stored by the relay; only its [`Sha256Hash`] is.
Token,
32
);
impl Token {
/// The hash the relay stores and compares against.
pub fn hash(&self) -> Sha256Hash {
Sha256Hash(Sha256::digest(self.0).into())
}
/// Parses an `Authorization` header value: `Bearer <token>`.
pub fn from_bearer(header: &str) -> Result<Self, ParseError> {
let token = header.strip_prefix("Bearer ").ok_or(ParseError::Scheme)?;
Self::parse(token)
}
pub fn to_bearer(&self) -> String {
format!("Bearer {}", self.to_wire())
}
}
// Tokens are secrets: never printed, not even in a debug log.
impl fmt::Debug for Token {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Token(..)")
}
}
macro_rules! debug_as_wire {
($($name:ident),*) => {$(
impl fmt::Debug for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}({})", stringify!($name), self.to_wire())
}
}
)*};
}
debug_as_wire!(MailboxId, InviteId, Sha256Hash);
/// The SHA-256 of a blob: how its recipient acknowledges it.
pub fn blob_hash(blob: &[u8]) -> Sha256Hash {
Sha256Hash(Sha256::digest(blob).into())
}
/// Bytes inside JSON as unpadded base64url, with an upper bound checked before decoding.
#[derive(Clone, PartialEq, Eq)]
pub struct WireBytes(pub Vec<u8>);
impl WireBytes {
pub fn parse(text: &str, max: usize) -> Result<Self, ParseError> {
// 4 characters carry 3 bytes: anything longer cannot fit, and is refused before decoding.
if text.len() > max.div_ceil(3) * 4 {
return Err(ParseError::TooLarge { max });
}
let bytes = decode_canonical(text)?;
if bytes.len() > max {
return Err(ParseError::TooLarge { max });
}
Ok(Self(bytes))
}
}
impl fmt::Debug for WireBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "WireBytes({} bytes)", self.0.len())
}
}
impl Serialize for WireBytes {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&URL_SAFE_NO_PAD.encode(&self.0))
}
}
macro_rules! bounded_bytes {
($(#[$doc:meta])* $name:ident, $max:expr) => {
$(#[$doc])*
#[derive(Clone, PartialEq, Eq, Debug, Serialize)]
#[serde(transparent)]
pub struct $name(pub WireBytes);
impl $name {
pub fn new(bytes: Vec<u8>) -> Result<Self, ParseError> {
if bytes.len() > $max {
return Err(ParseError::TooLarge { max: $max });
}
Ok(Self(WireBytes(bytes)))
}
pub fn bytes(&self) -> &[u8] {
&self.0 .0
}
}
impl<'de> Deserialize<'de> for $name {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let text = Cow::<'de, str>::deserialize(d)?;
WireBytes::parse(&text, $max)
.map(Self)
.map_err(serde::de::Error::custom)
}
}
};
}
bounded_bytes!(
/// A KeyPackage inside an invite, at most [`MAX_KEY_PACKAGE_BYTES`].
KeyPackageBytes,
MAX_KEY_PACKAGE_BYTES
);
bounded_bytes!(
/// A blob inside a fetch response, at most [`MAX_BLOB_BYTES`].
BlobBytes,
MAX_BLOB_BYTES
);
/// `POST /v0/mailboxes`. The owner sends hashes, so the relay never sees the tokens themselves here.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CreateMailbox {
pub id: MailboxId,
pub post_token_hash: Sha256Hash,
pub fetch_token_hash: Sha256Hash,
}
/// `PUT /v0/mailboxes/{id}/post-token`: blocking someone = giving everyone else a new post token.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RotatePostToken {
pub post_token_hash: Sha256Hash,
}
/// One waiting blob in `GET /v0/mailboxes/{id}/blobs`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FetchedBlob {
pub blob: BlobBytes,
/// Unix time in hours, rounded down: all the relay keeps of when it arrived.
pub received_hour: i64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FetchedBlobs {
pub blobs: Vec<FetchedBlob>,
}
/// `POST /v0/invites`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CreateInvite {
pub id: InviteId,
pub secret_hash: Sha256Hash,
pub key_package: KeyPackageBytes,
}
/// `GET /v0/invites/{id}`: the inviter's KeyPackage, handed out once.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ClaimedInvite {
pub key_package: KeyPackageBytes,
}
/// `GET /version`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct VersionInfo {
pub protocol: String,
pub relay: String,
}
/// Rounds unix seconds down to the hour, as the relay stores arrival times.
pub fn hour_of(unix_secs: i64) -> i64 {
unix_secs.div_euclid(3600)
}
/// Rounds unix seconds down to the day, as the relay stores when a mailbox was made.
pub fn day_of(unix_secs: i64) -> i64 {
unix_secs.div_euclid(86_400)
}
+186
View File
@@ -0,0 +1,186 @@
//! The wire spelling: one value, one spelling, and no input that panics a parser.
use proptest::prelude::*;
use tabellarius_protocol::*;
#[test]
fn ids_and_tokens_round_trip_through_their_wire_spelling() {
let id = MailboxId::from_bytes([7; 16]);
assert_eq!(id.to_wire().len(), 22);
assert_eq!(MailboxId::parse(&id.to_wire()), Ok(id));
let token = Token::from_bytes([9; 32]);
assert_eq!(token.to_wire().len(), 43);
assert_eq!(Token::from_bearer(&token.to_bearer()), Ok(token));
}
#[test]
fn a_wrong_length_alphabet_padding_or_spelling_is_refused() {
let good = MailboxId::from_bytes([0xAB; 16]).to_wire();
// one character short, one too many
assert!(MailboxId::parse(&good[..21]).is_err());
assert!(MailboxId::parse(&format!("{good}A")).is_err());
// the standard alphabet and padding are not this protocol's
assert_eq!(
MailboxId::parse(&good.replace('-', "+").replace('_', "/").replace('q', "+")),
Err(ParseError::Encoding)
);
assert_eq!(
MailboxId::parse(&format!("{good}==")),
Err(ParseError::Encoding)
);
// a Token is not a MailboxId
assert!(matches!(
MailboxId::parse(&Token::from_bytes([1; 32]).to_wire()),
Err(ParseError::Length { expected: 16, .. })
));
assert_eq!(
MailboxId::parse(""),
Err(ParseError::Length {
expected: 16,
got: 0
})
);
}
#[test]
fn a_second_spelling_of_the_same_bytes_is_refused() {
// 16 bytes leave 4 unused bits in the last character. 'A' (000000) is canonical for a zero
// tail; 'B' (000001) decodes to the same bytes with a non-zero unused bit.
let canonical = MailboxId::from_bytes([0; 16]).to_wire();
assert!(canonical.ends_with('A'));
let other = format!("{}B", &canonical[..21]);
assert_eq!(MailboxId::parse(&other), Err(ParseError::Encoding));
}
#[test]
fn a_bearer_header_needs_its_scheme() {
let token = Token::from_bytes([3; 32]);
assert_eq!(
Token::from_bearer(&token.to_wire()),
Err(ParseError::Scheme)
);
assert_eq!(
Token::from_bearer(&format!("bearer {}", token.to_wire())),
Err(ParseError::Scheme)
);
assert!(Token::from_bearer(&format!("Bearer {}", token.to_wire())).is_err());
}
#[test]
fn a_token_is_never_printed() {
let token = Token::from_bytes([0x5A; 32]);
let shown = format!("{token:?}");
assert_eq!(shown, "Token(..)");
assert!(!shown.contains(&token.to_wire()));
}
#[test]
fn the_hash_of_a_token_is_its_sha256() {
// SHA-256 of 32 zero bytes, a published value.
let hash = Token::from_bytes([0; 32]).hash();
let hex: String = hash.as_bytes().iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(
hex,
"66687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925"
);
}
#[test]
fn json_bodies_refuse_unknown_fields_and_bad_values() {
let ok = serde_json::json!({
"id": MailboxId::from_bytes([1; 16]).to_wire(),
"postTokenHash": Sha256Hash::from_bytes([2; 32]).to_wire(),
"fetchTokenHash": Sha256Hash::from_bytes([3; 32]).to_wire(),
});
let parsed: CreateMailbox = serde_json::from_value(ok.clone()).expect("valid body");
assert_eq!(parsed.id, MailboxId::from_bytes([1; 16]));
let mut extra = ok.clone();
extra["name"] = serde_json::json!("Eva");
assert!(serde_json::from_value::<CreateMailbox>(extra).is_err());
let mut short = ok;
short["id"] = serde_json::json!("AAAA");
assert!(serde_json::from_value::<CreateMailbox>(short).is_err());
}
#[test]
fn a_key_package_over_the_limit_is_refused_before_decoding() {
let at_limit = KeyPackageBytes::new(vec![0; MAX_KEY_PACKAGE_BYTES]).expect("at the limit");
let body = serde_json::json!({
"id": InviteId::from_bytes([1; 16]).to_wire(),
"secretHash": Sha256Hash::from_bytes([2; 32]).to_wire(),
"keyPackage": at_limit,
});
assert!(serde_json::from_value::<CreateInvite>(body.clone()).is_ok());
let mut over = body;
over["keyPackage"] = serde_json::json!("A".repeat(MAX_KEY_PACKAGE_BYTES / 3 * 4 + 8));
let err = serde_json::from_value::<CreateInvite>(over).expect_err("over the limit");
assert!(err.to_string().contains("more than"), "{err}");
assert!(KeyPackageBytes::new(vec![0; MAX_KEY_PACKAGE_BYTES + 1]).is_err());
}
#[test]
fn time_is_kept_only_to_the_hour_and_the_day() {
assert_eq!(hour_of(7199), 1);
assert_eq!(hour_of(-1), -1);
assert_eq!(day_of(86_399), 0);
assert_eq!(day_of(86_400), 1);
}
fn config() -> ProptestConfig {
ProptestConfig {
cases: 10_000,
..ProptestConfig::default()
}
}
proptest! {
#![proptest_config(config())]
/// Any string at all: every parser answers with a value or an error, never a panic.
#[test]
fn no_string_panics_a_parser(text in any::<String>()) {
let _ = MailboxId::parse(&text);
let _ = InviteId::parse(&text);
let _ = Sha256Hash::parse(&text);
let _ = Token::parse(&text);
let _ = Token::from_bearer(&text);
let _ = WireBytes::parse(&text, MAX_BLOB_BYTES);
}
/// Strings from the base64url alphabet (the ones that get furthest into the decoder).
#[test]
fn no_base64url_string_panics_a_parser(text in "[A-Za-z0-9_=+/-]{0,90}") {
let _ = MailboxId::parse(&text);
let _ = Token::parse(&text);
let _ = Token::from_bearer(&format!("Bearer {text}"));
let _ = WireBytes::parse(&text, 64);
}
/// Any JSON-ish bytes given to every request body: an error or a value, never a panic.
#[test]
fn no_body_panics_the_json_parsers(bytes in proptest::collection::vec(any::<u8>(), 0..300)) {
let _ = serde_json::from_slice::<CreateMailbox>(&bytes);
let _ = serde_json::from_slice::<RotatePostToken>(&bytes);
let _ = serde_json::from_slice::<CreateInvite>(&bytes);
let _ = serde_json::from_slice::<FetchedBlobs>(&bytes);
let _ = serde_json::from_slice::<ClaimedInvite>(&bytes);
}
/// Every id that parses has exactly the spelling it was given.
#[test]
fn whatever_parses_has_one_spelling(text in "[A-Za-z0-9_-]{22}") {
if let Ok(id) = MailboxId::parse(&text) {
prop_assert_eq!(id.to_wire(), text);
}
}
/// Bytes survive the wire unchanged.
#[test]
fn bytes_round_trip(bytes in proptest::collection::vec(any::<u8>(), 0..512)) {
let wire = serde_json::to_string(&BlobBytes::new(bytes.clone()).expect("small")).expect("json");
let back: BlobBytes = serde_json::from_str(&wire).expect("parses");
prop_assert_eq!(back.bytes(), &bytes[..]);
}
}