lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

commit d5a8ff3856f98aaa4906341ea00df975d15d25ea
parent b0d26aef0af793e54d01dd2e1e78ea83ae93c60a
Author: triesap <tyson@radroots.org>
Date:   Tue, 20 Oct 2026 11:20:21 +0000

execution: Admit typed public preparations through the shared journal

- Preserve original chat commitments while capturing closed listing commands
- Require seller authority and retain exact encrypted public T0 under the existing owner
- Continue exact legacy chat schemas without rewriting or inventing public effects
- Verify native and browser recovery, explicit refusals, APIs and dependency guards

Diffstat:
Mcontracts/api_baselines/radroots_protocol.txt | 43+++++++++++++++++++++++++++++++++++++++++++
Mcontracts/api_baselines/radroots_storage.txt | 9++++++---
Mcrates/domain/src/listing.rs | 10+++++-----
Mcrates/domain/tests/listing.rs | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/execution/src/error.rs | 1+
Mcrates/execution/src/session/inquiry.rs | 2+-
Mcrates/protocol/README.md | 8++++++++
Mcrates/protocol/src/command.rs | 25++++++++++++++++++-------
Acrates/protocol/src/command/captured.rs | 142+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/protocol/src/listing.rs | 6+++++-
Acrates/protocol/src/listing/command.rs | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/protocol/src/listing/input.rs | 242+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/protocol/tests/public_command.rs | 184+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/radroots/tests/support/receipt_client.rs | 11+++++++----
Mcrates/radroots/tests/support/receipt_delivery.rs | 9+++++++--
Mcrates/radroots/tests/support/receipt_installation_reports.rs | 9++++++---
Mcrates/radroots/tests/support/receipt_issuance.rs | 6+++++-
Mcrates/radroots/tests/support/receipt_snapshots.rs | 2+-
Mcrates/storage/Cargo.toml | 2+-
Mcrates/storage/README.md | 6++++++
Mcrates/storage/src/command.rs | 52+++++++++++++++++++++++++++++++++++++++++++---------
Mcrates/storage/src/command/protected/plan.rs | 2+-
Mcrates/storage/src/command/snapshot.rs | 5+++--
Mcrates/storage_indexeddb/src/workspace/delivery/operations.rs | 2+-
Mcrates/storage_indexeddb/src/workspace/installation.rs | 2+-
Mcrates/storage_indexeddb/src/workspace/installation/codec.rs | 18+++++++++++++-----
Mcrates/storage_indexeddb/src/workspace/journal.rs | 14++++++++------
Mcrates/storage_indexeddb/src/workspace/plans.rs | 10++++++----
Mcrates/storage_indexeddb/src/workspace/retained.rs | 2+-
Mcrates/storage_indexeddb/tests/browser/seller.mjs | 4+++-
Mcrates/storage_indexeddb/tests/browser/src/workspace.rs | 23+++++++++++++++++++++++
Mcrates/storage_indexeddb/tests/browser/src/workspace/delivery.rs | 5++++-
Mcrates/storage_indexeddb/tests/browser/src/workspace/observations.rs | 10++++++++--
Mcrates/storage_indexeddb/tests/browser/src/workspace/plans.rs | 10+++++-----
Mcrates/storage_sqlite/README.md | 8++++++++
Mcrates/storage_sqlite/src/workspace/admission.rs | 28++++++++++++++++++----------
Mcrates/storage_sqlite/src/workspace/delivery/graph_tests.rs | 2+-
Mcrates/storage_sqlite/src/workspace/delivery/operations.rs | 2+-
Mcrates/storage_sqlite/src/workspace/installation.rs | 24+++++++++++++++---------
Mcrates/storage_sqlite/src/workspace/operation.rs | 3++-
Mcrates/storage_sqlite/src/workspace/plan.rs | 2+-
Mcrates/storage_sqlite/src/workspace/snapshot.rs | 2+-
Mcrates/storage_sqlite/src/workspace/tests/mod.rs | 4++--
Mcrates/storage_sqlite/src/workspace/worker.rs | 9++++++---
Acrates/storage_sqlite/tests/support/public_admission.rs | 403+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/tests/support/workspace_issuance.rs | 12++++++++++--
Mcrates/storage_sqlite/tests/support/workspace_plans.rs | 28++++++++++++++++++----------
Mcrates/storage_sqlite/tests/workspace_admission.rs | 26+++++++++++++++++++++++---
48 files changed, 1484 insertions(+), 112 deletions(-)

