commit c162ccd5ccb511602d8ec38935000bdea834bf4c
parent 6ada4f98859a8b24b84caef70445c6cdc13b380c
Author: triesap <tyson@radroots.org>
Date: Fri, 23 Oct 2026 00:29:27 +0000
protocol: Require object shapes for captured commands
- Enforce map decoding for command roots, payloads and source references.
- Require objects for shared actor, authority, approval, checkpoint and context descriptors.
- Preserve canonical bytes, digests, explicit nulls and duplicate-field rejection.
- Verify reproduced regressions, native replay, target checks and unchanged coverage gates.
Diffstat:
9 files changed, 310 insertions(+), 17 deletions(-)
diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt
@@ -468,6 +468,8 @@ impl radroots_domain::AuthorityRef
pub const fn radroots_domain::AuthorityRef::executor_id(self) -> radroots_domain::ExecutorId
pub const fn radroots_domain::AuthorityRef::generation(self) -> radroots_domain::Generation
pub const fn radroots_domain::AuthorityRef::new(radroots_domain::ExecutorId, radroots_domain::Generation) -> Self
+impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::AuthorityRef
+pub fn radroots_domain::AuthorityRef::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error>
pub struct radroots_domain::CancellationProposal
impl radroots_domain::CancellationProposal
pub const fn radroots_domain::CancellationProposal::agreement(&self) -> radroots_domain::RecordId
diff --git a/crates/domain/src/context.rs b/crates/domain/src/context.rs
@@ -185,8 +185,7 @@ impl ActorRef {
}
/// Exact selected executor and authority epoch, without an authority certificate.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
-#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
-#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
+#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct AuthorityRef {
executor_id: ExecutorId,
generation: Generation,
@@ -473,6 +472,21 @@ impl fmt::Debug for CommandContextData {
mod serialization {
use super::*;
use serde::{Deserialize, Deserializer, Serializer, de::Error};
+
+ fn object<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<T, D::Error> {
+ struct ObjectVisitor<T>(core::marker::PhantomData<T>);
+ impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for ObjectVisitor<T> {
+ type Value = T;
+ fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("an object")
+ }
+ fn visit_map<M: serde::de::MapAccess<'de>>(self, map: M) -> Result<T, M::Error> {
+ T::deserialize(serde::de::value::MapAccessDeserializer::new(map))
+ }
+ }
+ d.deserialize_map(ObjectVisitor::<T>(core::marker::PhantomData))
+ }
+
fn nullable<'de, D: Deserializer<'de>, T: Deserialize<'de>>(
d: D,
) -> Result<Option<T>, D::Error> {
@@ -488,6 +502,18 @@ mod serialization {
Self::new(String::deserialize(d)?).map_err(D::Error::custom)
}
}
+ impl<'de> Deserialize<'de> for AuthorityRef {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ #[derive(Deserialize)]
+ #[serde(deny_unknown_fields)]
+ struct Raw {
+ executor_id: ExecutorId,
+ generation: Generation,
+ }
+ let raw: Raw = object(d)?;
+ Ok(Self::new(raw.executor_id, raw.generation))
+ }
+ }
impl<'de> Deserialize<'de> for ActorRef {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
@@ -500,7 +526,7 @@ mod serialization {
#[serde(deserialize_with = "nullable")]
grant_id: Option<GrantId>,
}
- let raw = Raw::deserialize(d)?;
+ let raw: Raw = object(d)?;
Ok(Self::new(
raw.participant,
raw.role,
@@ -519,7 +545,7 @@ mod serialization {
coverage: Coverage,
missing: Vec<SourceId>,
}
- let raw = Raw::deserialize(d)?;
+ let raw: Raw = object(d)?;
Self::new(raw.digest, raw.sequence, raw.coverage, raw.missing).map_err(D::Error::custom)
}
}
@@ -532,7 +558,7 @@ mod serialization {
scope: String,
expires_at: UnixSeconds,
}
- let raw = Raw::deserialize(d)?;
+ let raw: Raw = object(d)?;
Self::new(raw.intent_digest, raw.scope, raw.expires_at).map_err(D::Error::custom)
}
}
@@ -549,7 +575,7 @@ mod serialization {
buyer_head: Option<RecordId>,
checkpoint: CheckpointRef,
}
- let raw = Raw::deserialize(d)?;
+ let raw: Raw = object(d)?;
Ok(Self::new(
raw.order_id,
raw.agreement,
@@ -577,7 +603,7 @@ mod serialization {
#[serde(deserialize_with = "nullable")]
correlation_id: Option<CorrelationId>,
}
- let raw = Raw::deserialize(d)?;
+ let raw: Raw = object(d)?;
Self::new(
raw.operation_id,
raw.actor,
diff --git a/crates/domain/tests/context.rs b/crates/domain/tests/context.rs
@@ -40,6 +40,65 @@ fn context() -> CommandContextData {
.unwrap()
}
+#[cfg(feature = "serde")]
+#[test]
+fn context_descriptors_require_objects_when_decoded_directly() {
+ fn check<T>(value: T, fields: &[&str])
+ where
+ T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
+ {
+ let object = serde_json::to_value(&value).unwrap();
+ assert_eq!(serde_json::from_value::<T>(object.clone()).unwrap(), value);
+ let array = Value::Array(fields.iter().map(|field| object[field].clone()).collect());
+ assert!(serde_json::from_value::<T>(array).is_err());
+ }
+ check(
+ actor(),
+ &["participant", "role", "organization", "grant_id"],
+ );
+ check(context().authority(), &["executor_id", "generation"]);
+ check(checkpoint(), &["digest", "sequence", "coverage", "missing"]);
+ check(
+ Approval::new(
+ ApprovalIntentDigest::from_bytes([6; 32]),
+ "inbox.inquire",
+ UnixSeconds::new(190).unwrap(),
+ )
+ .unwrap(),
+ &["intent_digest", "scope", "expires_at"],
+ );
+ check(
+ ExpectedOrder::new(
+ OrderId::from_bytes([7; 32]),
+ None,
+ Sequence::new(4).unwrap(),
+ None,
+ checkpoint(),
+ ),
+ &[
+ "order_id",
+ "agreement",
+ "seller_sequence",
+ "buyer_head",
+ "checkpoint",
+ ],
+ );
+ check(
+ context(),
+ &[
+ "operation_id",
+ "actor",
+ "workspace_id",
+ "authority",
+ "route_digest",
+ "approval",
+ "expected",
+ "not_after",
+ "correlation_id",
+ ],
+ );
+}
+
#[test]
fn exact_integers_never_round_or_accept_numeric_json_coercions() {
for value in [0, 1, 9_007_199_254_740_993, i64::MAX as u64] {
diff --git a/crates/protocol/README.md b/crates/protocol/README.md
@@ -40,6 +40,10 @@ numbers embedded in wire and schema contracts.
Versioned DTOs live below an explicit generation module. The command codec
implements its fixed v1 profile without exposing automatic serialization of
captured private commands. Parsed command data supplies no authority or consent.
+Command roots, inquiry/reply inputs, source references and all shared context
+descriptors require objects; positional arrays are refused. The map-only typed
+decoder preserves borrowed input and existing duplicate, unknown-field, explicit
+null, byte/depth and exact canonical command/hash checks.
The crate root
does not reexport individual DTOs, so consumers must name the contract version
they use.
diff --git a/crates/protocol/src/command.rs b/crates/protocol/src/command.rs
@@ -263,19 +263,17 @@ impl CapturedChatCommand {
/// Parses a bounded closed profile. JSON syntax supplies no grant or consent.
pub fn parse(raw: &[u8]) -> Result<Self, CommandError> {
check_frame(raw)?;
- let root: RawRoot<'_> =
- serde_json::from_slice(raw).map_err(|_| CommandError::InvalidInput)?;
+ let root: RawRoot<'_> = parse_object(raw)?;
if root.kind.len() > 80 {
return Err(CommandError::LimitExceeded);
}
match root.kind.as_str() {
"inbox.inquire" => {
- let raw: RawInquiry = serde_json::from_str(root.input.get())
- .map_err(|_| CommandError::InvalidInput)?;
+ let raw: RawInquiry = parse_object(root.input.get().as_bytes())?;
if raw.text.len() > CHAT_MAX_BYTES {
return Err(CommandError::LimitExceeded);
}
- let source = raw.source.map(RawSource::validate).transpose()?;
+ let source = raw.source.map(|source| source.0.validate()).transpose()?;
Self::new(
root.context,
Input::Inquire(InquireInput {
@@ -287,8 +285,7 @@ impl CapturedChatCommand {
)
}
"inbox.reply" => {
- let raw: RawReply = serde_json::from_str(root.input.get())
- .map_err(|_| CommandError::InvalidInput)?;
+ let raw: RawReply = parse_object(root.input.get().as_bytes())?;
if raw.text.len() > CHAT_MAX_BYTES {
return Err(CommandError::LimitExceeded);
}
@@ -411,6 +408,35 @@ pub(crate) fn check_frame(raw: &[u8]) -> Result<(), CommandError> {
}
Ok(())
}
+
+// Require maps without materializing a second JSON tree. The typed decoder
+// still owns duplicate, required-field and unknown-field checks, and borrowed
+// RawValue fields continue to refer to the bounded original frame.
+fn object<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<T, D::Error> {
+ struct ObjectVisitor<T>(core::marker::PhantomData<T>);
+ impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for ObjectVisitor<T> {
+ type Value = T;
+ fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("an object")
+ }
+ fn visit_map<M: serde::de::MapAccess<'de>>(self, map: M) -> Result<T, M::Error> {
+ T::deserialize(serde::de::value::MapAccessDeserializer::new(map))
+ }
+ }
+ d.deserialize_map(ObjectVisitor::<T>(core::marker::PhantomData))
+}
+struct MapOnly<T>(T);
+impl<'de, T: Deserialize<'de>> Deserialize<'de> for MapOnly<T> {
+ fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ object(d).map(Self)
+ }
+}
+pub(crate) fn parse_object<'de, T: Deserialize<'de>>(raw: &'de [u8]) -> Result<T, CommandError> {
+ serde_json::from_slice::<MapOnly<T>>(raw)
+ .map(|value| value.0)
+ .map_err(|_| CommandError::InvalidInput)
+}
+
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawRoot<'a> {
@@ -434,7 +460,7 @@ struct RawInquiry {
thread_id: ThreadId,
peer: PublicKey,
#[serde(deserialize_with = "required_nullable")]
- source: Option<RawSource>,
+ source: Option<MapOnly<RawSource>>,
#[serde(deserialize_with = "private_text")]
text: Zeroizing<String>,
}
@@ -450,6 +476,7 @@ struct RawReply {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawSource {
+ #[serde(deserialize_with = "object")]
coordinate: RawCoordinate,
event_id: SourceId,
}
diff --git a/crates/protocol/src/command/captured.rs b/crates/protocol/src/command/captured.rs
@@ -47,7 +47,7 @@ impl CapturedCommand {
#[serde(rename = "type")]
kind: String,
}
- let header: Header = serde_json::from_slice(raw).map_err(|_| CommandError::InvalidInput)?;
+ let header: Header = super::parse_object(raw)?;
if header.kind.len() > 80 {
return Err(CommandError::LimitExceeded);
}
diff --git a/crates/protocol/src/listing/command.rs b/crates/protocol/src/listing/command.rs
@@ -74,7 +74,7 @@ impl CapturedListingCommand {
#[serde(borrow)]
input: &'a serde_json::value::RawValue,
}
- let root: Root<'_> = serde_json::from_slice(raw).map_err(|_| CommandError::InvalidInput)?;
+ let root: Root<'_> = crate::command::parse_object(raw)?;
if root.kind != "listing.publish" {
return Err(CommandError::UnsupportedCommand);
}
diff --git a/crates/protocol/tests/command.rs b/crates/protocol/tests/command.rs
@@ -51,6 +51,129 @@ fn inquiry(
)
.unwrap()
}
+
+#[test]
+fn closed_commands_require_objects_at_every_context_and_inquiry_boundary() {
+ use radroots_protocol::command::CapturedCommand;
+
+ let mut base: Value =
+ serde_json::from_slice(inquiry(None, None, "private").protected_wire()).unwrap();
+ base["context"]["approval"] = json!({
+ "intent_digest":"08".repeat(32),"scope":"inbox.inquire","expires_at":"190"
+ });
+ base["context"]["expected"] = json!({
+ "order_id":"09".repeat(32),"agreement":"0a".repeat(32),
+ "seller_sequence":"4","buyer_head":"0b".repeat(32),
+ "checkpoint":{"digest":"0c".repeat(32),"sequence":"4",
+ "coverage":"partial","missing":["0d".repeat(32)]}
+ });
+ base["input"]["source"] = json!({
+ "coordinate":{"kind":30402,"author":bob().to_hex(),"d":"55".repeat(16)},
+ "event_id":"0e".repeat(32)
+ });
+ let wire = serde_json::to_vec(&base).unwrap();
+ CapturedChatCommand::parse(&wire).unwrap();
+ CapturedCommand::parse(&wire).unwrap();
+ let mut accepted = Vec::new();
+ for (pointer, keys) in [
+ ("", &["type", "context", "input"][..]),
+ (
+ "/context",
+ &[
+ "operation_id",
+ "actor",
+ "workspace_id",
+ "authority",
+ "route_digest",
+ "approval",
+ "expected",
+ "not_after",
+ "correlation_id",
+ ][..],
+ ),
+ (
+ "/context/actor",
+ &["participant", "role", "organization", "grant_id"][..],
+ ),
+ ("/context/authority", &["executor_id", "generation"][..]),
+ (
+ "/context/approval",
+ &["intent_digest", "scope", "expires_at"][..],
+ ),
+ (
+ "/context/expected",
+ &[
+ "order_id",
+ "agreement",
+ "seller_sequence",
+ "buyer_head",
+ "checkpoint",
+ ][..],
+ ),
+ (
+ "/context/expected/checkpoint",
+ &["digest", "sequence", "coverage", "missing"][..],
+ ),
+ ("/input", &["thread_id", "peer", "source", "text"][..]),
+ ("/input/source", &["coordinate", "event_id"][..]),
+ ("/input/source/coordinate", &["kind", "author", "d"][..]),
+ ] {
+ let mut value = base.clone();
+ let array = Value::Array(
+ keys.iter()
+ .map(|key| value.pointer(pointer).unwrap()[key].clone())
+ .collect(),
+ );
+ *value.pointer_mut(pointer).unwrap() = array;
+ let raw = serde_json::to_vec(&value).unwrap();
+ if CapturedChatCommand::parse(&raw).is_ok() {
+ accepted.push(format!("chat:{pointer}"));
+ }
+ if CapturedCommand::parse(&raw).is_ok() {
+ accepted.push(format!("dispatch:{pointer}"));
+ }
+ }
+ assert!(
+ accepted.is_empty(),
+ "object fields accepted positional arrays: {accepted:?}"
+ );
+}
+
+#[test]
+fn closed_reply_input_requires_an_object_without_changing_its_canonical_bytes() {
+ use radroots_protocol::command::CapturedCommand;
+
+ let reply = CapturedChatCommand::reply(
+ context(None, None),
+ ReplyInput::new(
+ ThreadId::from_bytes([6; 32]),
+ bob(),
+ MessageId::from_bytes([11; 32]),
+ "reply",
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ let mut value: Value = serde_json::from_slice(reply.protected_wire()).unwrap();
+ let parsed = CapturedChatCommand::parse(reply.protected_wire()).unwrap();
+ assert_eq!(parsed.protected_wire(), reply.protected_wire());
+ assert_eq!(parsed.digest(), reply.digest());
+ value["input"] = Value::Array(
+ ["thread_id", "peer", "parent", "text"]
+ .iter()
+ .map(|key| value["input"][key].clone())
+ .collect(),
+ );
+ let raw = serde_json::to_vec(&value).unwrap();
+ assert!(matches!(
+ CapturedChatCommand::parse(&raw),
+ Err(CommandError::InvalidInput)
+ ));
+ assert!(matches!(
+ CapturedCommand::parse(&raw),
+ Err(CommandError::InvalidInput)
+ ));
+}
#[derive(Deserialize)]
struct Vectors {
vectors: Vec<Vector>,
diff --git a/crates/protocol/tests/public_command.rs b/crates/protocol/tests/public_command.rs
@@ -35,6 +35,58 @@ fn input() -> Value {
}
#[test]
+fn public_command_root_and_context_reject_positional_arrays() {
+ let command = CapturedListingCommand::capture(
+ context(),
+ PublishInput::parse(&serde_json::to_vec(&input()).unwrap()).unwrap(),
+ )
+ .unwrap();
+ let base: Value = serde_json::from_slice(command.protected_wire()).unwrap();
+ let mut accepted = Vec::new();
+ for (pointer, keys) in [
+ ("", &["type", "context", "input"][..]),
+ (
+ "/context",
+ &[
+ "operation_id",
+ "actor",
+ "workspace_id",
+ "authority",
+ "route_digest",
+ "approval",
+ "expected",
+ "not_after",
+ "correlation_id",
+ ][..],
+ ),
+ (
+ "/context/actor",
+ &["participant", "role", "organization", "grant_id"][..],
+ ),
+ ("/context/authority", &["executor_id", "generation"][..]),
+ ] {
+ let mut value = base.clone();
+ let array = Value::Array(
+ keys.iter()
+ .map(|key| value.pointer(pointer).unwrap()[key].clone())
+ .collect(),
+ );
+ *value.pointer_mut(pointer).unwrap() = array;
+ let raw = serde_json::to_vec(&value).unwrap();
+ if CapturedListingCommand::parse(&raw).is_ok() {
+ accepted.push(format!("listing:{pointer}"));
+ }
+ if CapturedCommand::parse(&raw).is_ok() {
+ accepted.push(format!("dispatch:{pointer}"));
+ }
+ }
+ assert!(
+ accepted.is_empty(),
+ "object fields accepted positional arrays: {accepted:?}"
+ );
+}
+
+#[test]
fn listing_objects_reject_positional_arrays_at_every_struct_boundary() {
let mut accepted = Vec::new();
for (pointer, fields) in [