commit dbab7a62eed99f153c9b2c32e278a6c9d7b482c2 parent a826dc9961cb6c81e2efa5ca1d11c41a3d2988c8 Author: triesap <tyson@radroots.org> Date: Fri, 23 Oct 2026 02:22:38 +0000 protocol: Decode closed private terms with protected text - Admit bounded object shapes with duplicate checks and required nullable fields. - Reuse public snapshot constructors and validate complete terms without effects. - Decode private Unicode text into zeroizing buffers and refuse future profiles. - Verify no_std, WASM, generated inventory, API, runtime coverage and strict lint. Diffstat:
18 files changed, 1162 insertions(+), 240 deletions(-)
diff --git a/contracts/api_baselines/radroots_protocol.txt b/contracts/api_baselines/radroots_protocol.txt @@ -1167,3 +1167,4 @@ pub fn radroots_protocol::terms::EncodedTerms::retained_bytes(&self) -> usize impl core::fmt::Debug for radroots_protocol::terms::EncodedTerms pub fn radroots_protocol::terms::EncodedTerms::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub const radroots_protocol::terms::TERMS_MAX_BYTES: usize +pub fn radroots_protocol::terms::decode(&[u8]) -> core::result::Result<radroots_domain::agreement::Terms, radroots_protocol::terms::TermsWireError> diff --git a/contracts/codegen/protocol_v1.inventory.json b/contracts/codegen/protocol_v1.inventory.json @@ -7,7 +7,7 @@ { "module": "capability::v1", "path": "crates/protocol/src/capability/v1.rs", - "sha256": "db2ac595ff4e45652791df49d3e0129afcac57fb568f71c6b7355e083b359ad6", + "sha256": "0907e7b4fc9b8d9c38825518c6f6878ae2fd43f9882373efb6f603b88f4f2631", "types": [ { "rust_path": "radroots_protocol::capability::v1::Availability", @@ -104,7 +104,7 @@ { "module": "radrootsd::transport_publish::v5", "path": "crates/protocol/src/radrootsd/transport_publish/v5.rs", - "sha256": "a562ce9af3fd0e65a31c121c0c73c44a895d45872546c9290c193643b9df8b5b", + "sha256": "1ad9ab4b3de960b8a1c02d68f50028419821143dc94a031ccad421b7b65556b6", "types": [ { "rust_path": "radroots_protocol::radrootsd::transport_publish::v5::AuthCapabilities", @@ -203,7 +203,7 @@ { "module": "runtime::v1", "path": "crates/protocol/src/runtime/v1.rs", - "sha256": "d25db1e8b5beaa017bbed549ccc0ce1a54c34f58de4c636b8a33e6a22b66c17f", + "sha256": "e408748d4be7ef7f50dc02f13e1a20c649154d30a970b4cf4df8ce77c26887e4", "types": [ { "rust_path": "radroots_protocol::runtime::v1::ApprovalRequirement", diff --git a/contracts/codegen/protocol_v1.inventory.sha256 b/contracts/codegen/protocol_v1.inventory.sha256 @@ -1 +1 @@ -239346a4d0f34c33f76cd06d3cda9a9df84e906c44474180cc139fb7712b7985 +21fb0edf62b14da69aaa8fd613043ad6bf4125dc767b565bf34b48eb46782f29 diff --git a/contracts/protocol/terms.v1.json b/contracts/protocol/terms.v1.json @@ -1,8 +1,8 @@ { "schema": "radroots.terms.codec.v1", "contract_version": 1, - "state": "canonical_encoder_contract", - "owner": "radroots_protocol::terms::EncodedTerms", + "state": "closed_bounded_terms_codec_contract", + "owner": "radroots_protocol::terms::{decode, EncodedTerms}", "feature": "terms", "input": "Validated complete radroots_domain::Terms; all source snapshots and supply commitments remain unauthenticated claims.", "content_max_utf8_bytes": 16384, @@ -33,9 +33,22 @@ "public_snapshot_serialization": "Only explicitly public product, option and listing-revision snapshots may enter a temporary serde_json Value. Private fulfillment, selected/agreed prices, lot labels and supply risk use the protected writer directly.", "retained_bytes": "EncodedTerms fixed object plus retained output buffer capacity; caller input and outer record/rumor allocations remain separate." }, + "decoding": { + "entry_point": "radroots_protocol::terms::decode", + "max_json_depth": 16, + "max_lines": 32, + "max_fulfillment_groups": 8, + "objects_only": true, + "unknown_duplicate_and_missing_fields_rejected": true, + "nullable_fields_must_be_present": true, + "private_fields_borrow_original_raw_json_until_protected_decoding": true, + "private_text_decoded_scratch": "Two-pass count then zeroizing UTF-8 output; explicit JSON escapes and paired UTF-16 surrogates, with no normalization.", + "domain_validation": "Every complete line, group, money, price, window, supply commitment and Terms constructor runs; no missing field or snapshot is synthesized.", + "caller_input_ownership": "The caller owns original private bytes and their protection; successful structural/domain decoding is not authenticated evidence." + }, "limits": { "record_header_cost_included": false, - "decoder_or_authenticated_admission_implemented_by_this_contract": false, + "authenticated_admission_implemented_by_this_contract": false, "structured_record_authoring_enabled": false, "consent_or_stock_authority_created": false, "runtime_clock_entropy_signer_or_network_allowed": false, diff --git a/crates/protocol/README.md b/crates/protocol/README.md @@ -31,7 +31,7 @@ numbers embedded in wire and schema contracts. | `radrootsd::transport_publish::v5` | daemon transport-publish request, job, outcome, and capability DTOs | | `schema` | schema IDs, module generations, descriptors, and aggregate registries | | `profile` | assigned regular commerce kind8890 and replaceable capability kind18890, with closed profile identities; authoring qualification remains pending | -| `terms` (`terms` feature) | explicit bounded private Terms v1 disclosure and its domain-separated digest; no parser, authenticated consent, stock or signing authority | +| `terms` (`terms` feature) | bounded closed Terms v1 decoding, explicit protected encoding and domain-separated digest; no authenticated consent, stock or signing authority | | `command` (`commands` feature) | bounded closed v1 inquiry/reply data codec and exact command/approval-intent hashes | | `nip01` (`nip01` feature) | exact bounded canonical preimages, IDs and complete-event sizes | | `intent` (`intent` feature) | exact v1 signing commitment data without execution authority | @@ -77,7 +77,7 @@ with at most nine tags and19 fields shared by signer and storage admission. | `intent` | no | enables pure domain-separated v1 signing commitment data | | `chat` | no | enables commands, NIP-01 and the bounded known-kind chat/plan data profile | | `listing` | no | enables portable complete listing input and exact public profile/event production | -| `terms` | no | enables the private canonical Terms encoder over validated domain data, without record authoring | +| `terms` | no | enables the closed private Terms codec over validated domain data, without record authoring | Terms encoding preserves complete source snapshots, resolved prices, private fulfillment and explicit supply commitments. It counts the escaped UTF-8 output @@ -89,6 +89,14 @@ record; fitting Terms alone supplies no complete-record or nested-wrap proof. redacted diagnostics provide no participant approval, authenticated source, reservation or installed agreement. +`terms::decode` admits at most16KiB and depth16, requiring closed objects, +explicit nullable fields and bounded line/group arrays. It checks duplicates +before acceptance and runs the shared domain constructors for every value. +Private text is borrowed from the caller's original frame until explicitly +decoded into zeroizing buffers; only public snapshots enter temporary JSON +trees. Decoding a claim establishes no signature, consent or current source +availability. Callers retain responsibility for protecting original bytes. + The listing producer emits one canonical `radroots.listing` version-1 profile, explicit default units and no fabricated price. Paused/withdrawn projections keep the same addressable coordinate, state non-availability in summary and diff --git a/crates/protocol/src/capability/v1.rs b/crates/protocol/src/capability/v1.rs @@ -372,6 +372,7 @@ impl std::error::Error for Error {} #[cfg(test)] mod tests { use super::*; + use alloc::borrow::ToOwned; #[test] fn catalog_and_schema_registry_validate() { diff --git a/crates/protocol/src/command.rs b/crates/protocol/src/command.rs @@ -412,7 +412,9 @@ pub(crate) fn check_frame(raw: &[u8]) -> Result<(), CommandError> { // 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> { +pub(crate) 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; diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs @@ -13,6 +13,9 @@ pub mod command; #[cfg(feature = "terms")] pub mod terms; +#[cfg(any(feature = "listing", feature = "terms"))] +mod listing_values; + /// Pure exact v1 signing-commitment data, without execution authority. #[cfg(feature = "intent")] pub mod intent; diff --git a/crates/protocol/src/listing/input.rs b/crates/protocol/src/listing/input.rs @@ -2,12 +2,9 @@ //! value invariant owner; no unknown field or unsupported feature is discarded. use super::PublishInput; use crate::command::{CommandError, check_frame, required_nullable}; +use crate::listing_values::{OptionInput, RawProduct}; use alloc::{string::String, vec::Vec}; -use radroots_domain::{ - AuthorityRef, ContentMeasure, Decimal, DiscountBps, FixedPrice, ListingOptionId, Money, - PositiveDecimal, PriceTier, PublicKey, Quantity, TimeZoneId, UnixSeconds, VariableWeight, - Window, listing::*, -}; +use radroots_domain::{AuthorityRef, ListingOptionId, UnixSeconds, listing::*}; use serde::Deserialize; #[derive(Deserialize)] @@ -51,166 +48,6 @@ enum State { } #[derive(Deserialize)] #[serde(deny_unknown_fields)] -struct RawProduct { - name: String, - description: String, - #[serde(deserialize_with = "required_nullable")] - producer: Option<PublicKey>, - #[serde(deserialize_with = "required_nullable")] - origin_summary: Option<String>, -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct OptionInput { - id: ListingOptionId, - label: String, - unit: Unit, - increment: PositiveDecimal, - minimum: PositiveDecimal, - price: RawPrice, - supply: RawSupply, - lead_seconds: LeadSeconds, -} -#[derive(Deserialize)] -#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] -enum Unit { - Measured { unit: Measure }, - Package { label: String, contents: Contents }, -} -#[derive(Deserialize)] -enum Measure { - #[serde(rename = "g")] - Gram, - #[serde(rename = "kg")] - Kilogram, - #[serde(rename = "mL")] - Millilitre, - #[serde(rename = "L")] - Litre, - #[serde(rename = "each")] - Each, -} -impl Measure { - fn domain(self) -> MeasurementUnit { - match self { - Self::Gram => MeasurementUnit::Gram, - Self::Kilogram => MeasurementUnit::Kilogram, - Self::Millilitre => MeasurementUnit::Millilitre, - Self::Litre => MeasurementUnit::Litre, - Self::Each => MeasurementUnit::Each, - } - } -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct RawQuantity { - amount: Decimal, - unit: Measure, -} -impl RawQuantity { - fn domain(self) -> Result<Quantity, CommandError> { - invalid(Quantity::new(self.amount, self.unit.domain())) - } -} -#[derive(Deserialize)] -#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] -enum Contents { - Fixed { quantity: RawQuantity }, - Estimated { quantity: RawQuantity }, - Unspecified, -} -#[derive(Deserialize)] -#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] -enum RawPrice { - Fixed { - rate: Money, - basis: PositiveDecimal, - discount_bps: u16, - tiers: Vec<RawTier>, - }, - QuoteRequired, - VariableWeight { - measurement_unit: Measure, - minimum_per_sale_unit: PositiveDecimal, - maximum_per_sale_unit: PositiveDecimal, - rate: Money, - basis: PositiveDecimal, - maximum_per_sale_unit_total: Money, - }, -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct RawTier { - from: Decimal, - rate: Money, -} -impl RawPrice { - fn domain(self) -> Result<Price, CommandError> { - match self { - Self::QuoteRequired => Ok(Price::QuoteRequired), - Self::Fixed { - rate, - basis, - discount_bps, - tiers, - } => Ok(Price::Fixed(invalid(FixedPrice::new( - rate, - basis, - invalid(DiscountBps::new(discount_bps))?, - tiers - .into_iter() - .map(|tier| PriceTier::new(tier.from, tier.rate)) - .collect(), - ))?)), - Self::VariableWeight { - measurement_unit, - minimum_per_sale_unit, - maximum_per_sale_unit, - rate, - basis, - maximum_per_sale_unit_total, - } => Ok(Price::VariableWeight(invalid(VariableWeight::new( - measurement_unit.domain(), - minimum_per_sale_unit, - maximum_per_sale_unit, - rate, - basis, - maximum_per_sale_unit_total, - ))?)), - } - } -} -#[derive(Deserialize)] -#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] -enum RawSupply { - Unknown, - Available { - amount: Decimal, - }, - Estimated { - amount: Decimal, - #[serde(deserialize_with = "required_nullable")] - window: Option<RawWindow>, - }, -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct RawWindow { - start: UnixSeconds, - end: UnixSeconds, - timezone: String, -} -impl RawWindow { - fn domain(self) -> Result<Window, CommandError> { - invalid(Window::new( - self.start, - self.end, - invalid(TimeZoneId::from_name(&self.timezone))?, - )) - } -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] struct Fulfillment { modes: Vec<Mode>, area: String, @@ -232,49 +69,13 @@ impl Input { if profile.profile != "radroots.listing" || profile.version != 1 { return Err(CommandError::UnsupportedProfile); } - let product = invalid(Product::new( - &profile.product.name, - &profile.product.description, - profile.product.producer, - profile.product.origin_summary.as_deref(), - ))?; + let product = profile.product.domain()?; if profile.options.is_empty() || profile.options.len() > 16 { return Err(CommandError::LimitExceeded); } let mut options = Vec::with_capacity(profile.options.len()); for option in profile.options { - let unit = match option.unit { - Unit::Measured { unit } => SaleUnit::measured(unit.domain()), - Unit::Package { label, contents } => { - let contents = match contents { - Contents::Fixed { quantity } => ContentMeasure::Fixed { - quantity: quantity.domain()?, - }, - Contents::Estimated { quantity } => ContentMeasure::Estimated { - quantity: quantity.domain()?, - }, - Contents::Unspecified => ContentMeasure::Unspecified, - }; - invalid(SaleUnit::package(&label, contents))? - } - }; - options.push(invalid(ListingOption::new( - option.id, - &option.label, - unit, - option.increment, - option.minimum, - option.price.domain()?, - match option.supply { - RawSupply::Unknown => Supply::Unknown, - RawSupply::Available { amount } => Supply::Available { amount }, - RawSupply::Estimated { amount, window } => Supply::Estimated { - amount, - window: window.map(RawWindow::domain).transpose()?, - }, - }, - option.lead_seconds, - ))?); + options.push(option.domain()?); } let fulfillment = invalid(PublicFulfillment::new( profile @@ -405,30 +206,7 @@ fn object_shapes(value: &serde_json::Value) -> Result<(), CommandError> { return Err(CommandError::LimitExceeded); } for option in options { - object(option)?; - object(&option["unit"])?; - object(&option["price"])?; - object(&option["supply"])?; - if let Some(window) = option["supply"].get("window") - && !window.is_null() - { - object(window)?; - } - if let Some(contents) = option["unit"].get("contents") { - object(contents)?; - if let Some(quantity) = contents.get("quantity") { - object(quantity)?; - } - } - if let Some(tiers) = option["price"].get("tiers") { - let tiers = tiers.as_array().ok_or(CommandError::InvalidInput)?; - if tiers.len() > FixedPrice::MAX_TIERS { - return Err(CommandError::LimitExceeded); - } - for tier in tiers { - object(tier)?; - } - } + crate::listing_values::option_shape(option)?; } Ok(()) } diff --git a/crates/protocol/src/listing_values.rs b/crates/protocol/src/listing_values.rs @@ -0,0 +1,301 @@ +//! Shared public snapshot decoding. Private Terms never enter these JSON trees. +use crate::command::CommandError; +#[cfg(feature = "terms")] +use crate::command::parse_object; +use crate::command::required_nullable; +use alloc::{string::String, vec::Vec}; +use radroots_domain::{ + ContentMeasure, Decimal, DiscountBps, FixedPrice, ListingOptionId, Money, PositiveDecimal, + PriceTier, PublicKey, Quantity, TimeZoneId, UnixSeconds, VariableWeight, Window, listing::*, +}; +use serde::Deserialize; +#[cfg(feature = "terms")] +use serde_json::value::RawValue; +fn invalid<T, E>(value: Result<T, E>) -> Result<T, CommandError> { + value.map_err(|_| CommandError::InvalidInput) +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct RawProduct { + name: String, + description: String, + #[serde(deserialize_with = "required_nullable")] + producer: Option<PublicKey>, + #[serde(deserialize_with = "required_nullable")] + origin_summary: Option<String>, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct OptionInput { + id: ListingOptionId, + label: String, + unit: Unit, + increment: PositiveDecimal, + minimum: PositiveDecimal, + price: RawPrice, + supply: RawSupply, + lead_seconds: LeadSeconds, +} +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +enum Unit { + Measured { unit: Measure }, + Package { label: String, contents: Contents }, +} +#[derive(Deserialize)] +enum Measure { + #[serde(rename = "g")] + Gram, + #[serde(rename = "kg")] + Kilogram, + #[serde(rename = "mL")] + Millilitre, + #[serde(rename = "L")] + Litre, + #[serde(rename = "each")] + Each, +} +impl Measure { + fn domain(self) -> MeasurementUnit { + match self { + Self::Gram => MeasurementUnit::Gram, + Self::Kilogram => MeasurementUnit::Kilogram, + Self::Millilitre => MeasurementUnit::Millilitre, + Self::Litre => MeasurementUnit::Litre, + Self::Each => MeasurementUnit::Each, + } + } +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawQuantity { + amount: Decimal, + unit: Measure, +} +impl RawQuantity { + fn domain(self) -> Result<Quantity, CommandError> { + invalid(Quantity::new(self.amount, self.unit.domain())) + } +} +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +enum Contents { + Fixed { quantity: RawQuantity }, + Estimated { quantity: RawQuantity }, + Unspecified, +} +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +enum RawPrice { + Fixed { + rate: Money, + basis: PositiveDecimal, + discount_bps: u16, + tiers: Vec<RawTier>, + }, + QuoteRequired, + VariableWeight { + measurement_unit: Measure, + minimum_per_sale_unit: PositiveDecimal, + maximum_per_sale_unit: PositiveDecimal, + rate: Money, + basis: PositiveDecimal, + maximum_per_sale_unit_total: Money, + }, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawTier { + from: Decimal, + rate: Money, +} +impl RawPrice { + fn domain(self) -> Result<Price, CommandError> { + match self { + Self::QuoteRequired => Ok(Price::QuoteRequired), + Self::Fixed { + rate, + basis, + discount_bps, + tiers, + } => Ok(Price::Fixed(invalid(FixedPrice::new( + rate, + basis, + invalid(DiscountBps::new(discount_bps))?, + tiers + .into_iter() + .map(|tier| PriceTier::new(tier.from, tier.rate)) + .collect(), + ))?)), + Self::VariableWeight { + measurement_unit, + minimum_per_sale_unit, + maximum_per_sale_unit, + rate, + basis, + maximum_per_sale_unit_total, + } => Ok(Price::VariableWeight(invalid(VariableWeight::new( + measurement_unit.domain(), + minimum_per_sale_unit, + maximum_per_sale_unit, + rate, + basis, + maximum_per_sale_unit_total, + ))?)), + } + } +} +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +enum RawSupply { + Unknown, + Available { + amount: Decimal, + }, + Estimated { + amount: Decimal, + #[serde(deserialize_with = "required_nullable")] + window: Option<RawWindow>, + }, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct RawWindow { + start: UnixSeconds, + end: UnixSeconds, + timezone: String, +} +impl RawWindow { + fn domain(self) -> Result<Window, CommandError> { + invalid(Window::new( + self.start, + self.end, + invalid(TimeZoneId::from_name(&self.timezone))?, + )) + } +} +impl RawProduct { + pub(crate) fn domain(self) -> Result<Product, CommandError> { + invalid(Product::new( + &self.name, + &self.description, + self.producer, + self.origin_summary.as_deref(), + )) + } +} +impl OptionInput { + pub(crate) fn domain(self) -> Result<ListingOption, CommandError> { + let unit = match self.unit { + Unit::Measured { unit } => SaleUnit::measured(unit.domain()), + Unit::Package { label, contents } => { + let contents = match contents { + Contents::Fixed { quantity } => ContentMeasure::Fixed { + quantity: quantity.domain()?, + }, + Contents::Estimated { quantity } => ContentMeasure::Estimated { + quantity: quantity.domain()?, + }, + Contents::Unspecified => ContentMeasure::Unspecified, + }; + invalid(SaleUnit::package(&label, contents))? + } + }; + invalid(ListingOption::new( + self.id, + &self.label, + unit, + self.increment, + self.minimum, + self.price.domain()?, + match self.supply { + RawSupply::Unknown => Supply::Unknown, + RawSupply::Available { amount } => Supply::Available { amount }, + RawSupply::Estimated { amount, window } => Supply::Estimated { + amount, + window: window.map(RawWindow::domain).transpose()?, + }, + }, + self.lead_seconds, + )) + } +} +pub(crate) fn object(value: &serde_json::Value) -> Result<(), CommandError> { + if value.is_object() { + Ok(()) + } else { + Err(CommandError::InvalidInput) + } +} +pub(crate) fn option_shape(option: &serde_json::Value) -> Result<(), CommandError> { + object(option)?; + object(&option["unit"])?; + object(&option["price"])?; + object(&option["supply"])?; + if let Some(window) = option["supply"].get("window") + && !window.is_null() + { + object(window)?; + } + if let Some(contents) = option["unit"].get("contents") { + object(contents)?; + if let Some(quantity) = contents.get("quantity") { + object(quantity)?; + } + } + if let Some(tiers) = option["price"].get("tiers") { + let tiers = tiers.as_array().ok_or(CommandError::InvalidInput)?; + if tiers.len() > FixedPrice::MAX_TIERS { + return Err(CommandError::LimitExceeded); + } + for tier in tiers { + object(tier)?; + } + } + Ok(()) +} + +#[cfg(feature = "terms")] +pub(crate) fn product(raw: &RawValue) -> Result<Product, CommandError> { + parse_object::<RawProduct>(raw.get().as_bytes())?.domain() +} +#[cfg(feature = "terms")] +pub(crate) fn option(raw: &RawValue) -> Result<ListingOption, CommandError> { + let value: serde_json::Value = + serde_json::from_str(raw.get()).map_err(|_| CommandError::InvalidInput)?; + option_shape(&value)?; + for (path, supported) in [ + ( + "/price/type", + &["quote_required", "fixed", "variable_weight"][..], + ), + ("/supply/type", &["unknown", "available", "estimated"][..]), + ("/unit/type", &["measured", "package"][..]), + ( + "/unit/contents/type", + &["unspecified", "fixed", "estimated"][..], + ), + ] { + if value + .pointer(path) + .and_then(serde_json::Value::as_str) + .is_some_and(|tag| !supported.contains(&tag)) + { + return Err(CommandError::UnsupportedProfile); + } + } + for path in [ + "/unit/unit", + "/unit/contents/quantity/unit", + "/price/measurement_unit", + ] { + if value + .pointer(path) + .and_then(serde_json::Value::as_str) + .is_some_and(|unit| !["g", "kg", "mL", "L", "each"].contains(&unit)) + { + return Err(CommandError::UnsupportedProfile); + } + } + parse_object::<OptionInput>(raw.get().as_bytes())?.domain() +} diff --git a/crates/protocol/src/radrootsd/transport_publish/v5.rs b/crates/protocol/src/radrootsd/transport_publish/v5.rs @@ -1164,6 +1164,7 @@ pub fn schema_registry() -> Result<Registry, crate::schema::Error> { #[cfg(test)] mod tests { use super::*; + use alloc::string::ToString; fn request() -> EventRequest { EventRequest { diff --git a/crates/protocol/src/runtime/v1.rs b/crates/protocol/src/runtime/v1.rs @@ -1182,6 +1182,7 @@ impl std::error::Error for Error {} #[cfg(test)] mod tests { use super::*; + use alloc::borrow::ToOwned; #[test] fn catalog_is_unique_and_preserves_every_v1_operation() { diff --git a/crates/protocol/src/terms.rs b/crates/protocol/src/terms.rs @@ -11,6 +11,9 @@ use zeroize::Zeroizing; mod writer; use writer::Writer; +mod decode; +mod text; +pub use decode::decode; /// Private content budget. A complete record additionally includes its header; /// fitting this Terms object alone does not prove that a record or rumor fits. diff --git a/crates/protocol/src/terms/decode.rs b/crates/protocol/src/terms/decode.rs @@ -0,0 +1,371 @@ +//! Closed data decoding. No source, participant, authority or consent is admitted. +use super::{TERMS_MAX_BYTES, TermsWireError, text}; +use crate::{ + command::{CommandError, check_frame, object, parse_object, required_nullable}, + listing_values, +}; +use alloc::{string::String, vec::Vec}; +use core::{fmt, marker::PhantomData}; +use radroots_domain::{ + AgreedFixedPrice, AgreementLine, AgreementLineId, AgreementPrice, Decimal, DiscountBps, + EnvelopeEventId, FulfillmentGroup, FulfillmentGroupId, FuturePromise, ListingOptionId, Money, + PositiveDecimal, PrivateFulfillment, PublicKey, SupplyCommitment, Terms, TimeZoneId, + UnixSeconds, VariableWeight, Window, + listing::{FulfillmentMode, ListingCoordinate, ListingId, ListingRevision, MeasurementUnit}, +}; +use serde::{ + Deserialize, + de::{IgnoredAny, SeqAccess, Visitor}, +}; +use serde_json::value::RawValue; + +/// Decodes bounded closed Terms claims and checks every domain constructor. +/// Original private bytes belong to the caller. No signature, approval, current +/// source availability, stock backing or application permission is established. +pub fn decode(raw: &[u8]) -> Result<Terms, TermsWireError> { + if raw.len() > TERMS_MAX_BYTES { + return Err(TermsWireError::LimitExceeded); + } + check_frame(raw).map_err(command_error)?; + let value: RawTerms<'_> = parse_object(raw).map_err(command_error)?; + if value.cancellation != "mutual_residual_v1" || value.rounding != "half_even_net_line_v1" { + return Err(TermsWireError::UnsupportedProfile); + } + let lines = value + .lines + .0 + .into_iter() + .map(line) + .collect::<Result<Vec<_>, _>>()?; + let groups = value + .fulfillment + .0 + .into_iter() + .map(group) + .collect::<Result<Vec<_>, _>>()?; + invalid(Terms::new( + value.buyer, + value.seller, + lines, + groups, + money(value.fulfillment_charge)?, + money(value.maximum_total)?, + supply(value.supply)?, + )) +} +fn invalid<T, E>(result: Result<T, E>) -> Result<T, TermsWireError> { + result.map_err(|_| TermsWireError::InvalidInput) +} +fn command_error(error: CommandError) -> TermsWireError { + match error { + CommandError::LimitExceeded => TermsWireError::LimitExceeded, + CommandError::UnsupportedProfile => TermsWireError::UnsupportedProfile, + _ => TermsWireError::InvalidInput, + } +} +fn parse<'a, T: Deserialize<'a>>(raw: &'a RawValue) -> Result<T, TermsWireError> { + parse_object(raw.get().as_bytes()).map_err(command_error) +} + +// Retain only bounded references into the caller's already byte/depth-bounded +// frame. An excessive element is ignored without constructing its value. +struct RawArray<'a, const N: usize>(Vec<&'a RawValue>); +impl<'de: 'a, 'a, const N: usize> Deserialize<'de> for RawArray<'a, N> { + fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> { + struct ArrayVisitor<'a, const N: usize>(PhantomData<&'a ()>); + impl<'de: 'a, 'a, const N: usize> Visitor<'de> for ArrayVisitor<'a, N> { + type Value = RawArray<'a, N>; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a bounded array") + } + fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> { + let mut values = Vec::new(); + loop { + if values.len() == N { + if seq.next_element::<IgnoredAny>()?.is_some() { + return Err(serde::de::Error::custom("array limit exceeded")); + } + break; + } + let Some(value) = seq.next_element::<&'de RawValue>()? else { + break; + }; + values.push(value); + } + Ok(RawArray(values)) + } + } + d.deserialize_seq(ArrayVisitor::<N>(PhantomData)) + } +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawTerms<'a> { + buyer: PublicKey, + seller: PublicKey, + #[serde(borrow)] + lines: RawArray<'a, 32>, + #[serde(borrow)] + fulfillment: RawArray<'a, 8>, + #[serde(borrow)] + fulfillment_charge: &'a RawValue, + #[serde(borrow)] + maximum_total: &'a RawValue, + #[serde(borrow)] + supply: &'a RawValue, + cancellation: String, + rounding: String, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawLine<'a> { + id: AgreementLineId, + #[serde(borrow)] + source: &'a RawValue, + option_id: ListingOptionId, + #[serde(borrow)] + product: &'a RawValue, + #[serde(borrow)] + option: &'a RawValue, + amount: PositiveDecimal, + fulfillment_group: FulfillmentGroupId, + #[serde(borrow, deserialize_with = "required_nullable")] + source_lot_label: Option<&'a RawValue>, + #[serde(borrow)] + price: &'a RawValue, + #[serde(borrow)] + maximum_line_total: &'a RawValue, +} +fn line(raw: &RawValue) -> Result<AgreementLine, TermsWireError> { + let value: RawLine<'_> = parse(raw)?; + let lot = value + .source_lot_label + .map(|v| text::decode(v.get(), 120)) + .transpose()?; + invalid(AgreementLine::new( + value.id, + source(value.source)?, + value.option_id, + listing_values::product(value.product).map_err(command_error)?, + listing_values::option(value.option).map_err(command_error)?, + value.amount, + value.fulfillment_group, + lot.as_deref().map(String::as_str), + price(value.price)?, + money(value.maximum_line_total)?, + )) +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawSource { + #[serde(deserialize_with = "object")] + coordinate: RawCoordinate, + event_id: EnvelopeEventId, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawCoordinate { + kind: u16, + author: PublicKey, + d: ListingId, +} +fn source(raw: &RawValue) -> Result<ListingRevision, TermsWireError> { + let value: RawSource = parse(raw)?; + if value.coordinate.kind != 30402 { + return Err(TermsWireError::InvalidInput); + } + Ok(ListingRevision::new( + ListingCoordinate::new(value.coordinate.author, value.coordinate.d), + value.event_id, + )) +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawMoney<'a> { + #[serde(borrow)] + currency: &'a RawValue, + #[serde(borrow)] + minor: &'a RawValue, + exponent: u8, +} +fn money(raw: &RawValue) -> Result<Money, TermsWireError> { + let value: RawMoney<'_> = parse(raw)?; + let code = text::decode(value.currency.get(), 3)?; + let minor = text::decode(value.minor.get(), 15)?; + invalid(Money::from_parts(&code, &minor, value.exponent)) +} +#[derive(Deserialize)] +struct Tag { + #[serde(rename = "type")] + kind: String, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawFixed<'a> { + #[serde(rename = "type")] + kind: String, + #[serde(borrow)] + rate: &'a RawValue, + basis: PositiveDecimal, + discount_bps: u16, + #[serde(deserialize_with = "required_nullable")] + selected_tier_from: Option<Decimal>, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawVariable<'a> { + #[serde(rename = "type")] + kind: String, + measurement_unit: String, + minimum: PositiveDecimal, + maximum: PositiveDecimal, + #[serde(borrow)] + rate: &'a RawValue, + basis: PositiveDecimal, + #[serde(borrow)] + maximum_total: &'a RawValue, +} +fn measurement_unit(value: &str) -> Result<MeasurementUnit, TermsWireError> { + match value { + "g" => Ok(MeasurementUnit::Gram), + "kg" => Ok(MeasurementUnit::Kilogram), + "mL" => Ok(MeasurementUnit::Millilitre), + "L" => Ok(MeasurementUnit::Litre), + "each" => Ok(MeasurementUnit::Each), + _ => Err(TermsWireError::UnsupportedProfile), + } +} +fn price(raw: &RawValue) -> Result<AgreementPrice, TermsWireError> { + let tag: Tag = parse(raw)?; + match tag.kind.as_str() { + "fixed" => { + let value: RawFixed<'_> = parse(raw)?; + if value.kind != "fixed" { + return Err(TermsWireError::InvalidInput); + } + Ok(AgreementPrice::Fixed(AgreedFixedPrice::new( + money(value.rate)?, + value.basis, + invalid(DiscountBps::new(value.discount_bps))?, + value.selected_tier_from, + ))) + } + "variable_weight" => { + let value: RawVariable<'_> = parse(raw)?; + if value.kind != "variable_weight" { + return Err(TermsWireError::InvalidInput); + } + Ok(AgreementPrice::VariableWeight(invalid( + VariableWeight::new( + measurement_unit(&value.measurement_unit)?, + value.minimum, + value.maximum, + money(value.rate)?, + value.basis, + money(value.maximum_total)?, + ), + )?)) + } + _ => Err(TermsWireError::UnsupportedProfile), + } +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawGroup<'a> { + id: FulfillmentGroupId, + #[serde(borrow)] + terms: &'a RawValue, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawFulfillment<'a> { + mode: String, + #[serde(borrow)] + window: &'a RawValue, + #[serde(borrow)] + address: &'a RawValue, + #[serde(borrow)] + instructions: &'a RawValue, + #[serde(borrow, deserialize_with = "required_nullable")] + contact: Option<&'a RawValue>, +} +fn group(raw: &RawValue) -> Result<FulfillmentGroup, TermsWireError> { + let value: RawGroup<'_> = parse(raw)?; + let terms: RawFulfillment<'_> = parse(value.terms)?; + let address = text::decode(terms.address.get(), 2048)?; + let instructions = text::decode(terms.instructions.get(), 2048)?; + let contact = terms + .contact + .map(|v| text::decode(v.get(), 256)) + .transpose()?; + Ok(FulfillmentGroup::new( + value.id, + invalid(PrivateFulfillment::new( + match terms.mode.as_str() { + "pickup" => FulfillmentMode::Pickup, + "delivery" => FulfillmentMode::Delivery, + _ => return Err(TermsWireError::UnsupportedProfile), + }, + window(terms.window)?, + &address, + &instructions, + contact.as_deref().map(String::as_str), + ))?, + )) +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawWindow<'a> { + start: UnixSeconds, + end: UnixSeconds, + #[serde(borrow)] + timezone: &'a RawValue, +} +fn window(raw: &RawValue) -> Result<Window, TermsWireError> { + let value: RawWindow<'_> = parse(raw)?; + let zone = text::decode(value.timezone.get(), 80)?; + invalid(Window::new( + value.start, + value.end, + invalid(TimeZoneId::from_name(&zone))?, + )) +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Stock { + #[serde(rename = "type")] + kind: String, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Future<'a> { + #[serde(rename = "type")] + kind: String, + #[serde(borrow)] + expected_window: &'a RawValue, + #[serde(borrow)] + risk_disclosure: &'a RawValue, +} +fn supply(raw: &RawValue) -> Result<SupplyCommitment, TermsWireError> { + let tag: Tag = parse(raw)?; + match tag.kind.as_str() { + "stock_backed" => { + let value: Stock = parse(raw)?; + if value.kind != "stock_backed" { + return Err(TermsWireError::InvalidInput); + } + Ok(SupplyCommitment::StockBacked) + } + "future_promise" => { + let value: Future<'_> = parse(raw)?; + if value.kind != "future_promise" { + return Err(TermsWireError::InvalidInput); + } + let risk = text::decode(value.risk_disclosure.get(), 512)?; + Ok(SupplyCommitment::FuturePromise(invalid( + FuturePromise::new(window(value.expected_window)?, &risk), + )?)) + } + _ => Err(TermsWireError::UnsupportedProfile), + } +} diff --git a/crates/protocol/src/terms/text.rs b/crates/protocol/src/terms/text.rs @@ -0,0 +1,136 @@ +//! Decode a private JSON string without a nonzeroizing decoded scratch buffer. +use super::TermsWireError; +use alloc::string::String; +use zeroize::Zeroizing; + +pub(super) fn decode(raw: &str, maximum_chars: usize) -> Result<Zeroizing<String>, TermsWireError> { + let mut bytes = 0usize; + let mut count = 0usize; + visit(raw, |ch| { + count += 1; + if count > maximum_chars { + return Err(TermsWireError::LimitExceeded); + } + bytes += ch.len_utf8(); + Ok(()) + })?; + let mut output = Zeroizing::new(String::with_capacity(bytes)); + visit(raw, |ch| { + output.push(ch); + Ok(()) + })?; + Ok(output) +} + +fn visit( + raw: &str, + mut emit: impl FnMut(char) -> Result<(), TermsWireError>, +) -> Result<(), TermsWireError> { + let text = raw + .strip_prefix('"') + .and_then(|value| value.strip_suffix('"')) + .ok_or(TermsWireError::InvalidInput)?; + let mut chars = text.chars(); + while let Some(ch) = chars.next() { + if ch == '\\' { + let escaped = chars.next().ok_or(TermsWireError::InvalidInput)?; + let value = match escaped { + '"' => '"', + '\\' => '\\', + '/' => '/', + 'b' => '\u{08}', + 'f' => '\u{0c}', + 'n' => '\n', + 'r' => '\r', + 't' => '\t', + 'u' => { + let first = hex(&mut chars)?; + let code = if (0xd800..=0xdbff).contains(&first) { + if chars.next() != Some('\\') || chars.next() != Some('u') { + return Err(TermsWireError::InvalidInput); + } + let second = hex(&mut chars)?; + if !(0xdc00..=0xdfff).contains(&second) { + return Err(TermsWireError::InvalidInput); + } + 0x10000 + ((u32::from(first) - 0xd800) << 10) + (u32::from(second) - 0xdc00) + } else { + u32::from(first) + }; + char::from_u32(code).ok_or(TermsWireError::InvalidInput)? + } + _ => return Err(TermsWireError::InvalidInput), + }; + emit(value)?; + } else { + if ch == '"' || ch <= '\u{1f}' { + return Err(TermsWireError::InvalidInput); + } + emit(ch)?; + } + } + Ok(()) +} + +fn hex(chars: &mut core::str::Chars<'_>) -> Result<u16, TermsWireError> { + let mut value = 0; + for _ in 0..4 { + let digit = chars + .next() + .and_then(|ch| ch.to_digit(16)) + .ok_or(TermsWireError::InvalidInput)?; + value = (value << 4) | u16::try_from(digit).map_err(|_| TermsWireError::InvalidInput)?; + } + Ok(value) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn private_json_text_matches_independent_literal_and_surrogate_decoding() { + for raw in [ + r#""""#, + r#""plain 🥬 Å A\u030a""#, + r#""\"\\\/\b\f\n\r\t\u0000\u001f\uD83E\uDD6C""#, + ] { + let expected: String = serde_json::from_str(raw).unwrap(); + assert_eq!(decode(raw, 2048).unwrap().as_str(), expected); + assert_eq!( + decode(raw, expected.chars().count()).unwrap().as_str(), + expected + ); + if !expected.is_empty() { + assert_eq!( + decode(raw, expected.chars().count() - 1), + Err(TermsWireError::LimitExceeded) + ); + } + } + } + + #[test] + fn private_json_text_rejects_malformed_literals_and_surrogates() { + for raw in [ + "null", + "[]", + "\"", + "\"a\"b\"", + "\"\n\"", + r#""\x""#, + r#""\u12""#, + r#""\u000z""#, + r#""\uDC00""#, + r#""\uD800""#, + r#""\uD800x""#, + r#""\uD800\u0041""#, + ] { + assert_eq!( + decode(raw, 2048), + Err(TermsWireError::InvalidInput), + "{raw}" + ); + } + } +} diff --git a/crates/protocol/tests/fixtures/protocol_v1.inventory.json b/crates/protocol/tests/fixtures/protocol_v1.inventory.json @@ -7,7 +7,7 @@ { "module": "capability::v1", "path": "crates/protocol/src/capability/v1.rs", - "sha256": "db2ac595ff4e45652791df49d3e0129afcac57fb568f71c6b7355e083b359ad6", + "sha256": "0907e7b4fc9b8d9c38825518c6f6878ae2fd43f9882373efb6f603b88f4f2631", "types": [ { "rust_path": "radroots_protocol::capability::v1::Availability", @@ -104,7 +104,7 @@ { "module": "radrootsd::transport_publish::v5", "path": "crates/protocol/src/radrootsd/transport_publish/v5.rs", - "sha256": "a562ce9af3fd0e65a31c121c0c73c44a895d45872546c9290c193643b9df8b5b", + "sha256": "1ad9ab4b3de960b8a1c02d68f50028419821143dc94a031ccad421b7b65556b6", "types": [ { "rust_path": "radroots_protocol::radrootsd::transport_publish::v5::AuthCapabilities", @@ -203,7 +203,7 @@ { "module": "runtime::v1", "path": "crates/protocol/src/runtime/v1.rs", - "sha256": "d25db1e8b5beaa017bbed549ccc0ce1a54c34f58de4c636b8a33e6a22b66c17f", + "sha256": "e408748d4be7ef7f50dc02f13e1a20c649154d30a970b4cf4df8ce77c26887e4", "types": [ { "rust_path": "radroots_protocol::runtime::v1::ApprovalRequirement", diff --git a/crates/protocol/tests/package_boundary.rs b/crates/protocol/tests/package_boundary.rs @@ -19,6 +19,8 @@ const VERSIONED_SOURCES: &[&str] = &[ include_str!("../src/profile.rs"), include_str!("../src/terms.rs"), include_str!("../src/terms/writer.rs"), + include_str!("../src/terms/decode.rs"), + include_str!("../src/terms/text.rs"), include_str!("../src/command.rs"), include_str!("../src/nip01.rs"), include_str!("../src/intent.rs"), @@ -27,6 +29,7 @@ const VERSIONED_SOURCES: &[&str] = &[ include_str!("../src/chat/plan.rs"), include_str!("../src/listing.rs"), include_str!("../src/listing/input.rs"), + include_str!("../src/listing_values.rs"), include_str!("../src/listing/command.rs"), include_str!("../src/listing/plan.rs"), include_str!("../src/plan.rs"), @@ -38,6 +41,14 @@ fn terms_contract_binds_limits_hash_domain_and_packaged_independent_fixtures() { use sha2::{Digest as _, Sha256}; let contract: serde_json::Value = serde_json::from_str(TERMS_CONTRACT).unwrap(); assert_eq!(contract["schema"], "radroots.terms.codec.v1"); + assert_eq!(contract["decoding"]["objects_only"], true); + assert_eq!(contract["decoding"]["max_json_depth"], 16); + assert_eq!(contract["decoding"]["max_lines"], 32); + assert_eq!(contract["decoding"]["max_fulfillment_groups"], 8); + assert_eq!( + contract["limits"]["authenticated_admission_implemented_by_this_contract"], + false + ); assert_eq!( contract["content_max_utf8_bytes"], radroots_protocol::terms::TERMS_MAX_BYTES diff --git a/crates/protocol/tests/terms_decode.rs b/crates/protocol/tests/terms_decode.rs @@ -0,0 +1,292 @@ +#![cfg(feature = "terms")] +use radroots_protocol::terms::{EncodedTerms, TermsWireError, decode}; +use serde_json::{Value, json}; + +fn fixtures() -> Value { + serde_json::from_str(include_str!("fixtures/terms_wire.v1.json")).unwrap() +} +fn example(index: usize) -> Value { + serde_json::from_str(fixtures()["vectors"][index]["wire"].as_str().unwrap()).unwrap() +} +fn bytes(value: &Value) -> Vec<u8> { + serde_json::to_vec(value).unwrap() +} + +#[test] +fn independently_authored_complete_terms_decode_and_reencode_without_changed_bytes_or_digests() { + for vector in fixtures()["vectors"].as_array().unwrap() { + let wire = vector["wire"].as_str().unwrap(); + let terms = decode(wire.as_bytes()).unwrap(); + let encoded = EncodedTerms::capture(&terms).unwrap(); + assert_eq!(encoded.protected_wire(), wire.as_bytes()); + assert_eq!( + encoded.digest().to_string(), + vector["terms_digest"].as_str().unwrap() + ); + let pretty = + serde_json::to_string_pretty(&serde_json::from_str::<Value>(wire).unwrap()).unwrap(); + if pretty.len() <= 16_384 { + assert_eq!( + EncodedTerms::capture(&decode(pretty.as_bytes()).unwrap()) + .unwrap() + .digest(), + encoded.digest() + ); + } + } +} + +#[test] +fn every_terms_object_boundary_is_closed_required_and_object_only() { + for (index, paths) in [ + ( + 0, + vec![ + "", + "/lines/0", + "/lines/0/source", + "/lines/0/source/coordinate", + "/lines/0/product", + "/lines/0/option", + "/lines/0/option/unit", + "/lines/0/option/unit/contents", + "/lines/0/option/unit/contents/quantity", + "/lines/0/option/price", + "/lines/0/option/price/rate", + "/lines/0/option/price/tiers/0", + "/lines/0/option/price/tiers/0/rate", + "/lines/0/option/supply", + "/lines/0/option/supply/window", + "/lines/0/price", + "/lines/0/price/rate", + "/lines/0/maximum_line_total", + "/fulfillment/0", + "/fulfillment/0/terms", + "/fulfillment/0/terms/window", + "/fulfillment_charge", + "/maximum_total", + "/supply", + ], + ), + ( + 1, + vec![ + "/lines/0/option/price", + "/lines/0/option/price/rate", + "/lines/0/option/price/maximum_per_sale_unit_total", + "/lines/0/price", + "/lines/0/price/rate", + "/lines/0/price/maximum_total", + "/supply", + "/supply/expected_window", + ], + ), + ] { + let original = example(index); + for path in paths { + let fields = original.pointer(path).unwrap().as_object().unwrap(); + let mut positional = original.clone(); + *positional.pointer_mut(path).unwrap() = + Value::Array(fields.values().cloned().collect()); + assert!( + decode(&bytes(&positional)).is_err(), + "positional {index}:{path}" + ); + let mut extra = original.clone(); + extra + .pointer_mut(path) + .unwrap() + .as_object_mut() + .unwrap() + .insert("unexpected".into(), json!(null)); + assert!(decode(&bytes(&extra)).is_err(), "unknown {index}:{path}"); + for key in fields.keys() { + let mut missing = original.clone(); + missing + .pointer_mut(path) + .unwrap() + .as_object_mut() + .unwrap() + .remove(key); + assert!( + decode(&bytes(&missing)).is_err(), + "missing {index}:{path}/{key}" + ); + // Duplicate the field in its exact object before inserting it + // into the surrounding fixture; no Value parser may erase it. + let object = if path.is_empty() { + serde_json::to_string(&original).unwrap() + } else { + serde_json::to_string(original.pointer(path).unwrap()).unwrap() + }; + let duplicate = format!( + "{{{}:{},{}", + serde_json::to_string(key).unwrap(), + serde_json::to_string(&fields[key]).unwrap(), + &object[1..] + ); + let mut template = original.clone(); + *template.pointer_mut(path).unwrap() = json!("__TERMS_NEGATIVE_TARGET__"); + let altered = serde_json::to_string(&template) + .unwrap() + .replace("\"__TERMS_NEGATIVE_TARGET__\"", &duplicate); + assert!( + decode(altered.as_bytes()).is_err(), + "duplicate {index}:{path}/{key}" + ); + } + } + } +} + +#[test] +fn private_text_decodes_escaped_unicode_without_normalizing_it_or_omitting_explicit_nulls() { + let original = example(0); + let wire = serde_json::to_string(&original).unwrap(); + let escaped = wire.replace("🥬", r"\uD83E\uDD6C").replace("Å", r"\u00c5"); + assert_ne!(wire, escaped); + assert_eq!( + EncodedTerms::capture(&decode(wire.as_bytes()).unwrap()) + .unwrap() + .digest(), + EncodedTerms::capture(&decode(escaped.as_bytes()).unwrap()) + .unwrap() + .digest() + ); + for (path, value) in [ + ("/fulfillment/0/terms/address", json!(true)), + ("/fulfillment/0/terms/contact", json!(12)), + ("/lines/0/source_lot_label", json!(false)), + ("/fulfillment/0/terms/instructions", json!("a".repeat(2049))), + ] { + let mut invalid = original.clone(); + *invalid.pointer_mut(path).unwrap() = value; + assert!(decode(&bytes(&invalid)).is_err(), "{path}"); + } +} + +#[test] +fn domain_invariants_and_unsupported_profiles_never_become_silent_fallbacks() { + let original = example(0); + for (path, value) in [ + ("/buyer", original["seller"].clone()), + ("/lines/0/amount", json!("0")), + ("/lines/0/option_id", json!("00".repeat(32))), + ("/lines/0/source/coordinate/kind", json!(95938)), + ( + "/lines/0/source/coordinate/author", + original["buyer"].clone(), + ), + ("/lines/0/price/discount_bps", json!(10001)), + ("/lines/0/maximum_line_total/minor", json!("438")), + ("/maximum_total/minor", json!("465")), + ("/fulfillment_charge/exponent", json!(0)), + ("/fulfillment/0/terms/window/end", json!("300")), + ( + "/fulfillment/0/terms/window/timezone", + json!("invalid/zone"), + ), + ("/lines/0/price/rate/minor", json!(150)), + ("/lines/0/price/basis", json!(1)), + ] { + let mut invalid = original.clone(); + *invalid.pointer_mut(path).unwrap() = value; + assert!(decode(&bytes(&invalid)).is_err(), "{path}"); + } + for path in [ + "/cancellation", + "/rounding", + "/supply/type", + "/lines/0/price/type", + "/lines/0/option/price/type", + "/lines/0/option/supply/type", + "/lines/0/option/unit/type", + "/lines/0/option/unit/contents/type", + "/lines/0/option/unit/contents/quantity/unit", + "/fulfillment/0/terms/mode", + ] { + let mut unknown = original.clone(); + *unknown.pointer_mut(path).unwrap() = json!("future_profile"); + assert!( + matches!( + decode(&bytes(&unknown)), + Err(TermsWireError::UnsupportedProfile) + ), + "{path}" + ); + } + let mut variable = example(1); + variable["lines"][0]["price"]["measurement_unit"] = json!("future_unit"); + assert!(matches!( + decode(&bytes(&variable)), + Err(TermsWireError::UnsupportedProfile) + )); +} + +#[test] +fn public_snapshot_alternatives_preserve_explicit_values_without_invented_defaults() { + for unit in ["g", "kg", "mL", "L", "each"] { + let mut value = example(0); + value["lines"][0]["product"]["producer"] = Value::Null; + value["lines"][0]["product"]["origin_summary"] = Value::Null; + value["lines"][0]["option"]["unit"] = json!({"type":"measured","unit":unit}); + value["lines"][0]["option"]["supply"] = json!({"type":"available","amount":"0"}); + let terms = decode(&bytes(&value)).unwrap(); + let output: Value = + serde_json::from_slice(EncodedTerms::capture(&terms).unwrap().protected_wire()) + .unwrap(); + assert_eq!(output, value); + value["lines"][0]["option"]["unit"]["unit"] = json!("future_unit"); + assert!(matches!( + decode(&bytes(&value)), + Err(TermsWireError::UnsupportedProfile) + )); + } + for unit in ["g", "kg", "mL", "L"] { + let mut value = example(1); + value["lines"][0]["price"]["measurement_unit"] = json!(unit); + let terms = decode(&bytes(&value)).unwrap(); + let output: Value = + serde_json::from_slice(EncodedTerms::capture(&terms).unwrap().protected_wire()) + .unwrap(); + assert_eq!(output, value); + } +} + +#[test] +fn byte_depth_and_collection_budgets_bound_terms_before_domain_materialization() { + let fixture = fixtures(); + let exact = fixture["vectors"] + .as_array() + .unwrap() + .iter() + .find(|v| v["name"] == "exact_content_limit") + .unwrap()["wire"] + .as_str() + .unwrap(); + assert!(decode(exact.as_bytes()).is_ok()); + assert!(matches!( + decode(format!("{exact} ").as_bytes()), + Err(TermsWireError::LimitExceeded) + )); + let original = example(0); + for (field, count) in [("lines", 33), ("fulfillment", 9)] { + let mut invalid = original.clone(); + invalid[field] = Value::Array(vec![Value::Null; count]); + assert!(decode(&bytes(&invalid)).is_err()); + } + for field in ["lines", "fulfillment"] { + let mut invalid = original.clone(); + let duplicate = invalid[field][0].clone(); + invalid[field].as_array_mut().unwrap().push(duplicate); + assert!(decode(&bytes(&invalid)).is_err()); + } + let too_deep = format!("{}0{}", "[".repeat(17), "]".repeat(17)); + assert!(matches!( + decode(too_deep.as_bytes()), + Err(TermsWireError::LimitExceeded) + )); + for raw in [b"{".as_slice(), b"[]", b"null", b"\xff"] { + assert!(decode(raw).is_err()); + } +}