diff --git a/contracts/api_baselines/radroots_protocol.txt b/contracts/api_baselines/radroots_protocol.txt @@ -139,6 +139,25 @@ pub const radroots_protocol::chat::SIGNED_MAX_BYTES: usize pub fn radroots_protocol::chat::nip44_v2_payload_len(usize) -> core::result::Result<usize, radroots_protocol::nip01::WireError> pub mod radroots_protocol::command pub use radroots_protocol::command::CHAT_MAX_BYTES +pub enum radroots_protocol::command::CapturedCommand +pub radroots_protocol::command::CapturedCommand::Chat(radroots_protocol::command::CapturedChatCommand) +pub radroots_protocol::command::CapturedCommand::Listing(radroots_protocol::listing::CapturedListingCommand) +impl radroots_protocol::command::CapturedCommand +pub const fn radroots_protocol::command::CapturedCommand::approval_intent_digest(&self) -> radroots_domain::identifier::ApprovalIntentDigest +pub const fn radroots_protocol::command::CapturedCommand::chat(&self) -> core::option::Option<&radroots_protocol::command::CapturedChatCommand> +pub const fn radroots_protocol::command::CapturedCommand::context(&self) -> &radroots_domain::context::CommandContextData +pub const fn radroots_protocol::command::CapturedCommand::digest(&self) -> radroots_domain::identifier::CommandDigest +pub const fn radroots_protocol::command::CapturedCommand::kind(&self) -> radroots_protocol::command::CommandKind +pub const fn radroots_protocol::command::CapturedCommand::listing(&self) -> core::option::Option<&radroots_protocol::listing::CapturedListingCommand> +pub fn radroots_protocol::command::CapturedCommand::parse(&[u8]) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub fn radroots_protocol::command::CapturedCommand::protected_wire(&self) -> &[u8] +pub fn radroots_protocol::command::CapturedCommand::requires_history(&self) -> bool +impl core::convert::From<radroots_protocol::command::CapturedChatCommand> for radroots_protocol::command::CapturedCommand +pub fn radroots_protocol::command::CapturedCommand::from(radroots_protocol::command::CapturedChatCommand) -> Self +impl core::convert::From<radroots_protocol::listing::CapturedListingCommand> for radroots_protocol::command::CapturedCommand +pub fn radroots_protocol::command::CapturedCommand::from(radroots_protocol::listing::CapturedListingCommand) -> Self +impl core::fmt::Debug for radroots_protocol::command::CapturedCommand +pub fn radroots_protocol::command::CapturedCommand::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub enum radroots_protocol::command::ChatKind pub radroots_protocol::command::ChatKind::Inquire pub radroots_protocol::command::ChatKind::Reply @@ -148,9 +167,16 @@ pub const fn radroots_protocol::command::ChatKind::as_str(self) -> &'static str pub radroots_protocol::command::CommandError::InvalidInput pub radroots_protocol::command::CommandError::LimitExceeded pub radroots_protocol::command::CommandError::UnsupportedCommand +pub radroots_protocol::command::CommandError::UnsupportedProfile impl core::error::Error for radroots_protocol::command::CommandError impl core::fmt::Display for radroots_protocol::command::CommandError pub fn radroots_protocol::command::CommandError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_protocol::command::CommandKind +pub radroots_protocol::command::CommandKind::Inquire +pub radroots_protocol::command::CommandKind::PublishListing +pub radroots_protocol::command::CommandKind::Reply +impl radroots_protocol::command::CommandKind +pub const fn radroots_protocol::command::CommandKind::as_str(self) -> &'static str pub struct radroots_protocol::command::CapturedChatCommand impl radroots_protocol::command::CapturedChatCommand pub const fn radroots_protocol::command::CapturedChatCommand::approval_intent_digest(&self) -> radroots_domain::identifier::ApprovalIntentDigest @@ -166,6 +192,8 @@ pub fn radroots_protocol::command::CapturedChatCommand::reply(radroots_domain::c pub fn radroots_protocol::command::CapturedChatCommand::source(&self) -> core::option::Option<&radroots_protocol::command::ListingRevisionRef> pub fn radroots_protocol::command::CapturedChatCommand::text(&self) -> &str pub const fn radroots_protocol::command::CapturedChatCommand::thread_id(&self) -> radroots_domain::identifier::ThreadId +impl core::convert::From<radroots_protocol::command::CapturedChatCommand> for radroots_protocol::command::CapturedCommand +pub fn radroots_protocol::command::CapturedCommand::from(radroots_protocol::command::CapturedChatCommand) -> Self impl core::fmt::Debug for radroots_protocol::command::CapturedChatCommand pub fn radroots_protocol::command::CapturedChatCommand::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_protocol::command::InquireInput @@ -466,6 +494,19 @@ impl core::error::Error for radroots_protocol::intent::InvalidIntentBinding impl core::fmt::Display for radroots_protocol::intent::InvalidIntentBinding pub fn radroots_protocol::intent::InvalidIntentBinding::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub mod radroots_protocol::listing +pub struct radroots_protocol::listing::CapturedListingCommand +impl radroots_protocol::listing::CapturedListingCommand +pub const fn radroots_protocol::listing::CapturedListingCommand::approval_intent_digest(&self) -> radroots_domain::identifier::ApprovalIntentDigest +pub fn radroots_protocol::listing::CapturedListingCommand::capture(radroots_domain::context::CommandContextData, radroots_protocol::listing::PublishInput) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub const fn radroots_protocol::listing::CapturedListingCommand::context(&self) -> &radroots_domain::context::CommandContextData +pub const fn radroots_protocol::listing::CapturedListingCommand::digest(&self) -> radroots_domain::identifier::CommandDigest +pub const fn radroots_protocol::listing::CapturedListingCommand::input(&self) -> &radroots_protocol::listing::PublishInput +pub fn radroots_protocol::listing::CapturedListingCommand::parse(&[u8]) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub fn radroots_protocol::listing::CapturedListingCommand::protected_wire(&self) -> &[u8] +impl core::convert::From<radroots_protocol::listing::CapturedListingCommand> for radroots_protocol::command::CapturedCommand +pub fn radroots_protocol::command::CapturedCommand::from(radroots_protocol::listing::CapturedListingCommand) -> Self +impl core::fmt::Debug for radroots_protocol::listing::CapturedListingCommand +pub fn radroots_protocol::listing::CapturedListingCommand::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_protocol::listing::ListingEvent impl radroots_protocol::listing::ListingEvent pub const fn radroots_protocol::listing::ListingEvent::event_id(&self) -> &[u8; 32] @@ -479,6 +520,8 @@ pub const fn radroots_protocol::listing::PublishInput::id(&self) -> radroots_dom pub fn radroots_protocol::listing::PublishInput::new(radroots_domain::listing::ListingId, &str, &str, &str, radroots_domain::context::UnixSeconds, radroots_domain::listing::ListingTerms) -> core::result::Result<Self, radroots_protocol::nip01::WireError> pub const fn radroots_protocol::listing::PublishInput::published_at(&self) -> radroots_domain::context::UnixSeconds pub const fn radroots_protocol::listing::PublishInput::terms(&self) -> &radroots_domain::listing::ListingTerms +impl radroots_protocol::listing::PublishInput +pub fn radroots_protocol::listing::PublishInput::parse(&[u8]) -> core::result::Result<Self, radroots_protocol::command::CommandError> impl core::fmt::Debug for radroots_protocol::listing::PublishInput pub fn radroots_protocol::listing::PublishInput::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub const radroots_protocol::listing::LISTING_EVENT_MAX_BYTES: usize diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -848,6 +848,7 @@ pub radroots_storage::command::OperationError::MissingHistory pub radroots_storage::command::OperationError::RecoveryRequired pub radroots_storage::command::OperationError::StorageFailure pub radroots_storage::command::OperationError::Unauthorized +pub radroots_storage::command::OperationError::UnsupportedOperation pub radroots_storage::command::OperationError::UnverifiedApproval pub radroots_storage::command::OperationError::Workspace(radroots_storage::workspace::WorkspaceError) impl radroots_storage::command::OperationError @@ -873,10 +874,12 @@ pub fn radroots_storage::command::RetainedOperation::fmt(&self, &mut core::fmt:: pub struct radroots_storage::command::AdmissionRequest impl radroots_storage::command::AdmissionRequest pub const fn radroots_storage::command::AdmissionRequest::binding(&self) -> &radroots_storage::workspace::WorkspaceBinding -pub const fn radroots_storage::command::AdmissionRequest::command(&self) -> &radroots_protocol::command::CapturedChatCommand +pub fn radroots_storage::command::AdmissionRequest::chat_command(&self) -> core::result::Result<&radroots_protocol::command::CapturedChatCommand, radroots_storage::command::OperationError> +pub const fn radroots_storage::command::AdmissionRequest::command(&self) -> &radroots_protocol::command::captured::CapturedCommand pub fn radroots_storage::command::AdmissionRequest::from_protected_wire(radroots_storage::workspace::WorkspaceBinding, &[u8]) -> core::result::Result<Self, radroots_storage::command::OperationError> -pub fn radroots_storage::command::AdmissionRequest::into_parts(self) -> (radroots_storage::workspace::WorkspaceBinding, radroots_protocol::command::CapturedChatCommand) -pub fn radroots_storage::command::AdmissionRequest::new(radroots_storage::workspace::WorkspaceBinding, radroots_protocol::command::CapturedChatCommand) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub fn radroots_storage::command::AdmissionRequest::into_parts(self) -> (radroots_storage::workspace::WorkspaceBinding, radroots_protocol::command::captured::CapturedCommand) +pub fn radroots_storage::command::AdmissionRequest::new(radroots_storage::workspace::WorkspaceBinding, impl core::convert::Into<radroots_protocol::command::captured::CapturedCommand>) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub fn radroots_storage::command::AdmissionRequest::validate_fresh(&self, radroots_domain::context::UnixSeconds) -> core::result::Result<(), radroots_storage::command::OperationError> impl core::fmt::Debug for radroots_storage::command::AdmissionRequest pub fn radroots_storage::command::AdmissionRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage::command::BoundSigningPlan diff --git a/crates/domain/src/listing.rs b/crates/domain/src/listing.rs @@ -2,7 +2,7 @@ //! Quote-required choices are supported independently of monetary registries. use crate::{AuthorityRef, Decimal, ListingOptionId, PositiveDecimal, PublicKey, Sequence}; -use alloc::{string::String, vec::Vec}; +use alloc::{boxed::Box, string::String, vec::Vec}; use core::{fmt, str::FromStr}; /// A fixed, input-free public-offer value failure. @@ -378,7 +378,7 @@ pub enum FulfillmentMode { #[derive(Clone, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub struct PublicFulfillment { - modes: Vec<FulfillmentMode>, + modes: Box<[FulfillmentMode]>, area: String, lead_seconds: LeadSeconds, } @@ -394,7 +394,7 @@ impl PublicFulfillment { } text(area, 160, true)?; Ok(Self { - modes, + modes: modes.into_boxed_slice(), area: area.into(), lead_seconds, }) @@ -418,7 +418,7 @@ pub struct ListingTerms { state: ListingState, product: Product, default_option: ListingOptionId, - options: Vec<ListingOption>, + options: Box<[ListingOption]>, fulfillment: PublicFulfillment, authority: Option<AuthorityRef>, #[cfg_attr(feature = "serde", serde(skip))] @@ -451,7 +451,7 @@ impl ListingTerms { state, product, default_option, - options, + options: options.into_boxed_slice(), fulfillment, authority, default_index, diff --git a/crates/domain/tests/listing.rs b/crates/domain/tests/listing.rs @@ -38,6 +38,62 @@ fn option( } #[test] +fn spare_caller_capacity_preserves_exact_terms_and_default_selection() { + let mut modes = Vec::with_capacity(4096); + modes.push(FulfillmentMode::Pickup); + let mut options = Vec::with_capacity(4096); + options.push( + option( + 1, + SaleUnit::package_unspecified("bunch").unwrap(), + "1", + "1", + "10", + ) + .unwrap(), + ); + options.push( + option( + 2, + SaleUnit::measured(MeasurementUnit::Kilogram), + "0.25", + "0.5", + "10", + ) + .unwrap(), + ); + let compact = options.clone(); + let expanded = ListingTerms::new( + ListingState::Active, + product(), + ListingOptionId::from_bytes([2; 32]), + options, + PublicFulfillment::new(modes, "Example region", LeadSeconds::new(0).unwrap()).unwrap(), + None, + ) + .unwrap(); + let expected = ListingTerms::new( + ListingState::Active, + product(), + ListingOptionId::from_bytes([2; 32]), + compact, + fulfillment(), + None, + ) + .unwrap(); + assert_eq!(expanded, expected); + assert_eq!( + expanded.default_option().id(), + ListingOptionId::from_bytes([2; 32]) + ); + assert_eq!( + serde_json::to_vec(&expanded).unwrap(), + serde_json::to_vec(&expected).unwrap() + ); + assert_eq!(expanded.clone(), expected); +} + +#[test] fn identifiers_durations_and_public_data_preserve_exact_cross_host_values() { let id = ListingId::from_bytes([0xAB; 16]); assert_eq!(id.to_string(), "ab".repeat(16)); diff --git a/crates/execution/src/error.rs b/crates/execution/src/error.rs @@ -223,6 +223,7 @@ impl Error { O::InvalidCommand => (Code::InvalidInput, RetryClass::Never), O::InvalidEvidence => (Code::RecoveryRequired, RetryClass::ManualReconciliation), O::Unauthorized | O::UnverifiedApproval => (Code::Unauthorized, RetryClass::Never), + O::UnsupportedOperation => (Code::CapabilityUnavailable, RetryClass::Never), O::MissingHistory => (Code::MissingHistory, RetryClass::AfterStateRefresh), O::DeadlineExceeded => (Code::DeadlineExceeded, RetryClass::AfterStateRefresh), O::IdempotencyConflict => (Code::IdempotencyConflict, RetryClass::Never), diff --git a/crates/execution/src/session/inquiry.rs b/crates/execution/src/session/inquiry.rs @@ -266,7 +266,7 @@ impl InquiryRuntime { if now >= prepared.issuance_window().first_issue_not_after() { return Err(OperationError::DeadlineExceeded); } - let command = prepared.request().command(); + let command = prepared.request().chat_command()?; let observed = signer .observe() .await diff --git a/crates/protocol/README.md b/crates/protocol/README.md @@ -124,6 +124,14 @@ The reviewed Rust surface is recorded in the ## Complete private signing-plan data +`command::CapturedCommand` preserves the original chat bytes and commitments +and admits a separate typed `listing::CapturedListingCommand` when `listing` +is enabled. Public capture uses the same context and correlation/approval hash +projections. Its closed parser validates the supported quote-required profile +through domain constructors; unsupported price, supply, package contents or +media features are refused explicitly. Public commands have no chat peer or +private message. Capture supplies no current grant, signature or durable effect. + `chat::ChatSigningPlan` retains the exact sorted unique peer/self recipient set, seal author/kind/time/empty tags/content/event ID/purpose, original signed DM route-source bytes, selected targets, logical message ID, command commitment and diff --git a/crates/protocol/src/command.rs b/crates/protocol/src/command.rs @@ -1,4 +1,5 @@ -//! Closed chat-command profile. Parsing and hashing are pure data operations. +//! Common captured commands and the original closed chat-command profile. +//! Parsing and hashing are pure data operations. //! They never authorize a principal, confirm a transaction or request signing. //! //! Canonical encoding follows the RFC 8785 subset specified for this profile: @@ -28,8 +29,10 @@ const JSON_MAX_DEPTH: usize = 16; pub enum CommandError { /// The closed input shape or a value is invalid. InvalidInput, - /// This command type is not implemented by the chat profile. + /// This command type is not implemented by the selected profile. UnsupportedCommand, + /// A known command requires a profile feature not implemented here. + UnsupportedProfile, /// A byte/depth bound was exceeded. LimitExceeded, } @@ -37,13 +40,17 @@ impl fmt::Display for CommandError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { Self::InvalidInput => "invalid command input", - Self::UnsupportedCommand => "unsupported chat command", + Self::UnsupportedCommand => "unsupported command", + Self::UnsupportedProfile => "unsupported command profile", Self::LimitExceeded => "command limit exceeded", }) } } impl core::error::Error for CommandError {} +mod captured; +pub use captured::{CapturedCommand, CommandKind}; + /// A captured public listing reference. This descriptor verifies neither its /// source event nor its availability, terms or stock backing. #[derive(Clone, Eq, PartialEq)] @@ -365,13 +372,13 @@ impl fmt::Debug for CapturedChatCommand { } } -fn hash(domain: &[u8], bytes: &[u8]) -> [u8; 32] { +pub(crate) fn hash(domain: &[u8], bytes: &[u8]) -> [u8; 32] { let mut hash = Sha256::new(); hash.update(domain); hash.update(bytes); hash.finalize().into() } -fn check_frame(raw: &[u8]) -> Result<(), CommandError> { +pub(crate) fn check_frame(raw: &[u8]) -> Result<(), CommandError> { if raw.len() > COMMAND_MAX_BYTES { return Err(CommandError::LimitExceeded); } @@ -413,7 +420,7 @@ struct RawRoot<'a> { #[serde(borrow)] input: &'a serde_json::value::RawValue, } -fn required_nullable<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>( +pub(crate) fn required_nullable<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>( d: D, ) -> Result<Option<T>, D::Error> { Option::deserialize(d) @@ -486,7 +493,11 @@ impl Serialize for CanonicalCommand<'_> { o.end() } } -struct Context<'a>(&'a CommandContextData, bool, bool); +pub(crate) struct Context<'a>( + pub(crate) &'a CommandContextData, + pub(crate) bool, + pub(crate) bool, +); impl Serialize for Context<'_> { fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { let v = self.0; diff --git a/crates/protocol/src/command/captured.rs b/crates/protocol/src/command/captured.rs @@ -0,0 +1,142 @@ +//! Common immutable command data. Domain-specific payloads remain explicit; +//! no chat identity or recipient is fabricated for a public command. +use super::{CapturedChatCommand, ChatKind, CommandError, check_frame}; +use alloc::string::String; +use core::fmt; +use radroots_domain::{ApprovalIntentDigest, CommandContextData, CommandDigest}; +use serde::Deserialize; + +/// Implemented known-kind command families, without execution permission. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum CommandKind { + /// Private inquiry. + Inquire, + /// Private reply requiring authenticated history. + Reply, + /// Public listing publication. + PublishListing, +} +impl CommandKind { + /// Exact closed command discriminator. + pub const fn as_str(self) -> &'static str { + match self { + Self::Inquire => "inbox.inquire", + Self::Reply => "inbox.reply", + Self::PublishListing => "listing.publish", + } + } +} + +/// Bounded captured data shared by authoritative admission. Parsing supplies +/// no grant, durable preparation, signer permission or installation evidence. +pub enum CapturedCommand { + /// Original chat profile, retaining its exact established commitments. + Chat(CapturedChatCommand), + /// Supported quote-required public profile. + #[cfg(feature = "listing")] + Listing(crate::listing::CapturedListingCommand), +} +impl CapturedCommand { + /// Selects an implemented family only after bounded JSON frame admission. + /// Each selected parser independently validates its entire closed shape. + pub fn parse(raw: &[u8]) -> Result<Self, CommandError> { + check_frame(raw)?; + #[derive(Deserialize)] + struct Header { + #[serde(rename = "type")] + kind: String, + } + let header: Header = serde_json::from_slice(raw).map_err(|_| CommandError::InvalidInput)?; + if header.kind.len() > 80 { + return Err(CommandError::LimitExceeded); + } + match header.kind.as_str() { + "inbox.inquire" | "inbox.reply" => CapturedChatCommand::parse(raw).map(Self::Chat), + #[cfg(feature = "listing")] + "listing.publish" => { + crate::listing::CapturedListingCommand::parse(raw).map(Self::Listing) + } + _ => Err(CommandError::UnsupportedCommand), + } + } + /// Original complete context data, requiring separate authentication. + pub const fn context(&self) -> &CommandContextData { + match self { + Self::Chat(v) => v.context(), + #[cfg(feature = "listing")] + Self::Listing(v) => v.context(), + } + } + /// Original semantic commitment, excluding diagnostic correlation. + pub const fn digest(&self) -> CommandDigest { + match self { + Self::Chat(v) => v.digest(), + #[cfg(feature = "listing")] + Self::Listing(v) => v.digest(), + } + } + /// Exact approval intent; its bytes authenticate no consent. + pub const fn approval_intent_digest(&self) -> ApprovalIntentDigest { + match self { + Self::Chat(v) => v.approval_intent_digest(), + #[cfg(feature = "listing")] + Self::Listing(v) => v.approval_intent_digest(), + } + } + /// Exact supported command family. + pub const fn kind(&self) -> CommandKind { + match self { + Self::Chat(v) => match v.kind() { + ChatKind::Inquire => CommandKind::Inquire, + ChatKind::Reply => CommandKind::Reply, + }, + #[cfg(feature = "listing")] + Self::Listing(_) => CommandKind::PublishListing, + } + } + /// Borrows retained canonical bytes for protected handling. + pub fn protected_wire(&self) -> &[u8] { + match self { + Self::Chat(v) => v.protected_wire(), + #[cfg(feature = "listing")] + Self::Listing(v) => v.protected_wire(), + } + } + /// Borrows actual chat data, never a synthesized peer or empty message. + pub const fn chat(&self) -> Option<&CapturedChatCommand> { + match self { + Self::Chat(v) => Some(v), + #[cfg(feature = "listing")] + Self::Listing(_) => None, + } + } + /// Borrows actual supported public listing data. + #[cfg(feature = "listing")] + pub const fn listing(&self) -> Option<&crate::listing::CapturedListingCommand> { + match self { + Self::Chat(_) => None, + Self::Listing(v) => Some(v), + } + } + /// Whether this capture names history the fresh outbox cannot invent. + pub fn requires_history(&self) -> bool { + self.context().expected().is_some() || self.chat().is_some_and(|v| v.parent().is_some()) + } +} +impl From<CapturedChatCommand> for CapturedCommand { + fn from(v: CapturedChatCommand) -> Self { + Self::Chat(v) + } +} +#[cfg(feature = "listing")] +impl From<crate::listing::CapturedListingCommand> for CapturedCommand { + fn from(v: crate::listing::CapturedListingCommand) -> Self { + Self::Listing(v) + } +} +impl fmt::Debug for CapturedCommand { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CapturedCommand(<redacted>)") + } +} diff --git a/crates/protocol/src/listing.rs b/crates/protocol/src/listing.rs @@ -17,6 +17,10 @@ use serde::Serialize; use serde_json::Value; use sha2::{Digest, Sha256}; +mod command; +mod input; +pub use command::CapturedListingCommand; + /// Assigned NIP-99 addressable classified-listing kind. pub const LISTING_KIND: u32 = 30402; /// Complete public event cap, including NIP-01 key, ID and signature framing. @@ -209,7 +213,7 @@ impl fmt::Debug for ListingEvent { // RFC8785 subset: field names are fixed ASCII, quantities/IDs/times are strings, // numeric fields are exact safe unsigned integers, and Unicode is preserved. // Explicit sorting remains correct if a downstream crate enables preserve_order. -fn canonical(value: &Value, out: &mut String) -> Result<(), WireError> { +pub(crate) fn canonical(value: &Value, out: &mut String) -> Result<(), WireError> { match value { Value::Object(fields) => { let mut keys: Vec<_> = fields.keys().collect(); diff --git a/crates/protocol/src/listing/command.rs b/crates/protocol/src/listing/command.rs @@ -0,0 +1,111 @@ +use super::{PublishInput, canonical}; +use crate::command::{COMMAND_MAX_BYTES, CommandError, Context, check_frame, hash}; +use alloc::{boxed::Box, string::String}; +use core::fmt; +use radroots_domain::{ApprovalIntentDigest, CommandContextData, CommandDigest}; +use serde::Deserialize; +use zeroize::Zeroizing; + +/// Exact captured public command data. Construction performs no authentication, +/// durable admission, event signing, installation or network work. +pub struct CapturedListingCommand { + context: CommandContextData, + input: PublishInput, + wire: Zeroizing<Box<[u8]>>, + digest: CommandDigest, + approval: ApprovalIntentDigest, +} +impl CapturedListingCommand { + /// Captures validated input with the common context/hash projections. + pub fn capture(context: CommandContextData, input: PublishInput) -> Result<Self, CommandError> { + let encode = |approval, correlation| -> Result<Zeroizing<String>, CommandError> { + let mut root = serde_json::Map::new(); + root.insert( + "context".into(), + serde_json::to_value(Context(&context, approval, correlation)) + .map_err(|_| CommandError::InvalidInput)?, + ); + root.insert( + "input".into(), + serde_json::to_value(&input).map_err(|_| CommandError::InvalidInput)?, + ); + root.insert( + "type".into(), + serde_json::Value::String("listing.publish".into()), + ); + let value = serde_json::Value::Object(root); + let mut out = Zeroizing::new(String::new()); + canonical(&value, &mut out).map_err(|error| match error { + crate::nip01::WireError::LimitExceeded => CommandError::LimitExceeded, + _ => CommandError::InvalidInput, + })?; + if out.len() > COMMAND_MAX_BYTES { + return Err(CommandError::LimitExceeded); + } + Ok(out) + }; + let wire = Zeroizing::new(Box::from(encode(true, true)?.as_bytes())); + let digest = CommandDigest::from_bytes(hash( + b"radroots.command.v1\0", + encode(true, false)?.as_bytes(), + )); + let approval = ApprovalIntentDigest::from_bytes(hash( + b"radroots.approval.v1\0", + encode(false, false)?.as_bytes(), + )); + Ok(Self { + context, + input, + wire, + digest, + approval, + }) + } + /// Strictly parses an implemented profile; unsupported modes never become + /// a quote, a zero price, an empty attachment or a replacement command. + pub fn parse(raw: &[u8]) -> Result<Self, CommandError> { + check_frame(raw)?; + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Root<'a> { + #[serde(rename = "type")] + kind: String, + context: CommandContextData, + #[serde(borrow)] + input: &'a serde_json::value::RawValue, + } + let root: Root<'_> = serde_json::from_slice(raw).map_err(|_| CommandError::InvalidInput)?; + if root.kind != "listing.publish" { + return Err(CommandError::UnsupportedCommand); + } + Self::capture( + root.context, + PublishInput::parse(root.input.get().as_bytes())?, + ) + } + /// Original context descriptors, without workspace permission. + pub const fn context(&self) -> &CommandContextData { + &self.context + } + /// Exact immutable input, with bounded owned collections. + pub const fn input(&self) -> &PublishInput { + &self.input + } + /// Semantic commitment excluding correlation only. + pub const fn digest(&self) -> CommandDigest { + self.digest + } + /// Approval-intent commitment excluding approval and correlation. + pub const fn approval_intent_digest(&self) -> ApprovalIntentDigest { + self.approval + } + /// Original canonical bytes for protected retention. + pub fn protected_wire(&self) -> &[u8] { + &self.wire + } +} +impl fmt::Debug for CapturedListingCommand { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CapturedListingCommand(<redacted>)") + } +} diff --git a/crates/protocol/src/listing/input.rs b/crates/protocol/src/listing/input.rs @@ -0,0 +1,242 @@ +//! Closed known-profile input admission. Domain construction remains the sole +//! value invariant owner; no unknown field or unsupported feature is discarded. +use super::PublishInput; +use crate::command::{CommandError, check_frame, required_nullable}; +use alloc::{string::String, vec::Vec}; +use radroots_domain::{ + AuthorityRef, Decimal, ListingOptionId, PositiveDecimal, PublicKey, UnixSeconds, listing::*, +}; +use serde::Deserialize; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Input { + id: ListingId, + title: String, + summary: String, + description_markdown: String, + published_at: UnixSeconds, + profile: Profile, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Profile { + profile: String, + version: u32, + state: State, + product: RawProduct, + default_option: ListingOptionId, + options: Vec<OptionInput>, + fulfillment: Fulfillment, + #[serde(deserialize_with = "required_nullable")] + authority: Option<AuthorityRef>, + #[serde(rename = "media")] + _media: [(); 0], +} +#[derive(Deserialize)] +#[serde(rename_all = "snake_case")] +enum State { + Active, + Paused, + Withdrawn, +} +#[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: Quote, + 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, +} +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +enum Contents { + Unspecified, +} +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +enum Quote { + QuoteRequired, +} +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +enum RawSupply { + Unknown, + Available { amount: Decimal }, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Fulfillment { + modes: Vec<Mode>, + area: String, + lead_seconds: LeadSeconds, +} +#[derive(Deserialize)] +#[serde(rename_all = "snake_case")] +enum Mode { + Pickup, + Delivery, +} + +fn invalid<T>(value: Result<T, ListingError>) -> Result<T, CommandError> { + value.map_err(|_| CommandError::InvalidInput) +} +impl Input { + fn validate(self) -> Result<PublishInput, CommandError> { + let profile = self.profile; + 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(), + ))?; + 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 Quote::QuoteRequired = option.price; + let unit = match option.unit { + Unit::Measured { unit } => SaleUnit::measured(match unit { + Measure::Gram => MeasurementUnit::Gram, + Measure::Kilogram => MeasurementUnit::Kilogram, + Measure::Millilitre => MeasurementUnit::Millilitre, + Measure::Litre => MeasurementUnit::Litre, + Measure::Each => MeasurementUnit::Each, + }), + Unit::Package { label, contents } => { + let Contents::Unspecified = contents; + invalid(SaleUnit::package_unspecified(&label))? + } + }; + options.push(invalid(ListingOption::quote_required( + option.id, + &option.label, + unit, + option.increment, + option.minimum, + match option.supply { + RawSupply::Unknown => Supply::Unknown, + RawSupply::Available { amount } => Supply::Available { amount }, + }, + option.lead_seconds, + ))?); + } + let fulfillment = invalid(PublicFulfillment::new( + profile + .fulfillment + .modes + .into_iter() + .map(|mode| match mode { + Mode::Pickup => FulfillmentMode::Pickup, + Mode::Delivery => FulfillmentMode::Delivery, + }) + .collect(), + &profile.fulfillment.area, + profile.fulfillment.lead_seconds, + ))?; + let terms = invalid(ListingTerms::new( + match profile.state { + State::Active => ListingState::Active, + State::Paused => ListingState::Paused, + State::Withdrawn => ListingState::Withdrawn, + }, + product, + profile.default_option, + options, + fulfillment, + profile.authority, + ))?; + PublishInput::new( + self.id, + &self.title, + &self.summary, + &self.description_markdown, + self.published_at, + terms, + ) + .map_err(|_| CommandError::InvalidInput) + } +} +impl PublishInput { + /// Admits bounded closed quote-required input. Known unsupported features + /// return an explicit refusal; they are never silently stripped or coerced. + pub fn parse(raw: &[u8]) -> Result<Self, CommandError> { + check_frame(raw)?; + // This bounded peek only classifies unimplemented features. Acceptance + // still requires the independent closed parser, including duplicates, + // required nulls and all nested domain constructors. + let value: serde_json::Value = + serde_json::from_slice(raw).map_err(|_| CommandError::InvalidInput)?; + if let Some(profile) = value.get("profile") { + if profile + .get("profile") + .is_some_and(|v| v != "radroots.listing") + || profile.get("version").is_some_and(|v| v != 1) + || profile + .get("media") + .and_then(serde_json::Value::as_array) + .is_some_and(|v| !v.is_empty()) + { + return Err(CommandError::UnsupportedProfile); + } + if let Some(options) = profile.get("options").and_then(serde_json::Value::as_array) { + for option in options { + if option + .pointer("/price/type") + .and_then(serde_json::Value::as_str) + .is_some_and(|v| v != "quote_required") + || option + .pointer("/supply/type") + .and_then(serde_json::Value::as_str) + .is_some_and(|v| !matches!(v, "unknown" | "available")) + || option + .pointer("/unit/contents/type") + .and_then(serde_json::Value::as_str) + .is_some_and(|v| v != "unspecified") + { + return Err(CommandError::UnsupportedProfile); + } + } + } + } + let input: Input = serde_json::from_slice(raw).map_err(|_| CommandError::InvalidInput)?; + input.validate() + } +} diff --git a/crates/protocol/tests/public_command.rs b/crates/protocol/tests/public_command.rs @@ -0,0 +1,184 @@ +#![cfg(feature = "listing")] +use radroots_domain::{ + ActorRef, ActorRole, AuthorityRef, CommandContextData, ExecutorId, Generation, GrantId, + OperationId, PublicKey, RouteDigest, ThreadId, UnixSeconds, WorkspaceId, +}; +use radroots_protocol::{ + command::{CapturedChatCommand, CapturedCommand, CommandError, InquireInput}, + listing::{CapturedListingCommand, PublishInput}, +}; +use serde_json::{Value, json}; +fn key() -> PublicKey { + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() +} +fn context() -> CommandContextData { + CommandContextData::new( + OperationId::from_bytes([7; 32]), + ActorRef::new( + key(), + ActorRole::Seller, + None, + Some(GrantId::from_bytes([3; 32])), + ), + WorkspaceId::from_bytes([1; 32]), + AuthorityRef::new(ExecutorId::from_bytes([2; 32]), Generation::new(1).unwrap()), + RouteDigest::from_bytes([5; 32]), + None, + None, + UnixSeconds::new(150).unwrap(), + None, + ) + .unwrap() +} +fn input() -> Value { + json!({"id":"01".repeat(16),"title":"Carrots","summary":"One bunch; quote required","description_markdown":"Public terms","published_at":"100","profile":{"profile":"radroots.listing","version":1,"state":"active","product":{"name":"Carrots","description":"Public description","producer":null,"origin_summary":null},"default_option":"02".repeat(32),"options":[{"id":"02".repeat(32),"label":"One bunch","unit":{"type":"package","label":"bunch","contents":{"type":"unspecified"}},"increment":"1","minimum":"1","price":{"type":"quote_required"},"supply":{"type":"available","amount":"10"},"lead_seconds":"0"}],"fulfillment":{"modes":["pickup"],"area":"Example region","lead_seconds":"0"},"authority":null,"media":[]}}) +} + +#[test] +fn both_families_round_trip_without_rehashing_or_fabricating_chat_data() { + let chat = CapturedChatCommand::inquire( + context(), + InquireInput::new( + ThreadId::from_bytes([6; 32]), + key(), + None, + "Original private text", + ) + .unwrap(), + ) + .unwrap(); + let wire = chat.protected_wire().to_vec(); + let digest = chat.digest(); + let intent = chat.approval_intent_digest(); + let common = CapturedCommand::from(chat); + assert_eq!(common.protected_wire(), wire); + assert_eq!(common.digest(), digest); + assert_eq!(common.approval_intent_digest(), intent); + assert!(common.listing().is_none()); + let replay = CapturedCommand::parse(&wire).unwrap(); + assert_eq!(replay.protected_wire(), wire); + assert_eq!(replay.chat().unwrap().text(), "Original private text"); + let public = CapturedListingCommand::capture( + context(), + PublishInput::parse(&serde_json::to_vec(&input()).unwrap()).unwrap(), + ) + .unwrap(); + let common = CapturedCommand::from(public); + let replay = CapturedCommand::parse(common.protected_wire()).unwrap(); + assert_eq!(replay.digest(), common.digest()); + assert_eq!(replay.protected_wire(), common.protected_wire()); + assert_eq!(replay.kind().as_str(), "listing.publish"); + assert!(replay.chat().is_none()); + assert!(!replay.requires_history()); + assert_eq!( + replay.listing().unwrap().input().id().to_string(), + "01".repeat(16) + ); + assert!(!format!("{replay:?}").contains("Carrots")); +} + +#[test] +fn diagnostic_correlation_and_approval_projections_reuse_the_common_context_contract() { + let public = CapturedListingCommand::capture( + context(), + PublishInput::parse(&serde_json::to_vec(&input()).unwrap()).unwrap(), + ) + .unwrap(); + let mut wire: Value = serde_json::from_slice(public.protected_wire()).unwrap(); + wire["context"]["correlation_id"] = json!("diagnostic-two"); + let diagnostic = CapturedListingCommand::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); + assert_eq!(diagnostic.digest(), public.digest()); + assert_eq!( + diagnostic.approval_intent_digest(), + public.approval_intent_digest() + ); + assert_ne!(diagnostic.protected_wire(), public.protected_wire()); + wire["context"]["approval"] = json!({"intent_digest":"11".repeat(32),"scope":"synthetic approval metadata","expires_at":"140"}); + let approved = CapturedListingCommand::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); + assert_ne!(approved.digest(), public.digest()); + assert_eq!( + approved.approval_intent_digest(), + public.approval_intent_digest() + ); +} + +#[test] +fn closed_input_refuses_unknown_duplicate_missing_nullable_and_invalid_value_paths() { + let original = input(); + let bytes = serde_json::to_vec(&original).unwrap(); + PublishInput::parse(&bytes).unwrap(); + for pointer in [ + "/profile/authority", + "/profile/product/producer", + "/profile/product/origin_summary", + ] { + let mut value = original.clone(); + let (parent, key) = pointer.rsplit_once('/').unwrap(); + value + .pointer_mut(parent) + .unwrap() + .as_object_mut() + .unwrap() + .remove(key); + assert!( + PublishInput::parse(&serde_json::to_vec(&value).unwrap()).is_err(), + "{pointer}" + ); + } + for (pointer, bad) in [ + ("/profile/options/0/minimum", json!("1.5")), + ("/profile/options/0/supply/amount", json!("0.5")), + ("/profile/default_option", json!("03".repeat(32))), + ("/profile/fulfillment/modes", json!(["pickup", "pickup"])), + ("/published_at", json!(100)), + ] { + let mut value = original.clone(); + *value.pointer_mut(pointer).unwrap() = bad; + assert!( + PublishInput::parse(&serde_json::to_vec(&value).unwrap()).is_err(), + "{pointer}" + ); + } + let mut unknown = original.clone(); + unknown["profile"]["options"][0]["pool_id"] = json!("private inventory selector"); + assert!(PublishInput::parse(&serde_json::to_vec(&unknown).unwrap()).is_err()); + let raw = String::from_utf8(bytes).unwrap(); + let duplicate = raw.replacen("\"version\":1", "\"version\":1,\"version\":1", 1); + assert!(PublishInput::parse(duplicate.as_bytes()).is_err()); + assert_eq!( + CapturedCommand::parse(&vec![b' '; 65537]).unwrap_err(), + CommandError::LimitExceeded + ); +} + +#[test] +fn unsupported_full_profile_features_are_refused_without_silent_quote_or_media_fallback() { + for (pointer, bad) in [ + ("/profile/version", json!(2)), + ("/profile/profile", json!("other.profile")), + ( + "/profile/media", + json!([{"url":"https://example.invalid/image"}]), + ), + ( + "/profile/options/0/price", + json!({"type":"fixed","rate":{"currency":"CAD","minor":"325","exponent":2}}), + ), + ( + "/profile/options/0/supply", + json!({"type":"estimated","amount":"10","window":null}), + ), + ( + "/profile/options/0/unit/contents", + json!({"type":"fixed","quantity":{"amount":"1","unit":"kg"}}), + ), + ] { + let mut value = input(); + *value.pointer_mut(pointer).unwrap() = bad; + assert_eq!( + PublishInput::parse(&serde_json::to_vec(&value).unwrap()).unwrap_err(), + CommandError::UnsupportedProfile, + "{pointer}" + ); + } +} diff --git a/crates/radroots/tests/support/receipt_client.rs b/crates/radroots/tests/support/receipt_client.rs @@ -139,7 +139,7 @@ async fn ordinary_inquiry_confirms_actual_t0_and_current_pending_receipt_without .unwrap() .unwrap(); assert_eq!( - actual.prepared().request().command().text(), + actual.prepared().request().chat_command().unwrap().text(), "private ordinary inquiry" ); assert!(actual.bound_plan().is_none()); @@ -388,7 +388,7 @@ async fn accepted_ordinary_inquiry_survives_observer_loss_and_client_close_drain .unwrap() .unwrap(); assert_eq!( - snapshot.prepared().request().command().text(), + snapshot.prepared().request().chat_command().unwrap().text(), "retained after wait loss" ); assert!(snapshot.bound_plan().is_none()); @@ -499,7 +499,10 @@ async fn ordinary_owned_budget_survives_lost_observers_and_all_accepted_commands .await .unwrap() .unwrap(); - assert_eq!(snapshot.prepared().request().command().text(), body); + assert_eq!( + snapshot.prepared().request().chat_command().unwrap().text(), + body + ); } assert!( reopened @@ -567,7 +570,7 @@ async fn owned_inquiry_continues_to_its_coherent_query_after_the_caller_disappea .unwrap() .unwrap(); assert_eq!( - snapshot.prepared().request().command().text(), + snapshot.prepared().request().chat_command().unwrap().text(), "independent owner continuation" ); reopened.close().await.unwrap(); diff --git a/crates/radroots/tests/support/receipt_delivery.rs b/crates/radroots/tests/support/receipt_delivery.rs @@ -86,9 +86,14 @@ impl Ready { .await .unwrap(), ); - let plan = plan_with_routes(prepared.request().command(), time, "delivery", Some(urls)); + let plan = plan_with_routes( + prepared.request().chat_command().unwrap(), + time, + "delivery", + Some(urls), + ); let digest = *plan.digest(); - let recipient = prepared.request().command().peer(); + let recipient = prepared.request().chat_command().unwrap().peer(); bound( store .bind_signing_intents(binding.clone(), plan, copy(&proof)) diff --git a/crates/radroots/tests/support/receipt_installation_reports.rs b/crates/radroots/tests/support/receipt_installation_reports.rs @@ -17,8 +17,11 @@ fn restamp_plan(source: &BoundSigningPlan, transaction: TransactionId) -> BoundS original.issuance_window(), ) .unwrap(); - let plan = ChatSigningPlan::parse(prepared.request().command(), source.plan().protected_wire()) - .unwrap(); + let plan = ChatSigningPlan::parse( + prepared.request().chat_command().unwrap(), + source.plan().protected_wire(), + ) + .unwrap(); BoundSigningPlan::from_committed_store(prepared, plan, transaction, source.bound_at()).unwrap() } @@ -95,7 +98,7 @@ async fn structural_installation_reports_bind_original_plan_capture_and_complete assert_eq!(reported.installation(), Some(installation)); assert_eq!( reported.installed_message().unwrap().text(), - prepared.request().command().text() + prepared.request().chat_command().unwrap().text() ); // No actual installation was performed by constructing any of these values. assert!( diff --git a/crates/radroots/tests/support/receipt_issuance.rs b/crates/radroots/tests/support/receipt_issuance.rs @@ -74,7 +74,11 @@ pub(super) async fn prepare( .await .unwrap(), ); - let plan = plan(prepared.request().command(), 100, "native-issuance"); + let plan = plan( + prepared.request().chat_command().unwrap(), + 100, + "native-issuance", + ); let digest = *plan.digest(); let recipients = plan.seals().iter().map(|seal| seal.recipient()).collect(); bound( diff --git a/crates/radroots/tests/support/receipt_snapshots.rs b/crates/radroots/tests/support/receipt_snapshots.rs @@ -459,7 +459,7 @@ async fn coherent_snapshots_retain_t0_t1_and_independent_recipient_claim_and_cap && value.claim().is_none() && value.obtained().is_none()) ); - let plan = plan(prepared.request().command(), 100, "snapshot"); + let plan = plan(prepared.request().chat_command().unwrap(), 100, "snapshot"); let plan_digest = *plan.digest(); let message = plan.message_id(); let plan_receipt = bound( diff --git a/crates/storage/Cargo.toml b/crates/storage/Cargo.toml @@ -35,7 +35,7 @@ name = "radroots_storage" [features] default = ["memory", "serde"] memory = [] -command_journal = ["radroots_protocol/chat", "radroots_protocol/intent"] +command_journal = ["radroots_protocol/chat", "radroots_protocol/intent", "radroots_protocol/listing"] protected_outbox = ["command_journal", "serde", "dep:serde_json", "dep:subtle"] serde = [ "dep:serde", diff --git a/crates/storage/README.md b/crates/storage/README.md @@ -100,6 +100,12 @@ New preparations retain scope explicitly in version 3. Historical version 2 preparations remain readable only with their original buyer-outbox authority; no actor descriptor can infer a seller grant during recovery. +Common admission retains a typed command family. Fresh public listing T0 +requires an authenticated seller outbox and valid bounded event inputs. The +current history and approval prerequisites remain explicit refusals. Chat-only +ports require actual chat data and return `capability_unavailable` for a public +preparation; no synthetic peer or receipt bridges the families. + `BackupSource::settle_backup_writes` waits for earlier owner writes, including work whose caller was cancelled. The host excludes new writes before settling and retains that exclusion through related inventory and capture. Settling does diff --git a/crates/storage/src/command.rs b/crates/storage/src/command.rs @@ -8,7 +8,7 @@ use radroots_domain::{ CommandDigest, IssuanceWindow, OperationId, Sequence, TransactionId, WorkspaceId, }; pub use radroots_protocol::chat::ChatSigningPlan; -use radroots_protocol::command::CapturedChatCommand; +use radroots_protocol::command::{CapturedChatCommand, CapturedCommand}; use radroots_transport::BoxFuture; #[cfg(feature = "protected_outbox")] @@ -49,6 +49,8 @@ pub enum OperationError { InvalidEvidence, /// This concrete authority cannot execute the requested action. Unauthorized, + /// This exact backend/family port cannot perform the requested operation. + UnsupportedOperation, /// Required authenticated thread/order history is unavailable. MissingHistory, /// No qualified protected origin verifies the supplied approval descriptor. @@ -72,6 +74,7 @@ impl OperationError { Self::InvalidCommand => "invalid_command", Self::InvalidEvidence => "invalid_evidence", Self::Unauthorized => "unauthorized", + Self::UnsupportedOperation => "capability_unavailable", Self::MissingHistory => "missing_history", Self::UnverifiedApproval => "unverified_approval", Self::DeadlineExceeded => "deadline_exceeded", @@ -99,7 +102,7 @@ impl From<WorkspaceError> for OperationError { /// persisted state inside the actual admission transaction. pub struct AdmissionRequest { binding: WorkspaceBinding, - command: CapturedChatCommand, + command: CapturedCommand, } impl AdmissionRequest { /// Refuses substituted workspace, actor/grant, authority or route data. @@ -107,8 +110,9 @@ impl AdmissionRequest { /// an expired original command may still be queried/reconciled by identity. pub fn new( binding: WorkspaceBinding, - command: CapturedChatCommand, + command: impl Into<CapturedCommand>, ) -> Result<Self, OperationError> { + let command = command.into(); let context = command.context(); let input = binding.input(); if context.actor() != binding.actor() @@ -126,8 +130,7 @@ impl AdmissionRequest { binding: WorkspaceBinding, wire: &[u8], ) -> Result<Self, OperationError> { - let command = - CapturedChatCommand::parse(wire).map_err(|_| OperationError::RecoveryRequired)?; + let command = CapturedCommand::parse(wire).map_err(|_| OperationError::RecoveryRequired)?; Self::new(binding, command) } /// Borrows the captured attachment observation, without claiming it is current. @@ -135,11 +138,41 @@ impl AdmissionRequest { &self.binding } /// Borrows exact immutable command data. - pub const fn command(&self) -> &CapturedChatCommand { + pub const fn command(&self) -> &CapturedCommand { &self.command } + /// Borrows actual chat data only. A public operation has no invented peer, + /// rumor, text or parent and cannot enter a chat-only effect port. + pub fn chat_command(&self) -> Result<&CapturedChatCommand, OperationError> { + self.command + .chat() + .ok_or(OperationError::UnsupportedOperation) + } + /// Checks fresh non-stock payload preconditions after actual authentication. + /// This structural check supplies no current access, transaction or hold; + /// concrete owners must independently recheck their authoritative fences. + pub fn validate_fresh(&self, now: radroots_domain::UnixSeconds) -> Result<(), OperationError> { + if self.command.requires_history() { + return Err(OperationError::MissingHistory); + } + if self.command.context().approval().is_some() { + return Err(OperationError::UnverifiedApproval); + } + if let Some(listing) = self.command.listing() { + if self.binding.scope() != crate::workspace::LocalOutboxScope::NewSellerOutbox { + return Err(OperationError::Unauthorized); + } + radroots_protocol::listing::ListingEvent::new( + listing.input(), + self.binding.actor().participant(), + now, + ) + .map_err(|_| OperationError::InvalidCommand)?; + } + Ok(()) + } /// Transfers both owned descriptors to the concrete transaction owner. - pub fn into_parts(self) -> (WorkspaceBinding, CapturedChatCommand) { + pub fn into_parts(self) -> (WorkspaceBinding, CapturedCommand) { (self.binding, self.command) } } @@ -438,8 +471,9 @@ impl BoundSigningPlan { } // Reconstruct against the actually retained command, rather than trust // a matching digest descriptor attached to unrelated plan fields. - let checked = ChatSigningPlan::parse(prepared.request().command(), plan.protected_wire()) - .map_err(|_| OperationError::RecoveryRequired)?; + let checked = + ChatSigningPlan::parse(prepared.request().chat_command()?, plan.protected_wire()) + .map_err(|_| OperationError::RecoveryRequired)?; Ok(Self { prepared, plan: checked, diff --git a/crates/storage/src/command/protected/plan.rs b/crates/storage/src/command/protected/plan.rs @@ -162,7 +162,7 @@ mod tests { fn make_plan(prepared: &PreparedOperation, created: u64) -> ChatSigningPlan { // These are structural descriptors for pure codec tests. They supply // neither authenticated ciphertext nor a verified relay advertisement. - let command = prepared.request().command(); + let command = prepared.request().chat_command().unwrap(); let now = UnixSeconds::new(created).unwrap(); let rumor = ChatRumor::from_command(command, now).unwrap(); let recipient = rumor.recipients()[0]; diff --git a/crates/storage/src/command/snapshot.rs b/crates/storage/src/command/snapshot.rs @@ -336,11 +336,12 @@ impl OperationSnapshot { recipients: Vec<RecipientSnapshot>, observed_at: UnixSeconds, ) -> Result<Self, OperationError> { + retained.prepared().request().chat_command()?; if recipients.is_empty() || recipients.len() > 2 || observed_at.get() == 0 { return Err(OperationError::RecoveryRequired); } let prepared = retained.prepared(); - let command = prepared.request().command(); + let command = prepared.request().chat_command()?; let mut expected = vec![command.context().actor().participant(), command.peer()]; expected.sort_unstable(); expected.dedup(); @@ -472,7 +473,7 @@ impl OperationSnapshot { if !basis_linked { return Err(OperationError::RecoveryRequired); } - let command = bound.prepared().request().command(); + let command = bound.prepared().request().chat_command()?; let relation = match command.parent() { Some(parent) => ChatRelation::Reply { parent }, None => ChatRelation::Inquire { diff --git a/crates/storage_indexeddb/src/workspace/delivery/operations.rs b/crates/storage_indexeddb/src/workspace/delivery/operations.rs @@ -31,7 +31,7 @@ fn contains_original( .participant(); if candidate.work() != work || candidate.author() == actor - || candidate.author() == bound.prepared().request().command().peer() + || candidate.author() == bound.prepared().request().chat_command()?.peer() || candidate.author() == work.evidence().recipient() || source.digest() != work.evidence().digest() { diff --git a/crates/storage_indexeddb/src/workspace/installation.rs b/crates/storage_indexeddb/src/workspace/installation.rs @@ -205,7 +205,7 @@ impl BrowserWorkspace { }; let mut extra = Vec::with_capacity(3); if original.is_none() { - let raw = codec::message(bound, installed); + let raw = codec::message(bound, installed)?; let protected = crypto::seal_bound( state.provider.as_ref(), &state.reference, diff --git a/crates/storage_indexeddb/src/workspace/installation/codec.rs b/crates/storage_indexeddb/src/workspace/installation/codec.rs @@ -72,20 +72,28 @@ fn selectors( .map_err(|_| OperationError::RecoveryRequired)?; Ok((transaction, time, recipient)) } -pub(super) fn message(bound: &BoundSigningPlan, value: ChatInstallation) -> Zeroizing<Vec<u8>> { - encode( +pub(super) fn message( + bound: &BoundSigningPlan, + value: ChatInstallation, +) -> Result<Zeroizing<Vec<u8>>, OperationError> { + Ok(encode( MESSAGE, [ value.plan_digest(), value.message_id().as_bytes(), - bound.prepared().request().command().thread_id().as_bytes(), + bound + .prepared() + .request() + .chat_command()? + .thread_id() + .as_bytes(), value.preparation_transaction_id().as_bytes(), value.plan_transaction_id().as_bytes(), value.transaction_id().as_bytes(), ], value.installed_at(), value.basis(), - ) + )) } pub(super) fn decode_message( raw: &[u8], @@ -99,7 +107,7 @@ pub(super) fn decode_message( transaction, time, )?; - if message(bound, report).as_slice() != raw { + if message(bound, report)?.as_slice() != raw { return Err(OperationError::RecoveryRequired); } Ok(report) diff --git a/crates/storage_indexeddb/src/workspace/journal.rs b/crates/storage_indexeddb/src/workspace/journal.rs @@ -348,6 +348,11 @@ impl BrowserWorkspace { let state = self.state.clone(); let result = owned(work, async move { let access = state.operation_access(request.binding(), proof).await?; + // The current browser writer has no public signing/installation + // continuation. Refuse before admitting unsupported public work. + if request.command().listing().is_some() { + return Err(OperationError::UnsupportedOperation); + } let context = request.command().context(); let operation = context.operation_id(); let view = state.read_view(operation).await?; @@ -364,14 +369,10 @@ impl BrowserWorkspace { context.actor(), Some(request.command().digest()), )?; + protected::same_binding(existing.request().binding(), request.binding())?; (existing, None, false) } else { - if request.command().parent().is_some() || context.expected().is_some() { - return Err(OperationError::MissingHistory); - } - if context.approval().is_some() { - return Err(OperationError::UnverifiedApproval); - } + request.validate_fresh(access.binding.observed_at())?; if access.binding.observed_at() < request.binding().observed_at() { return Err(WorkspaceError::Unavailable.into()); } @@ -444,6 +445,7 @@ impl BrowserWorkspace { let result = state.preparation(operation, &records).await?; if let Some(prepared) = &result { protected::check_digest(prepared, binding.actor(), digest)?; + protected::same_binding(prepared.request().binding(), &binding)?; } let mut change = OperationChange::observe(records); if result.is_none() { diff --git a/crates/storage_indexeddb/src/workspace/plans.rs b/crates/storage_indexeddb/src/workspace/plans.rs @@ -155,7 +155,7 @@ impl State { Ok(()) })?; } - let plan = ChatSigningPlan::parse(prepared.request().command(), &wire) + let plan = ChatSigningPlan::parse(prepared.request().chat_command()?, &wire) .map_err(|_| OperationError::RecoveryRequired)?; if plan.digest() != manifest.plan_digest().as_bytes() { return Err(OperationError::RecoveryRequired); @@ -247,9 +247,11 @@ impl BrowserWorkspace { if observed >= window.first_issue_not_after() { return Err(OperationError::DeadlineExceeded); } - let checked = - ChatSigningPlan::parse(prepared.request().command(), supplied.protected_wire()) - .map_err(|_| OperationError::InvalidCommand)?; + let checked = ChatSigningPlan::parse( + prepared.request().chat_command()?, + supplied.protected_wire(), + ) + .map_err(|_| OperationError::InvalidCommand)?; drop(supplied); let transaction = TransactionId::from_bytes(*crypto::random::<32>()?); let manifest = PlanManifest::capture(&prepared, &checked, transaction, observed)?; diff --git a/crates/storage_indexeddb/src/workspace/retained.rs b/crates/storage_indexeddb/src/workspace/retained.rs @@ -108,7 +108,7 @@ impl Graph { Some(RetainedOperation::Planned(Box::new(bound))) } Some(RetainedOperation::Prepared(prepared)) => { - let command = prepared.request().command(); + let command = prepared.request().chat_command()?; let mut keys = vec![command.context().actor().participant(), command.peer()]; keys.sort_unstable(); keys.dedup(); diff --git a/crates/storage_indexeddb/tests/browser/seller.mjs b/crates/storage_indexeddb/tests/browser/seller.mjs @@ -32,7 +32,9 @@ async function workflow({WorkspaceFixture}, previous) { check(await seller.is_seller()); check(await seller.authenticate() === 1); await refuses(() => seller.wrong_proof(), 'unauthorized'); - tests.push('explicit protected seller scope and exact credential'); + await refuses(() => seller.admit_public(244), 'capability_unavailable'); + check((await seller.query(244)).length === 0); + tests.push('explicit protected seller scope, exact credential and unsupported public refusal without a row'); const fingerprint = seller.fingerprint(), selection = seller.selection(), proof = seller.proof(); const preparation = Array.from(await seller.admit(244, false)); await seller.close(); diff --git a/crates/storage_indexeddb/tests/browser/src/workspace.rs b/crates/storage_indexeddb/tests/browser/src/workspace.rs @@ -147,6 +147,29 @@ impl WorkspaceFixture { AdmissionOutcome::Unknown(_) => Err(JsValue::from_str("commit_unknown")), } } + pub async fn admit_public(&self, n: u8) -> Result<(), JsValue> { + let request = self.request(n, false).await?; + let input = serde_json::json!({"id":"01".repeat(16),"title":"Carrots","summary":"Quote required", + "description_markdown":"Public terms","published_at":"1000","profile":{ + "profile":"radroots.listing","version":1,"state":"active", + "product":{"name":"Carrots","description":"","producer":null,"origin_summary":null}, + "default_option":"02".repeat(32),"options":[{"id":"02".repeat(32),"label":"One bunch", + "unit":{"type":"package","label":"bunch","contents":{"type":"unspecified"}}, + "increment":"1","minimum":"1","price":{"type":"quote_required"}, + "supply":{"type":"unknown"},"lead_seconds":"0"}], + "fulfillment":{"modes":["pickup"],"area":"Example region","lead_seconds":"0"}, + "authority":null,"media":[]}}); + let wire = serde_json::to_vec(&serde_json::json!({"type":"listing.publish", + "context":request.command().context(),"input":input})) + .unwrap(); + let public = AdmissionRequest::from_protected_wire(request.binding().clone(), &wire) + .map_err(|e| JsValue::from_str(e.code()))?; + self.journal() + .admit_command_and_hold(public, copied(&self.proof)) + .await + .map_err(|e| JsValue::from_str(e.code()))?; + Err(JsValue::from_str("unexpected_public_commit")) + } pub async fn query(&self, n: u8) -> Result<Vec<u8>, JsValue> { let binding = self .owner diff --git a/crates/storage_indexeddb/tests/browser/src/workspace/delivery.rs b/crates/storage_indexeddb/tests/browser/src/workspace/delivery.rs @@ -278,7 +278,10 @@ impl WorkspaceFixture { } pub async fn query_envelope(&self, n: u8, index: u8, id: u8) -> Result<String, JsValue> { let request = self.request(n, false).await?; - let mut recipients = vec![self.input.participant(), request.command().peer()]; + let mut recipients = vec![ + self.input.participant(), + request.chat_command().unwrap().peer(), + ]; recipients.sort_unstable(); recipients.dedup(); let recipient: PublicKey = *recipients diff --git a/crates/storage_indexeddb/tests/browser/src/workspace/observations.rs b/crates/storage_indexeddb/tests/browser/src/workspace/observations.rs @@ -53,7 +53,10 @@ impl WorkspaceFixture { time: u32, ) -> Result<ObtainedObservation, JsValue> { let request = self.request(n, false).await?; - let mut recipients = vec![self.input.participant(), request.command().peer()]; + let mut recipients = vec![ + self.input.participant(), + request.chat_command().unwrap().peer(), + ]; recipients.sort_unstable(); recipients.dedup(); let attempt = self @@ -146,7 +149,10 @@ impl WorkspaceFixture { } pub async fn query_observations(&self, n: u8, index: u8, id: u8) -> Result<String, JsValue> { let request = self.request(n, false).await?; - let mut recipients = vec![self.input.participant(), request.command().peer()]; + let mut recipients = vec![ + self.input.participant(), + request.chat_command().unwrap().peer(), + ]; recipients.sort_unstable(); recipients.dedup(); self.journal() diff --git a/crates/storage_indexeddb/tests/browser/src/workspace/plans.rs b/crates/storage_indexeddb/tests/browser/src/workspace/plans.rs @@ -69,7 +69,7 @@ impl WorkspaceFixture { async fn plan_with_relays(&self, n: u8, profile: u8) -> Result<Vec<u8>, JsValue> { std::panic::set_hook(Box::new(|info| fixture_panic(&format!("{info}")))); let request = self.request(n, false).await?; - let command = request.command(); + let command = request.chat_command().unwrap(); let time = UnixSeconds::new(1000).unwrap(); let rumor = ChatRumor::from_command(command, time).unwrap(); let context = nostr::secp256k1::Secp256k1::new(); @@ -171,7 +171,7 @@ impl WorkspaceFixture { hook: js_sys::Function, ) -> Result<Vec<u8>, JsValue> { let request = self.request(n, false).await?; - let plan = ChatSigningPlan::parse(request.command(), &wire).unwrap(); + let plan = ChatSigningPlan::parse(request.chat_command().unwrap(), &wire).unwrap(); hook.call0(&JsValue::NULL)?; match self .journal() @@ -196,7 +196,7 @@ impl WorkspaceFixture { } pub async fn bind_plan_foreign(&self, n: u8, wire: Vec<u8>) -> Result<(), JsValue> { let request = self.request(n, false).await?; - let plan = ChatSigningPlan::parse(request.command(), &wire).unwrap(); + let plan = ChatSigningPlan::parse(request.chat_command().unwrap(), &wire).unwrap(); let sibling = self.sibling().await?; let foreign = sibling .owner @@ -224,7 +224,7 @@ impl WorkspaceFixture { } pub async fn abandon_plan(&self, n: u8, wire: Vec<u8>) -> Result<(), JsValue> { let request = self.request(n, false).await?; - let plan = ChatSigningPlan::parse(request.command(), &wire).unwrap(); + let plan = ChatSigningPlan::parse(request.chat_command().unwrap(), &wire).unwrap(); if self .journal() .bind_signing_intents(request.binding().clone(), plan, copied(&self.proof)) @@ -252,7 +252,7 @@ impl WorkspaceFixture { impl WorkspaceFixture { async fn bind_plan_mode(&self, n: u8, wire: Vec<u8>, mode: u8) -> Result<Vec<u8>, JsValue> { let request = self.request(n, false).await?; - let plan = ChatSigningPlan::parse(request.command(), &wire) + let plan = ChatSigningPlan::parse(request.chat_command().unwrap(), &wire) .map_err(|_| JsValue::from_str("invalid_plan"))?; if mode == 1 { self.clock.after.set(Some(1500)); diff --git a/crates/storage_sqlite/README.md b/crates/storage_sqlite/README.md @@ -1,5 +1,13 @@ # radroots_storage_sqlite +The separate execution-workspace database creates exact schema generation 8 +for shared chat/public non-stock preparation. `listing.publish` uses the same +operation identity, protected preparation, bounded worker and confirmed commit +classification as chat. Current seller authentication is required. T0 retains +data only; public signing, installation and delivery are separate stages. +The exact generation 7 catalog remains accepted for original chat recovery and +continuation. It refuses public admission without rewriting its catalog. + SQLite storage backend for Radroots. Startup and migration preserve typed `SpaceInsufficient` for numeric SQLite diff --git a/crates/storage_sqlite/src/workspace/admission.rs b/crates/storage_sqlite/src/workspace/admission.rs @@ -78,9 +78,11 @@ impl Journal<'_> { if current.observed_at() >= window.first_issue_not_after() { return Err(OperationError::DeadlineExceeded); } - let supplied = - ChatSigningPlan::parse(prepared.request().command(), supplied.protected_wire()) - .map_err(|_| OperationError::InvalidCommand)?; + let supplied = ChatSigningPlan::parse( + prepared.request().chat_command()?, + supplied.protected_wire(), + ) + .map_err(|_| OperationError::InvalidCommand)?; if supplied.created_at() < window.prepared_at() || supplied.created_at() > current.observed_at() { @@ -232,6 +234,15 @@ impl Journal<'_> { proof: AttachmentProof, ) -> Result<AdmissionOutcome, OperationError> { let (record, grant, observed) = self.access(request.binding(), &proof).await?; + if request.command().listing().is_some() { + let version: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&mut *self.connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + if version != 8 { + return Err(OperationError::UnsupportedOperation); + } + } let context = request.command().context(); let workspace = context.workspace_id(); let operation_id = context.operation_id(); @@ -241,6 +252,7 @@ impl Journal<'_> { operation::read(self.connection, self.selected, operation_id, self.crypto).await?; if let Some((snapshot, protected)) = existing { operation::check_digest(&snapshot, context.actor(), Some(digest))?; + same_binding(snapshot.request().binding(), request.binding())?; let anchor = snapshot.identity(); let mut transaction = self .connection @@ -270,14 +282,9 @@ impl Journal<'_> { return Ok(AdmissionOutcome::Committed(snapshot)); } - // This fresh local buyer namespace has no authenticated parent/order + // This fresh local outbox has no authenticated parent/order // history or protected approval origin. Selectors cannot create either. - if request.command().parent().is_some() || context.expected().is_some() { - return Err(OperationError::MissingHistory); - } - if context.approval().is_some() { - return Err(OperationError::UnverifiedApproval); - } + request.validate_fresh(observed.observed_at())?; if observed.observed_at() < request.binding().observed_at() { return Err(super::WorkspaceError::Unavailable.into()); } @@ -349,6 +356,7 @@ impl Journal<'_> { operation::read(self.connection, self.selected, operation_id, self.crypto).await?; if let Some((snapshot, _)) = &result { operation::check_digest(snapshot, binding.actor(), digest)?; + same_binding(snapshot.request().binding(), &binding)?; } let mut transaction = self .connection diff --git a/crates/storage_sqlite/src/workspace/delivery/graph_tests.rs b/crates/storage_sqlite/src/workspace/delivery/graph_tests.rs @@ -16,7 +16,7 @@ mod cases { let transaction = original.transaction_id(); let time = original.bound_at(); let (prepared, plan) = original.into_parts(); - let command = prepared.request().command(); + let command = prepared.request().chat_command().unwrap(); let rumor = ChatRumor::from_command(command, plan.created_at()).unwrap(); let seals = plan .seals() diff --git a/crates/storage_sqlite/src/workspace/delivery/operations.rs b/crates/storage_sqlite/src/workspace/delivery/operations.rs @@ -37,7 +37,7 @@ fn contains_original( .participant(); if candidate.work() != work || candidate.author() == actor - || candidate.author() == bound.prepared().request().command().peer() + || candidate.author() == bound.prepared().request().chat_command()?.peer() || candidate.author() == work.evidence().recipient() || source.digest() != work.evidence().digest() { diff --git a/crates/storage_sqlite/src/workspace/installation.rs b/crates/storage_sqlite/src/workspace/installation.rs @@ -70,18 +70,18 @@ struct MessageRecord { basis: EvidenceRef, } impl MessageRecord { - fn new(bound: &BoundSigningPlan, value: ChatInstallation) -> Self { - Self { + fn new(bound: &BoundSigningPlan, value: ChatInstallation) -> Result<Self, OperationError> { + Ok(Self { version: 1, plan_digest: *value.plan_digest(), message: value.message_id(), - thread: bound.prepared().request().command().thread_id(), + thread: bound.prepared().request().chat_command()?.thread_id(), preparation_transaction: value.preparation_transaction_id(), plan_transaction: value.plan_transaction_id(), transaction: value.transaction_id(), installed_at: value.installed_at(), basis: EvidenceRef::new(value.basis()), - } + }) } } #[derive(Serialize, Deserialize, Eq, PartialEq)] @@ -183,9 +183,15 @@ impl Records { encoded.transaction, encoded.installed_at, )?; - if encoded != MessageRecord::new(bound, report) + if encoded != MessageRecord::new(bound, report)? || bytes(&row, 0)? != report.message_id().as_bytes() - || bytes(&row, 1)? != bound.prepared().request().command().thread_id().as_bytes() + || bytes(&row, 1)? + != bound + .prepared() + .request() + .chat_command()? + .thread_id() + .as_bytes() || bytes(&row, 2)? != report.plan_digest() || bytes(&row, 3)? != report.transaction_id().as_bytes() { @@ -288,7 +294,7 @@ pub(super) async fn protect_message( crypto: &WorkspaceCrypto, ) -> Result<ProtectedMessage, OperationError> { let plaintext = Zeroizing::new( - serde_json::to_vec(&MessageRecord::new(bound, report)) + serde_json::to_vec(&MessageRecord::new(bound, report)?) .map_err(|_| OperationError::InvalidCommand)?, ); let protected = crypto @@ -301,7 +307,7 @@ pub(super) async fn protect_message( .await?; Ok(ProtectedMessage { report, - thread: bound.prepared().request().command().thread_id(), + thread: bound.prepared().request().chat_command()?.thread_id(), protected, }) } @@ -332,7 +338,7 @@ pub(super) async fn insert_message( ) -> Result<(), OperationError> { let report = value.report; sqlx::query("INSERT INTO chat_messages(workspace,message_id,operation_id,thread_id,plan_digest,transaction_id,protected) VALUES(?,?,?,?,?,?,?)") - .bind(report.workspace_id().as_bytes().as_slice()).bind(report.message_id().as_bytes().as_slice()).bind(report.operation_id().as_bytes().as_slice()).bind(bound.prepared().request().command().thread_id().as_bytes().as_slice()).bind(report.plan_digest().as_slice()).bind(report.transaction_id().as_bytes().as_slice()).bind(&value.protected).execute(connection).await.map_err(write_error)?; + .bind(report.workspace_id().as_bytes().as_slice()).bind(report.message_id().as_bytes().as_slice()).bind(report.operation_id().as_bytes().as_slice()).bind(bound.prepared().request().chat_command()?.thread_id().as_bytes().as_slice()).bind(report.plan_digest().as_slice()).bind(report.transaction_id().as_bytes().as_slice()).bind(&value.protected).execute(connection).await.map_err(write_error)?; Ok(()) } pub(super) async fn insert_work( diff --git a/crates/storage_sqlite/src/workspace/operation.rs b/crates/storage_sqlite/src/workspace/operation.rs @@ -5,7 +5,8 @@ use radroots_domain::{IssuanceWindow, OperationId, TransactionId}; use radroots_storage::command::{AdmissionRequest, OperationError, PreparedOperation}; use sqlx::{Row, SqliteConnection}; -pub(super) const TABLE: &str = "CREATE TABLE operations (workspace BLOB NOT NULL CHECK(length(workspace)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL CHECK(length(grant_id)=32), command_type TEXT NOT NULL CHECK(command_type IN ('inbox.inquire','inbox.reply')), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), phase TEXT NOT NULL CHECK(phase='prepared'), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), grant_singleton INTEGER NOT NULL CHECK(grant_singleton=1) REFERENCES workspace_grant(singleton), PRIMARY KEY(workspace,operation_id)) STRICT, WITHOUT ROWID"; +pub(super) const TABLE_V7: &str = "CREATE TABLE operations (workspace BLOB NOT NULL CHECK(length(workspace)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL CHECK(length(grant_id)=32), command_type TEXT NOT NULL CHECK(command_type IN ('inbox.inquire','inbox.reply')), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), phase TEXT NOT NULL CHECK(phase='prepared'), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), grant_singleton INTEGER NOT NULL CHECK(grant_singleton=1) REFERENCES workspace_grant(singleton), PRIMARY KEY(workspace,operation_id)) STRICT, WITHOUT ROWID"; +pub(super) const TABLE: &str = "CREATE TABLE operations (workspace BLOB NOT NULL CHECK(length(workspace)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL CHECK(length(grant_id)=32), command_type TEXT NOT NULL CHECK(command_type IN ('inbox.inquire','inbox.reply','listing.publish')), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), phase TEXT NOT NULL CHECK(phase='prepared'), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), grant_singleton INTEGER NOT NULL CHECK(grant_singleton=1) REFERENCES workspace_grant(singleton), PRIMARY KEY(workspace,operation_id)) STRICT, WITHOUT ROWID"; pub(super) const INDEX: &str = "CREATE UNIQUE INDEX operation_transaction_identity ON operations(workspace,transaction_id)"; diff --git a/crates/storage_sqlite/src/workspace/plan.rs b/crates/storage_sqlite/src/workspace/plan.rs @@ -180,7 +180,7 @@ pub(super) async fn read( })?; parts.push(protected); } - let plan = ChatSigningPlan::parse(prepared.request().command(), &wire) + let plan = ChatSigningPlan::parse(prepared.request().chat_command()?, &wire) .map_err(|_| OperationError::RecoveryRequired)?; if plan.digest() != &digest { return Err(OperationError::RecoveryRequired); diff --git a/crates/storage_sqlite/src/workspace/snapshot.rs b/crates/storage_sqlite/src/workspace/snapshot.rs @@ -124,7 +124,7 @@ impl RetainedGraph { } RetainedOperation::Planned(Box::new(bound)) } else { - let command = prepared.request().command(); + let command = prepared.request().chat_command()?; let mut keys = vec![command.context().actor().participant(), command.peer()]; keys.sort_unstable(); keys.dedup(); diff --git a/crates/storage_sqlite/src/workspace/tests/mod.rs b/crates/storage_sqlite/src/workspace/tests/mod.rs @@ -686,7 +686,7 @@ async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_r WorkspaceError::RecoveryRequired }; let statement = match fault { - 0 => "PRAGMA user_version=8", + 0 => "PRAGMA user_version=9", 1 => "DELETE FROM workspace_grant", 2 => "UPDATE workspace_grant SET grant_id=zeroblob(31)", 3 => "UPDATE workspace_grant SET protected=zeroblob(0)", @@ -732,7 +732,7 @@ async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_r .fetch_one(&mut connection) .await .unwrap(); - assert_eq!(version, if fault == 0 { 8 } else { 7 }); + assert_eq!(version, if fault == 0 { 9 } else { 8 }); assert_eq!(rows, if fault == 1 { 0 } else { 1 }); if let Some(expected) = retained_protected { let actual: Vec<u8> = sqlx::query_scalar("SELECT protected FROM workspace_grant") diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -589,6 +589,9 @@ impl Handle { Job::PrepareDelivery(..) => 1024 * 1024, Job::BindPlan(..) => 1024 * 1024, Job::Capture(..) | Job::RecoverCapture(..) => 256 * 1024, + // Public capture can retain a full 64 KiB wire plus decoded + // bounded fields. Include collection/descriptor ownership as well. + Job::Admit(request, ..) if request.command().listing().is_some() => 192 * 1024, Job::Admit(..) => 96 * 1024, _ => 16 * 1024, }; @@ -1010,7 +1013,7 @@ pub(super) async fn initialize( .await .map_err(|_| WorkspaceError::StorageFailure)?; } - sqlx::query("PRAGMA user_version=7") + sqlx::query("PRAGMA user_version=8") .execute(&mut *transaction) .await .map_err(|_| WorkspaceError::StorageFailure)?; @@ -1032,11 +1035,11 @@ pub(super) async fn initialize( .fetch_one(&mut *connection) .await .map_err(|_| WorkspaceError::RecoveryRequired)?; - if version != 7 { + if !matches!(version, 7 | 8) { return Err(WorkspaceError::RecoveryRequired); } let catalog_matches: i64 = sqlx::query_scalar("SELECT CASE WHEN count(*)=20 AND sum(CASE WHEN type='table' AND name='workspace_grant' AND tbl_name='workspace_grant' AND sql=? THEN 1 WHEN type='table' AND name='operations' AND tbl_name='operations' AND sql=? THEN 1 WHEN type='table' AND name='signing_plans' AND tbl_name='signing_plans' AND sql=? THEN 1 WHEN type='table' AND name='signing_plan_parts' AND tbl_name='signing_plan_parts' AND sql=? THEN 1 WHEN type='table' AND name='signing_attempts' AND tbl_name='signing_attempts' AND sql=? THEN 1 WHEN type='index' AND name='signing_attempt_identity' AND tbl_name='signing_attempts' AND sql=? THEN 1 WHEN type='index' AND name='signing_attempt_transaction_identity' AND tbl_name='signing_attempts' AND sql=? THEN 1 WHEN type='table' AND name='seal_evidence' AND tbl_name='seal_evidence' AND sql=? THEN 1 WHEN type='table' AND name='seal_evidence_parts' AND tbl_name='seal_evidence_parts' AND sql=? THEN 1 WHEN type='index' AND name='seal_evidence_transaction_identity' AND tbl_name='seal_evidence' AND sql=? THEN 1 WHEN type='index' AND name='operation_transaction_identity' AND tbl_name='operations' AND sql=? THEN 1 WHEN type='table' AND name='chat_messages' AND tbl_name='chat_messages' AND sql=? THEN 1 WHEN type='index' AND name='chat_message_operation_identity' AND tbl_name='chat_messages' AND sql=? THEN 1 WHEN type='index' AND name='chat_message_transaction_identity' AND tbl_name='chat_messages' AND sql=? THEN 1 WHEN type='index' AND name='chat_message_thread' AND tbl_name='chat_messages' AND sql=? THEN 1 WHEN type='table' AND name='chat_publication_work' AND tbl_name='chat_publication_work' AND sql=? THEN 1 WHEN type='table' AND name='chat_delivery_attempts' AND tbl_name='chat_delivery_attempts' AND sql=? THEN 1 WHEN type='table' AND name='chat_delivery_parts' AND tbl_name='chat_delivery_parts' AND sql=? THEN 1 WHEN type='index' AND name='chat_delivery_transaction_identity' AND tbl_name='chat_delivery_attempts' AND sql=? THEN 1 WHEN type='table' AND name='chat_delivery_observations' AND tbl_name='chat_delivery_observations' AND sql=? THEN 1 ELSE 0 END)=20 THEN 1 ELSE 0 END FROM sqlite_schema") - .bind(TABLE).bind(operation::TABLE).bind(plan::TABLE).bind(plan::PARTS).bind(attempt::TABLE).bind(attempt::ID_INDEX).bind(attempt::TX_INDEX).bind(evidence::TABLE).bind(evidence::PARTS).bind(evidence::TX_INDEX).bind(operation::INDEX).bind(installation::TABLE).bind(installation::OP_INDEX).bind(installation::TX_INDEX).bind(installation::THREAD_INDEX).bind(installation::WORK).bind(delivery::TABLE).bind(delivery::PARTS).bind(delivery::TX_INDEX).bind(delivery::OBSERVATIONS).fetch_one(&mut *connection).await.map_err(|_| WorkspaceError::RecoveryRequired)?; + .bind(TABLE).bind(if version==7 {operation::TABLE_V7} else {operation::TABLE}).bind(plan::TABLE).bind(plan::PARTS).bind(attempt::TABLE).bind(attempt::ID_INDEX).bind(attempt::TX_INDEX).bind(evidence::TABLE).bind(evidence::PARTS).bind(evidence::TX_INDEX).bind(operation::INDEX).bind(installation::TABLE).bind(installation::OP_INDEX).bind(installation::TX_INDEX).bind(installation::THREAD_INDEX).bind(installation::WORK).bind(delivery::TABLE).bind(delivery::PARTS).bind(delivery::TX_INDEX).bind(delivery::OBSERVATIONS).fetch_one(&mut *connection).await.map_err(|_| WorkspaceError::RecoveryRequired)?; if catalog_matches != 1 { return Err(WorkspaceError::RecoveryRequired); } diff --git a/crates/storage_sqlite/tests/support/public_admission.rs b/crates/storage_sqlite/tests/support/public_admission.rs @@ -0,0 +1,403 @@ +//! Actual encrypted T0 only. No signature, installation or delivery is claimed. +use super::*; + +fn public_request( + binding: &WorkspaceBinding, + id: u8, + title: &str, + correlation: &str, +) -> AdmissionRequest { + let context = CommandContextData::new( + OperationId::from_bytes([id; 32]), + binding.actor(), + binding.input().workspace_id(), + binding.input().authority(), + binding.input().route_digest(), + None, + None, + UnixSeconds::new(150).unwrap(), + Some(CorrelationId::new(correlation).unwrap()), + ) + .unwrap(); + let wire = json!({"type":"listing.publish", "context":context,"input":{ + "id":"01".repeat(16),"title":title,"summary":"Quote required","description_markdown":"Public terms", + "published_at":"100","profile":{"profile":"radroots.listing","version":1,"state":"active", + "product":{"name":"Carrots","description":"Public description","producer":null,"origin_summary":null}, + "default_option":"02".repeat(32),"options":[{"id":"02".repeat(32),"label":"One bunch", + "unit":{"type":"package","label":"bunch","contents":{"type":"unspecified"}},"increment":"1", + "minimum":"1","price":{"type":"quote_required"},"supply":{"type":"available","amount":"10"},"lead_seconds":"0"}], + "fulfillment":{"modes":["pickup"],"area":"Example region","lead_seconds":"0"},"authority":null,"media":[]}}}); + AdmissionRequest::from_protected_wire(binding.clone(), &serde_json::to_vec(&wire).unwrap()) + .unwrap() +} +async fn count(fixture: &Fixture) -> i64 { + let mut db = fixture.database().await; + let count = sqlx::query_scalar("SELECT count(*) FROM operations") + .fetch_one(&mut db) + .await + .unwrap(); + db.close().await.unwrap(); + count +} + +#[tokio::test] +async fn public_t0_reopen_replay_retains_original_bytes_and_uses_the_same_operation_namespace() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create_scoped(200, true).await; + let captured = public_request(&binding, 70, "public-preparation-carrots", "first"); + let digest = captured.command().digest(); + let wire = captured.command().protected_wire().to_vec(); + let original = committed( + store + .admit_command_and_hold(captured, copy(&proof)) + .await + .unwrap(), + ); + let anchor = original.identity(); + assert_eq!(original.revision().get(), 1); + assert!(original.request().command().listing().is_some()); + assert_eq!( + original.request().chat_command().err(), + Some(OperationError::UnsupportedOperation) + ); + store.close().await.unwrap(); + for name in ["execution_v1.sqlite", "execution_v1.sqlite-wal"] { + if let Ok(bytes) = std::fs::read(fixture.path.join(name)) { + assert!( + !bytes + .windows(b"public-preparation-carrots".len()) + .any(|w| w == b"public-preparation-carrots") + ); + } + } + fixture.clock.now.store(160, Ordering::SeqCst); + let reopened = fixture.reopen(input).await; + let retained = reopened + .operation( + binding.clone(), + anchor.operation_id(), + Some(digest), + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(retained.identity(), anchor); + assert_eq!(retained.issuance_window(), original.issuance_window()); + assert_eq!(retained.request().command().protected_wire(), wire); + let replay = committed( + reopened + .admit_command_and_hold( + public_request(&binding, 70, "public-preparation-carrots", "second"), + copy(&proof), + ) + .await + .unwrap(), + ); + assert_eq!(replay.identity(), anchor); + assert_eq!(replay.request().command().protected_wire(), wire); + for captured in [ + public_request(&binding, 70, "changed terms", "second"), + request(&binding, 70, "different family", "second"), + ] { + assert!(matches!( + reopened + .admit_command_and_hold(captured, copy(&proof)) + .await, + Err(OperationError::IdempotencyConflict) + )); + } + assert!(matches!( + reopened + .admit_command_and_hold( + public_request(&binding, 71, "new expired work", "second"), + copy(&proof) + ) + .await, + Err(OperationError::DeadlineExceeded) + )); + assert_eq!(count(&fixture).await, 1); + reopened.close().await.unwrap(); +} + +#[tokio::test] +async fn public_t0_requires_actual_seller_access_and_refuses_unverified_prerequisites_without_rows() +{ + let buyer = Fixture::new(); + let (store, _, proof, binding) = buyer.create().await; + assert!(matches!( + store + .admit_command_and_hold( + public_request(&binding, 72, "wrong scope", "one"), + copy(&proof) + ) + .await, + Err(OperationError::Unauthorized) + )); + assert_eq!(count(&buyer).await, 0); + store.close().await.unwrap(); + let seller = Fixture::new(); + let (store, input, proof, binding) = seller.create_scoped(200, true).await; + let wrong = AttachmentProof::from_protected_input(&[0; 32]).unwrap(); + assert!(matches!( + store + .admit_command_and_hold(public_request(&binding, 72, "wrong proof", "one"), wrong) + .await, + Err(OperationError::Workspace(WorkspaceError::Unauthorized)) + )); + let captured = public_request(&binding, 72, "prerequisites", "one"); + let base: serde_json::Value = + serde_json::from_slice(captured.command().protected_wire()).unwrap(); + for (field, value, expected) in [ + ( + "approval", + json!({"intent_digest":"22".repeat(32),"scope":"unverified","expires_at":"150"}), + OperationError::UnverifiedApproval, + ), + ( + "expected", + serde_json::to_value(radroots_domain::ExpectedOrder::new( + radroots_domain::OrderId::from_bytes([0x33; 32]), + None, + radroots_domain::Sequence::new(1).unwrap(), + None, + binding.input().checkpoint().clone(), + )) + .unwrap(), + OperationError::MissingHistory, + ), + ] { + let mut wire = base.clone(); + wire["context"][field] = value; + let request = AdmissionRequest::from_protected_wire( + binding.clone(), + &serde_json::to_vec(&wire).unwrap(), + ) + .unwrap(); + assert!( + matches!(store.admit_command_and_hold(request,copy(&proof)).await,Err(error) if error==expected) + ); + } + assert_eq!(count(&seller).await, 0); + store.revoke(input, &proof).await.unwrap(); + assert!(matches!( + store + .admit_command_and_hold(public_request(&binding, 72, "revoked", "one"), copy(&proof)) + .await, + Err(OperationError::Workspace(WorkspaceError::GrantRevoked)) + )); + assert_eq!(count(&seller).await, 0); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn accepted_public_t0_survives_observer_loss_and_close_drains_the_existing_owner() { + use futures::FutureExt; + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create_scoped(200, true).await; + let captured = public_request(&binding, 73, "retained after observer loss", "one"); + let digest = captured.command().digest(); + let (arrived, resume) = fixture.clock.arm(0); + assert!( + store + .admit_command_and_hold(captured, copy(&proof)) + .now_or_never() + .is_none() + ); + reached(arrived).await; + resume.send(()).unwrap(); + store.close().await.unwrap(); + let reopened = fixture.reopen(input).await; + let retained = reopened + .operation( + binding, + OperationId::from_bytes([73; 32]), + Some(digest), + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + assert!(retained.request().command().listing().is_some()); + assert_eq!(count(&fixture).await, 1); + reopened.close().await.unwrap(); +} + +#[tokio::test] +async fn public_queue_counts_decoded_ownership_and_releases_budget_after_draining() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create_scoped(200, true).await; + let (arrived, resume) = fixture.clock.arm(1); + let owner = store.clone(); + let first = public_request(&binding, 100, "first", "one"); + let secret = copy(&proof); + let blocked = tokio::spawn(async move { owner.admit_command_and_hold(first, secret).await }); + reached(arrived).await; + let mut queued = Vec::new(); + // Twenty queued plus one in-flight public capture consume 4032 KiB. + for id in 1..=20 { + let mut future = store + .admit_command_and_hold(public_request(&binding, id, "queued", "one"), copy(&proof)); + assert!(futures::poll!(future.as_mut()).is_pending()); + queued.push(future); + } + assert!(matches!( + store + .admit_command_and_hold( + public_request(&binding, 21, "overflow", "one"), + copy(&proof) + ) + .await, + Err(OperationError::Workspace(WorkspaceError::Unavailable)) + )); + resume.send(()).unwrap(); + committed(blocked.await.unwrap().unwrap()); + store.close().await.unwrap(); + for future in queued { + assert!( + committed(future.await.unwrap()) + .request() + .command() + .listing() + .is_some() + ); + } + assert_eq!(count(&fixture).await, 21); + let reopened = fixture.reopen(input).await; + assert!( + reopened + .operation( + binding.clone(), + OperationId::from_bytes([21; 32]), + None, + copy(&proof) + ) + .await + .unwrap() + .is_none() + ); + committed( + reopened + .admit_command_and_hold( + public_request(&binding, 21, "after drain", "one"), + copy(&proof), + ) + .await + .unwrap(), + ); + assert_eq!(count(&fixture).await, 22); + reopened.close().await.unwrap(); +} + +#[tokio::test] +async fn exact_generation_seven_retains_chat_without_rewrite_and_explicitly_refuses_public_writes() +{ + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create_scoped(200, true).await; + let original = committed( + store + .admit_command_and_hold( + request(&binding, 74, "original chat", "first"), + copy(&proof), + ) + .await + .unwrap(), + ); + store.close().await.unwrap(); + // Construct the exact old catalog around unchanged encrypted rows. This is + // a retained-schema fixture, not a claim that an old binary was executed. + let mut db = fixture.database().await; + let current: String = + sqlx::query_scalar("SELECT sql FROM sqlite_schema WHERE name='operations'") + .fetch_one(&mut db) + .await + .unwrap(); + let index: String = sqlx::query_scalar( + "SELECT sql FROM sqlite_schema WHERE name='operation_transaction_identity'", + ) + .fetch_one(&mut db) + .await + .unwrap(); + let legacy = current.replace("'inbox.reply','listing.publish'", "'inbox.reply'"); + assert_ne!(legacy, current); + for sql in [ + "CREATE TEMP TABLE retained_operations AS SELECT * FROM operations", + "DROP TABLE operations", + &legacy, + &index, + "INSERT INTO operations SELECT * FROM retained_operations", + "DROP TABLE retained_operations", + "PRAGMA user_version=7", + ] { + // Only exact catalog SQL read from our own synthetic database is used. + sqlx::query(sqlx::AssertSqlSafe(sql.to_owned())) + .execute(&mut db) + .await + .unwrap(); + } + db.close().await.unwrap(); + let reopened = fixture.reopen(input.clone()).await; + let retained = reopened + .operation( + binding.clone(), + original.identity().operation_id(), + Some(original.identity().command_digest()), + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(retained.identity(), original.identity()); + assert_eq!( + retained.request().command().protected_wire(), + original.request().command().protected_wire() + ); + committed( + reopened + .admit_command_and_hold( + request(&binding, 75, "continued chat", "next"), + copy(&proof), + ) + .await + .unwrap(), + ); + assert!(matches!( + reopened + .admit_command_and_hold( + public_request(&binding, 76, "unsupported public", "one"), + copy(&proof) + ) + .await, + Err(OperationError::UnsupportedOperation) + )); + reopened.close().await.unwrap(); + let mut db = fixture.database().await; + let version: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&mut db) + .await + .unwrap(); + assert_eq!(version, 7); + let retained_sql: String = + sqlx::query_scalar("SELECT sql FROM sqlite_schema WHERE name='operations'") + .fetch_one(&mut db) + .await + .unwrap(); + assert_eq!(retained_sql, legacy); + assert_eq!(count(&fixture).await, 2); + // A misleading generation tag never makes the new schema an old schema. + sqlx::query("PRAGMA user_version=8") + .execute(&mut db) + .await + .unwrap(); + db.close().await.unwrap(); + assert!(matches!( + NativeWorkspace::open_existing( + &fixture.path, + input, + fixture.crypto(), + fixture.clock.clone() + ) + .await, + Err(WorkspaceError::RecoveryRequired) + )); +} diff --git a/crates/storage_sqlite/tests/support/workspace_issuance.rs b/crates/storage_sqlite/tests/support/workspace_issuance.rs @@ -73,7 +73,11 @@ async fn prepare( .await .unwrap(), ); - let plan = plan(prepared.request().command(), 100, "native-issuance"); + let plan = plan( + prepared.request().chat_command().unwrap(), + 100, + "native-issuance", + ); let digest = *plan.digest(); let recipients = plan.seals().iter().map(|seal| seal.recipient()).collect(); bound( @@ -659,7 +663,11 @@ async fn missing_preparation_plan_and_attempt_are_distinct_from_wrong_plan_ident .unwrap() .is_none() ); - let retained = plan(prepared.request().command(), 100, "missing-claim"); + let retained = plan( + prepared.request().chat_command().unwrap(), + 100, + "missing-claim", + ); let digest = *retained.digest(); bound( store diff --git a/crates/storage_sqlite/tests/support/workspace_plans.rs b/crates/storage_sqlite/tests/support/workspace_plans.rs @@ -98,7 +98,7 @@ async fn complete_private_plan_commits_reopens_and_replays_exact_original_bytes_ .await .unwrap(), ); - let original = plan(prepared.request().command(), 100, "original"); + let original = plan(prepared.request().chat_command().unwrap(), 100, "original"); let wire = original.protected_wire().to_vec(); let digest = prepared.identity().command_digest(); let operation = prepared.identity().operation_id(); @@ -122,7 +122,7 @@ async fn complete_private_plan_commits_reopens_and_replays_exact_original_bytes_ prepared.transaction_id() ); let transaction = retained.transaction_id(); - let altered = plan(prepared.request().command(), 100, "changed"); + let altered = plan(prepared.request().chat_command().unwrap(), 100, "changed"); assert!(matches!( store .bind_signing_intents(binding.clone(), altered, copy(&proof)) @@ -130,7 +130,7 @@ async fn complete_private_plan_commits_reopens_and_replays_exact_original_bytes_ Err(OperationError::IdempotencyConflict) )); fixture.clock.now.store(151, Ordering::SeqCst); - let replay = ChatSigningPlan::parse(prepared.request().command(), &wire).unwrap(); + let replay = ChatSigningPlan::parse(prepared.request().chat_command().unwrap(), &wire).unwrap(); assert_eq!( bound( store @@ -186,7 +186,7 @@ async fn no_new_plan_commits_after_window_or_after_current_grant_revocation() { .await .unwrap(), ); - let supplied = plan(prepared.request().command(), 100, "one"); + let supplied = plan(prepared.request().chat_command().unwrap(), 100, "one"); if revoked { store.revoke(input, &proof).await.unwrap(); } else { @@ -229,7 +229,11 @@ async fn admitted_plan_outlives_its_observer_and_byte_budget_refuses_unadmitted_ let (arrived, resume) = fixture.clock.arm(0); let mut first = store.bind_signing_intents( binding.clone(), - plan(preparations[0].request().command(), 100, "one"), + plan( + preparations[0].request().chat_command().unwrap(), + 100, + "one", + ), copy(&proof), ); assert!(futures::poll!(first.as_mut()).is_pending()); @@ -239,7 +243,7 @@ async fn admitted_plan_outlives_its_observer_and_byte_budget_refuses_unadmitted_ for prepared in &preparations[1..4] { let mut next = store.bind_signing_intents( binding.clone(), - plan(prepared.request().command(), 100, "one"), + plan(prepared.request().chat_command().unwrap(), 100, "one"), copy(&proof), ); assert!(futures::poll!(next.as_mut()).is_pending()); @@ -249,7 +253,11 @@ async fn admitted_plan_outlives_its_observer_and_byte_budget_refuses_unadmitted_ store .bind_signing_intents( binding.clone(), - plan(preparations[4].request().command(), 100, "one"), + plan( + preparations[4].request().chat_command().unwrap(), + 100, + "one" + ), copy(&proof) ) .await, @@ -298,7 +306,7 @@ async fn expiry_during_protection_and_known_sql_rollback_preserve_unbound_prepar .await .unwrap(), ); - let supplied = plan(prepared.request().command(), 100, "one"); + let supplied = plan(prepared.request().chat_command().unwrap(), 100, "one"); let mut database = fixture.database().await; if !expire { sqlx::raw_sql("CREATE TRIGGER reject_plan BEFORE INSERT ON signing_plan_parts WHEN NEW.part=2 BEGIN SELECT RAISE(ABORT,'synthetic storage failure'); END").execute(&mut database).await.unwrap(); @@ -355,7 +363,7 @@ async fn unknown_plan_completion_latches_until_reopen_and_preserves_original_ope .await .unwrap(), ); - let supplied = plan(prepared.request().command(), 100, "one"); + let supplied = plan(prepared.request().chat_command().unwrap(), 100, "one"); let mut database = fixture.database().await; sqlx::raw_sql("CREATE TRIGGER unknown_plan BEFORE INSERT ON signing_plan_parts WHEN NEW.part=2 BEGIN SELECT RAISE(ROLLBACK,'synthetic unknown completion'); END").execute(&mut database).await.unwrap(); let outcome = store @@ -420,7 +428,7 @@ async fn retained_plan_refuses_index_manifest_and_part_substitution_without_repa store .bind_signing_intents( binding.clone(), - plan(prepared.request().command(), 100, "one"), + plan(prepared.request().chat_command().unwrap(), 100, "one"), copy(&proof), ) .await diff --git a/crates/storage_sqlite/tests/workspace_admission.rs b/crates/storage_sqlite/tests/workspace_admission.rs @@ -3,6 +3,9 @@ #[path = "support/workspace_plans.rs"] mod plans; +#[path = "support/public_admission.rs"] +mod public_admission; + use radroots_domain::{ CommandContextData, CommandDigest, CorrelationId, OperationId, PublicKey, UnixSeconds, }; @@ -147,9 +150,26 @@ impl Fixture { AttachmentProof, WorkspaceBinding, ) { + self.create_scoped(expiry, false).await + } + async fn create_scoped( + &self, + expiry: u64, + seller: bool, + ) -> ( + Arc<NativeWorkspace>, + AttachmentInput, + AttachmentProof, + WorkspaceBinding, + ) { + let config = if seller { + LocalOutboxConfig::seller + } else { + LocalOutboxConfig::new + }; let (store, input, proof) = NativeWorkspace::initialize_local_outbox( &self.path, - LocalOutboxConfig::new( + config( key(), key(), "synthetic-device", @@ -253,7 +273,7 @@ async fn actual_commit_reopen_and_replay_preserve_original_identity_and_private_ let anchor = original.identity(); assert_eq!(original.revision().get(), 1); assert_eq!( - original.request().command().text(), + original.request().chat_command().unwrap().text(), "private-cabbage-inquiry-🧺" ); assert_eq!(original.request().binding().input(), &input); @@ -444,7 +464,7 @@ async fn lost_observer_does_not_cancel_admitted_transaction_and_close_drains_it( .unwrap() .unwrap(); assert_eq!( - result.request().command().text(), + result.request().chat_command().unwrap().text(), "retained after observer cancellation" ); reopened.close().await.unwrap();