commit dc04b333826e1e7f0e2bee4f69bf6fd309ca91d5 parent b8647038b643979ba69b7925a8eb7747e025ae62 Author: triesap <tyson@radroots.org> Date: Sat, 17 Oct 2026 23:47:15 +0000 execution: retain protected native chat preparations - Capture closed chat data and exact canonical command commitments. - Commit authenticated buyer inquiry preparation on the owned SQLite journal. - Preserve original replay identity and classify uncertain completion safely. - Verify protected reopen, cancellation, boundaries and portable APIs. Diffstat:
41 files changed, 3441 insertions(+), 45 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock @@ -3288,8 +3288,11 @@ dependencies = [ name = "radroots_protocol" version = "0.1.0-alpha" dependencies = [ + "radroots_domain", "serde", "serde_json", + "sha2", + "zeroize", ] [[package]] diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt @@ -165,6 +165,20 @@ impl serde_core::ser::Serialize for radroots_domain::Decimal pub fn radroots_domain::Decimal::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::Decimal pub fn radroots_domain::Decimal::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::EnvelopeEventId(_) +impl radroots_domain::EnvelopeEventId +pub const fn radroots_domain::EnvelopeEventId::as_bytes(&self) -> &[u8; 32] +pub const fn radroots_domain::EnvelopeEventId::from_bytes([u8; 32]) -> Self +pub const fn radroots_domain::EnvelopeEventId::into_bytes(self) -> [u8; 32] +impl core::fmt::Display for radroots_domain::EnvelopeEventId +pub fn radroots_domain::EnvelopeEventId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::EnvelopeEventId +pub type radroots_domain::EnvelopeEventId::Err = radroots_domain::IdentifierError +pub fn radroots_domain::EnvelopeEventId::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::EnvelopeEventId +pub fn radroots_domain::EnvelopeEventId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::EnvelopeEventId +pub fn radroots_domain::EnvelopeEventId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub struct radroots_domain::ExecutorId(_) impl radroots_domain::ExecutorId pub const fn radroots_domain::ExecutorId::as_bytes(&self) -> &[u8; 32] @@ -216,6 +230,20 @@ impl serde_core::ser::Serialize for radroots_domain::GrantId pub fn radroots_domain::GrantId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::GrantId pub fn radroots_domain::GrantId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::MessageId(_) +impl radroots_domain::MessageId +pub const fn radroots_domain::MessageId::as_bytes(&self) -> &[u8; 32] +pub const fn radroots_domain::MessageId::from_bytes([u8; 32]) -> Self +pub const fn radroots_domain::MessageId::into_bytes(self) -> [u8; 32] +impl core::fmt::Display for radroots_domain::MessageId +pub fn radroots_domain::MessageId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::MessageId +pub type radroots_domain::MessageId::Err = radroots_domain::IdentifierError +pub fn radroots_domain::MessageId::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::MessageId +pub fn radroots_domain::MessageId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::MessageId +pub fn radroots_domain::MessageId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub struct radroots_domain::OperationId(_) impl radroots_domain::OperationId pub const fn radroots_domain::OperationId::as_bytes(&self) -> &[u8; 32] @@ -331,6 +359,20 @@ impl serde_core::ser::Serialize for radroots_domain::ThreadId pub fn radroots_domain::ThreadId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::ThreadId pub fn radroots_domain::ThreadId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::TransactionId(_) +impl radroots_domain::TransactionId +pub const fn radroots_domain::TransactionId::as_bytes(&self) -> &[u8; 32] +pub const fn radroots_domain::TransactionId::from_bytes([u8; 32]) -> Self +pub const fn radroots_domain::TransactionId::into_bytes(self) -> [u8; 32] +impl core::fmt::Display for radroots_domain::TransactionId +pub fn radroots_domain::TransactionId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::TransactionId +pub type radroots_domain::TransactionId::Err = radroots_domain::IdentifierError +pub fn radroots_domain::TransactionId::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::TransactionId +pub fn radroots_domain::TransactionId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::TransactionId +pub fn radroots_domain::TransactionId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub struct radroots_domain::UnixSeconds(_) impl radroots_domain::UnixSeconds pub const fn radroots_domain::UnixSeconds::get(self) -> u64 diff --git a/contracts/api_baselines/radroots_protocol.txt b/contracts/api_baselines/radroots_protocol.txt @@ -62,6 +62,66 @@ pub const radroots_protocol::capability::v1::MAX_TRANSPORT_KIND_BYTES: usize pub const radroots_protocol::capability::v1::SCHEMAS: &[radroots_protocol::schema::Metadata] pub fn radroots_protocol::capability::v1::schema_registry() -> core::result::Result<radroots_protocol::schema::Registry, radroots_protocol::schema::Error> pub fn radroots_protocol::capability::v1::validate_catalog(&[radroots_protocol::capability::v1::TransportDescriptor]) -> core::result::Result<(), radroots_protocol::capability::v1::Error> +pub mod radroots_protocol::command +pub enum radroots_protocol::command::ChatKind +pub radroots_protocol::command::ChatKind::Inquire +pub radroots_protocol::command::ChatKind::Reply +impl radroots_protocol::command::ChatKind +pub const fn radroots_protocol::command::ChatKind::as_str(self) -> &'static str +#[non_exhaustive] pub enum radroots_protocol::command::CommandError +pub radroots_protocol::command::CommandError::InvalidInput +pub radroots_protocol::command::CommandError::LimitExceeded +pub radroots_protocol::command::CommandError::UnsupportedCommand +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 +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 +pub const fn radroots_protocol::command::CapturedChatCommand::context(&self) -> &radroots_domain::context::CommandContextData +pub const fn radroots_protocol::command::CapturedChatCommand::digest(&self) -> radroots_domain::identifier::CommandDigest +pub fn radroots_protocol::command::CapturedChatCommand::inquire(radroots_domain::context::CommandContextData, radroots_protocol::command::InquireInput) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub const fn radroots_protocol::command::CapturedChatCommand::kind(&self) -> radroots_protocol::command::ChatKind +pub const fn radroots_protocol::command::CapturedChatCommand::parent(&self) -> core::option::Option<radroots_domain::identifier::MessageId> +pub fn radroots_protocol::command::CapturedChatCommand::parse(&[u8]) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub const fn radroots_protocol::command::CapturedChatCommand::peer(&self) -> radroots_identity::key::PublicKey +pub fn radroots_protocol::command::CapturedChatCommand::protected_wire(&self) -> &[u8] +pub fn radroots_protocol::command::CapturedChatCommand::reply(radroots_domain::context::CommandContextData, radroots_protocol::command::ReplyInput) -> core::result::Result<Self, radroots_protocol::command::CommandError> +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::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 +impl radroots_protocol::command::InquireInput +pub fn radroots_protocol::command::InquireInput::new(radroots_domain::identifier::ThreadId, radroots_identity::key::PublicKey, core::option::Option<radroots_protocol::command::ListingRevisionRef>, &str) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub const fn radroots_protocol::command::InquireInput::peer(&self) -> radroots_identity::key::PublicKey +pub fn radroots_protocol::command::InquireInput::source(&self) -> core::option::Option<&radroots_protocol::command::ListingRevisionRef> +pub fn radroots_protocol::command::InquireInput::text(&self) -> &str +pub const fn radroots_protocol::command::InquireInput::thread_id(&self) -> radroots_domain::identifier::ThreadId +impl core::fmt::Debug for radroots_protocol::command::InquireInput +pub fn radroots_protocol::command::InquireInput::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_protocol::command::ListingRevisionRef +impl radroots_protocol::command::ListingRevisionRef +pub const fn radroots_protocol::command::ListingRevisionRef::author(&self) -> radroots_identity::key::PublicKey +pub fn radroots_protocol::command::ListingRevisionRef::d(&self) -> &str +pub const fn radroots_protocol::command::ListingRevisionRef::event_id(&self) -> radroots_domain::identifier::SourceId +pub fn radroots_protocol::command::ListingRevisionRef::new(radroots_identity::key::PublicKey, &str, radroots_domain::identifier::SourceId) -> core::result::Result<Self, radroots_protocol::command::CommandError> +impl core::fmt::Debug for radroots_protocol::command::ListingRevisionRef +pub fn radroots_protocol::command::ListingRevisionRef::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl serde_core::ser::Serialize for radroots_protocol::command::ListingRevisionRef +pub fn radroots_protocol::command::ListingRevisionRef::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +pub struct radroots_protocol::command::ReplyInput +impl radroots_protocol::command::ReplyInput +pub fn radroots_protocol::command::ReplyInput::new(radroots_domain::identifier::ThreadId, radroots_identity::key::PublicKey, radroots_domain::identifier::MessageId, &str) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub const fn radroots_protocol::command::ReplyInput::parent(&self) -> radroots_domain::identifier::MessageId +pub const fn radroots_protocol::command::ReplyInput::peer(&self) -> radroots_identity::key::PublicKey +pub fn radroots_protocol::command::ReplyInput::text(&self) -> &str +pub const fn radroots_protocol::command::ReplyInput::thread_id(&self) -> radroots_domain::identifier::ThreadId +impl core::fmt::Debug for radroots_protocol::command::ReplyInput +pub fn radroots_protocol::command::ReplyInput::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub const radroots_protocol::command::CHAT_MAX_BYTES: usize +pub const radroots_protocol::command::COMMAND_MAX_BYTES: usize pub mod radroots_protocol::error pub mod radroots_protocol::error::v1 pub enum radroots_protocol::error::v1::Class diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -756,6 +756,57 @@ pub fn radroots_storage::memory::MemoryStorage::status(&self) -> radroots_transp pub fn radroots_storage::memory::MemoryStorage::transition_backup(&self, radroots_storage::backup::BackupId, radroots_storage::backup::ReliabilityRevision, radroots_storage::backup::BackupTransition, u64) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::backup::BackupOperation, radroots_storage::Error>> pub fn radroots_storage::memory::MemoryStorage::transition_restore(&self, radroots_storage::backup::BackupId, radroots_storage::backup::ReliabilityRevision, radroots_storage::backup::RestoreTransition, u64) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::backup::RestoreOperation, radroots_storage::Error>> pub fn radroots_storage::memory::MemoryStorage::verify_backup(&self, radroots_storage::backup::BackupPlan, radroots_storage::backup::BackupManifest) -> radroots_transport::source::BoxFuture<'_, core::result::Result<(), radroots_storage::backup::BackupCapabilityError>> +pub mod radroots_storage::command +pub enum radroots_storage::command::AdmissionOutcome +pub radroots_storage::command::AdmissionOutcome::Committed(radroots_storage::command::PreparedOperation) +pub radroots_storage::command::AdmissionOutcome::Unknown(radroots_storage::command::CommitAttempt) +impl core::fmt::Debug for radroots_storage::command::AdmissionOutcome +pub fn radroots_storage::command::AdmissionOutcome::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_storage::command::OperationError +pub radroots_storage::command::OperationError::DeadlineExceeded +pub radroots_storage::command::OperationError::IdempotencyConflict +pub radroots_storage::command::OperationError::InvalidCommand +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::UnverifiedApproval +pub radroots_storage::command::OperationError::Workspace(radroots_storage::workspace::WorkspaceError) +impl radroots_storage::command::OperationError +pub const fn radroots_storage::command::OperationError::code(self) -> &'static str +impl core::convert::From<radroots_storage::workspace::WorkspaceError> for radroots_storage::command::OperationError +pub fn radroots_storage::command::OperationError::from(radroots_storage::workspace::WorkspaceError) -> Self +impl core::error::Error for radroots_storage::command::OperationError +impl core::fmt::Display for radroots_storage::command::OperationError +pub fn radroots_storage::command::OperationError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +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::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> +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::CommitAttempt +impl radroots_storage::command::CommitAttempt +pub const fn radroots_storage::command::CommitAttempt::command_digest(self) -> radroots_domain::identifier::CommandDigest +pub const fn radroots_storage::command::CommitAttempt::new(radroots_domain::identifier::WorkspaceId, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, core::option::Option<radroots_domain::identifier::TransactionId>) -> Self +pub const fn radroots_storage::command::CommitAttempt::operation_id(self) -> radroots_domain::identifier::OperationId +pub const fn radroots_storage::command::CommitAttempt::transaction_id(self) -> core::option::Option<radroots_domain::identifier::TransactionId> +pub const fn radroots_storage::command::CommitAttempt::workspace_id(self) -> radroots_domain::identifier::WorkspaceId +pub struct radroots_storage::command::PreparedOperation +impl radroots_storage::command::PreparedOperation +pub fn radroots_storage::command::PreparedOperation::from_committed_store(radroots_storage::command::AdmissionRequest, radroots_domain::identifier::TransactionId, radroots_domain::context::Sequence) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub fn radroots_storage::command::PreparedOperation::identity(&self) -> radroots_storage::command::CommitAttempt +pub const fn radroots_storage::command::PreparedOperation::request(&self) -> &radroots_storage::command::AdmissionRequest +pub const fn radroots_storage::command::PreparedOperation::revision(&self) -> radroots_domain::context::Sequence +pub const fn radroots_storage::command::PreparedOperation::transaction_id(&self) -> radroots_domain::identifier::TransactionId +impl core::fmt::Debug for radroots_storage::command::PreparedOperation +pub fn radroots_storage::command::PreparedOperation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub trait radroots_storage::command::OperationJournal: radroots_storage::workspace::WorkspaceStore +pub fn radroots_storage::command::OperationJournal::admit_command_and_hold(&self, radroots_storage::command::AdmissionRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::AdmissionOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage::command::OperationJournal::operation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::PreparedOperation>, radroots_storage::command::OperationError>> pub mod radroots_storage::event pub use radroots_storage::event::BoxFuture pub use radroots_storage::event::EventId @@ -1838,6 +1889,8 @@ pub radroots_storage::workspace::WorkspaceError::WriterActive pub radroots_storage::workspace::WorkspaceError::WrongNamespace impl radroots_storage::workspace::WorkspaceError pub const fn radroots_storage::workspace::WorkspaceError::code(self) -> &'static str +impl core::convert::From<radroots_storage::workspace::WorkspaceError> for radroots_storage::command::OperationError +pub fn radroots_storage::command::OperationError::from(radroots_storage::workspace::WorkspaceError) -> Self impl core::error::Error for radroots_storage::workspace::WorkspaceError impl core::fmt::Display for radroots_storage::workspace::WorkspaceError pub fn radroots_storage::workspace::WorkspaceError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -379,6 +379,9 @@ pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::open_existing( pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::revoke(&self, radroots_storage::workspace::AttachmentInput, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> impl core::fmt::Debug for radroots_storage_sqlite::workspace::NativeWorkspace pub fn radroots_storage_sqlite::workspace::NativeWorkspace::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl radroots_storage::command::OperationJournal for radroots_storage_sqlite::workspace::NativeWorkspace +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::admit_command_and_hold(&self, radroots_storage::command::AdmissionRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::AdmissionOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::operation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::PreparedOperation>, radroots_storage::command::OperationError>> impl radroots_storage::workspace::WorkspaceStore for radroots_storage_sqlite::workspace::NativeWorkspace pub fn radroots_storage_sqlite::workspace::NativeWorkspace::authenticate(&self, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::WorkspaceError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::close_workspace(&self) -> radroots_transport::source::BoxFuture<'_, core::result::Result<(), radroots_storage::workspace::WorkspaceError>> diff --git a/contracts/architecture/deviations.toml b/contracts/architecture/deviations.toml @@ -2,6 +2,33 @@ schema_version = 1 architecture_id = "radroots.crates.release.v1" [[deviation]] +id = "RCRV1-DEV-053" +date = "2026-10-17" +status = "closed" +approval = "The user authorizes the complete approved shared SDK refactor, its required breaking dependency closure, verified source checkpoints and master publication." +affected_steps = ["040", "050", "060", "110", "120", "130"] +spec_anchors = ["contracts/crates/release_v1/radroots_crates_release_v1.toml#package.radroots_protocol"] +source_evidence = [ + "The approved shared_sdk_refactor.v1 machine decision requires protocol to import canonical domain values. The closed chat codec now uses that exact edge rather than duplicating IDs, context or exact-value models.", + "The actual dependency guard rejects protocol (foundation rank 0) importing domain (domain rank 1). Current catalog placement and the checked-in current dependency-tier policy still encode the predecessor graph.", +] +replacement_action = "Activate the already-approved protocol-to-domain direction by placing protocol in the current catalog and dependency policy's domain tier and permitting only foundation/domain dependencies. Regenerate catalog projections through catalog write. Preserve the historical Release V1 artifacts, immutable provenance and the unchanged all-kind same-or-lower dependency guard; add no exception or guard bypass. Protocol remains passive portable data/encoding and owns no domain reducer, storage, signer, network or executor." +verification = [ + "Preserve the original real upward-edge failure. Actual architecture preflight passes the prospective deviation and policy/catalog structure before placement correction; the separate actual Cargo dependency guard remains red until the current placement is reconciled.", + "Run catalog generation/freshness, unchanged dependency/API guards, architecture and contract validation against the actual Cargo graph. Execute the retained dependency-boundary negative controls for domain-to-storage, SPI-to-adapter and orchestration-to-SDK directions.", + "Retain source-bound codec/native admission checks, reviewed APIs, portable composition and unchanged coverage gates. Classification supplies no runtime, full-receipt, consumer or release qualification.", +] +unresolved_risk = "The current classification activates one already-approved dependency edge only. Complete receipts, known-kind T1/S/T2/D, browser/bindings, supported consumer adoption and every final acceptance gate remain unfinished." +normative_architecture_change = true +adr_required = true +closure_evidence = [ + "Protocol now occupies the current domain tier in both catalog and dependency policy. Catalog projections are fresh; immutable provenance and every frozen Release V1 artifact remain unchanged. No dependency exception or production guard change was added.", + "All ten dependency-boundary cases pass, including the approved Protocol-to-Domain edge, retained upward-direction controls and new Protocol-to-Storage/Identity-to-Domain refusals. Tooling strict lint and actual API/dependency/architecture/catalog/contracts pass.", + "Closed command vectors, protected actual buyer preparation/reopen/replay, transaction-time authority/deadline and cancellation/unknown completion execute. The original indexed-shadow regression fails on unchanged production and passes after the private full-snapshot recheck correction. The original fixture compile, lint, interrupted run and coverage failures remain preserved.", + "All four owning unchanged ninety-percent coverage gates pass. SQLite branches measure 1207/1336 after the added actual corruption/captured-binding refusals and complete retained-fact recheck. Reviewed public APIs and portable codec/facade composition are retained at their exact source scope. Complete receipts, T1/S/T2/D, browser/bindings, supported consumer adoption and final acceptance remain unfinished.", +] + +[[deviation]] id = "RCRV1-DEV-052" date = "2026-10-17" status = "closed" diff --git a/contracts/coverage-profiles.toml b/contracts/coverage-profiles.toml @@ -8,6 +8,9 @@ no_default_features = false features = ["session", "signer_session", "client_session", "workspace_session"] test_threads = 1 +[profiles.crates."radroots_protocol"] +features = ["commands"] + [profiles.crates."radroots"] no_default_features = false features = ["native"] @@ -39,4 +42,5 @@ features = ["full"] test_threads = 1 [profiles.crates."radroots_storage"] +features = ["command_journal"] test_packages = ["radroots_storage_sqlite"] diff --git a/contracts/crates/catalog.v2.toml b/contracts/crates/catalog.v2.toml @@ -142,7 +142,7 @@ replaces = [] name = "radroots_protocol" path = "crates/protocol" state = "active" -tier = "foundation" +tier = "domain" visibility = "public_release" publish = true version = "0.1.0-alpha" @@ -150,7 +150,7 @@ license = "MIT OR Apache-2.0" platforms = ["any"] groups = ["coverage_required", "portable", "public_native"] owners = ["protocol"] -permitted_dependency_tiers = ["foundation"] +permitted_dependency_tiers = ["foundation", "domain"] provenance_kind = "imported" source_repository = "https://github.com/radrootslabs/lib" source_revision = "3f35c869c827b35b27e7a7d789d409e6c3def6a8" diff --git a/contracts/crates/generated/package_groups.v1.toml b/contracts/crates/generated/package_groups.v1.toml @@ -1,5 +1,5 @@ schema = "radroots.workspace.package-groups.v1" -catalog_sha256 = "b405314962f9fe5212288580d6376d4af51af0d731f90ae417576a9e8b55c4e3" +catalog_sha256 = "407a02944413642b772593c6bfd23967daccd0a21cb2daabef509aafa49f311a" [[group]] id = "boundaries" diff --git a/contracts/crates/generated/platform_inventory.v1.toml b/contracts/crates/generated/platform_inventory.v1.toml @@ -1,5 +1,5 @@ schema = "radroots.workspace.platform-inventory.v1" -catalog_sha256 = "b405314962f9fe5212288580d6376d4af51af0d731f90ae417576a9e8b55c4e3" +catalog_sha256 = "407a02944413642b772593c6bfd23967daccd0a21cb2daabef509aafa49f311a" [[platform]] id = "any" diff --git a/contracts/crates/generated/release_inventory.v2.toml b/contracts/crates/generated/release_inventory.v2.toml @@ -1,5 +1,5 @@ schema = "radroots.workspace.release-inventory.v2" -catalog_sha256 = "b405314962f9fe5212288580d6376d4af51af0d731f90ae417576a9e8b55c4e3" +catalog_sha256 = "407a02944413642b772593c6bfd23967daccd0a21cb2daabef509aafa49f311a" architecture = "radroots.crates.release.v2" version = "0.1.0-alpha" public_packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_domain", "radroots_event", "radroots_event_codec", "radroots_execution", "radroots_geonames", "radroots_identity", "radroots_nostr", "radroots_nostr_connect", "radroots_protocol", "radroots_sdk", "radroots_secrets", "radroots_signing", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_trade", "radroots_transport", "radroots_transport_nostr"] diff --git a/contracts/execution/workspace.v1.json b/contracts/execution/workspace.v1.json @@ -1,12 +1,13 @@ { "schema_version": 1, "contract_id": "radroots.execution.workspace.v1", - "state": "native_buyer_attachment_component_implemented", + "state": "native_buyer_chat_preparation_component_implemented", "ownership": { "domain": "Validated actor, authority, checkpoint and captured-context descriptors; descriptors grant no rights", "execution": "Owned authenticated workspace session and opaque captured command context", "storage_sqlite": "Concrete protected native namespace and current grant/authority verification", - "facade": "Explicit local attachment and shared execution entry points" + "facade": "Explicit local attachment and shared execution entry points", + "protocol": "Closed v1 inquiry/reply command data codec, canonical command/approval-intent hashes; parsing grants no authority" }, "identity": { "workspace_executor_operation_grant_bytes": 32, @@ -21,10 +22,11 @@ "credential_persistence": "verifier only, under protected handling; no plaintext credential in SQL, diagnostics or arguments", "private_payload_max_bytes": 16384, "private_codec": "existing context-bound authenticated envelope v2 with explicit qualified provider, key material and unique nonce", - "transactions": "Grant creation and revocation observe actual SQLite commit completion. Transaction-time business admission/revalidation remains unimplemented.", + "transactions": "Grant creation/revocation and buyer inquiry preparation observe actual SQLite completion. T0 uses BEGIN IMMEDIATE and exact protected grant-row comparison before current proof/generation/route/deadline checks. Provider work finishes before the transaction. Prepared state does not install a message or invoke signing/delivery.", "initialization": "explicit fresh local outbox enrollment; no automatic stock ledger or restore from a key/public cache", "remote_attachment_qualified": false, - "firm_stock_qualified": false + "firm_stock_qualified": false, + "private_payload_scope": "Protected grant plaintext and protocol private-record limits remain distinct from the internal retained command journal." }, "context": { "constructor": "pure synchronous authenticated workspace-session method; no clock, storage, signer or network effects; arbitrary JSON yields descriptors, never a trusted context", @@ -57,15 +59,52 @@ "Revoked/expired grant refusal and persisted reopen behavior", "No context authority from signer observation, public cache or caller-provided descriptors", "Full captured context fields, exact strings, explicit null, bounded redacted diagnostics and local/native lifetime checks", - "Owning native/portable/API/contract checks and unchanged coverage policy" + "Owning native/portable/API/contract checks and unchanged coverage policy", + "Independent canonical command and approval-intent vectors and closed shape/byte/depth refusals", + "Actual inquiry commit/reopen/replay, original correlation, digest conflict, proof/revocation/deadline and transaction-time grant checks", + "Actual SQLite statement failure/confirmed rollback, deferred-constraint commit failure/unknown latch, lost observer and bounded queue/drain", + "Protected operation-context substitution refusal and predecessor-schema byte preservation" ], "remaining": [ - "Complete operation receipts and actual known-kind T0/T1/S/T2/D execution", + "Complete operation receipts, authenticated reply/history and actual known-kind listing/chat T1/S/T2/D execution", "Owned durable workers, per-target delivery and process-fault recovery", "Full stock executor, remote pairing/transfer and restore/fencing", "Actual browser/platform providers, generated bindings, coherent consumers and final acceptance" ], "implementation_claimed": true, - "implementation_scope": "Fresh unrelated protected local buyer attachment and pure captured context only; no durable business command, selected seller stock, remote pairing or recovery qualification.", - "package_publication_authorized": false + "implementation_scope": "Fresh protected local buyer attachment/context and actual inquiry Prepared admission/query only; no installed message, issuance/delivery, complete receipt, seller stock, remote pairing or general recovery qualification.", + "package_publication_authorized": false, + "command_data": { + "types": [ + "inbox.inquire", + "inbox.reply" + ], + "raw_and_canonical_max_bytes": 65536, + "chat_utf8_max_bytes": 4096, + "maximum_json_depth": 16, + "canonicalization": "Closed ASCII-key RFC 8785 subset with preserved Unicode, fixed numeric kind 30402, canonical decimal-string exact values and explicit required nulls; not a general-purpose JCS implementation", + "command_digest": "SHA-256(radroots.command.v1 NUL || canonical command excluding context.correlation_id)", + "approval_intent_digest": "SHA-256(radroots.approval.v1 NUL || canonical command excluding context.approval and context.correlation_id)", + "private_buffers": "Zeroizing retained canonical command and decoded private text; borrowed raw private JSON during parsing" + }, + "prepared_journal": { + "schema_user_version": 2, + "catalog": [ + "workspace_grant", + "operations", + "operation_transaction_identity" + ], + "single_participant_scope": "One protected fresh local buyer grant per namespace; operations unique by complete workspace and operation ID", + "admitted_effect": "Protected authorized inquiry preparation only; no stock effect, installed chat, signature or publication", + "retained_identity": "Full operation and command digest plus original 32-byte transaction ID and positive revision", + "internal_plaintext_max_bytes": 65536, + "protected_envelope_max_bytes": 262144, + "replay": "Current access and the original digest are verified before fresh planning, deadline or entropy; original correlation is retained", + "unknown": "Original operation/digest and observed nullable transaction identity are retained; uncertain owner blocks business admission/query until safe close/reopen and exact original-row reconciliation", + "known_failure": "No write was attempted, or actual rollback completed; commit/rollback uncertainty never becomes a known failure", + "unavailable_history": "Reply parents and order expectations are refused until authenticated history is implemented", + "approval": "Caller-provided approval descriptors are refused without a qualified protected consent origin", + "predecessor_schema": "Preserve and refuse the prior grant-only namespace; no implicit rewrite, deletion, re-enrollment or import", + "transaction_recheck": "The short transaction matches complete workspace/operation, participant/grant, command type/digest, original transaction, prepared phase/revision and exact retained protected bytes; matching ciphertext alone cannot hide changed indexed facts." + } } diff --git a/contracts/releases/package_tiers.toml b/contracts/releases/package_tiers.toml @@ -10,13 +10,12 @@ packages = [ "radroots_core", "radroots_identity", "radroots_blossom", - "radroots_protocol", ] [[tier]] id = "domain" rank = 1 -packages = ["radroots_domain", "radroots_event", "radroots_event_codec", "radroots_trade"] +packages = ["radroots_domain", "radroots_protocol", "radroots_event", "radroots_event_codec", "radroots_trade"] [[tier]] id = "spi" diff --git a/crates/domain/src/context.rs b/crates/domain/src/context.rs @@ -268,7 +268,7 @@ impl CheckpointRef { } /// A bounded diagnostic reference excluded from semantic idempotency. #[derive(Clone, Eq, PartialEq)] -pub struct CorrelationId(String); +pub struct CorrelationId(Box<str>); impl CorrelationId { /// Retains at most 128 UTF-8 bytes, with no terminal/control characters. pub fn new(value: impl Into<String>) -> Result<Self, ContextError> { @@ -276,7 +276,7 @@ impl CorrelationId { if value.len() > 128 || value.chars().any(char::is_control) { return Err(ContextError::InvalidText); } - Ok(Self(value)) + Ok(Self(value.into_boxed_str())) } /// Borrows the explicit diagnostic value for an authorized presentation. pub fn as_str(&self) -> &str { @@ -293,7 +293,7 @@ impl fmt::Debug for CorrelationId { #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub struct Approval { intent_digest: ApprovalIntentDigest, - scope: String, + scope: Box<str>, expires_at: UnixSeconds, } impl Approval { @@ -312,7 +312,7 @@ impl Approval { } Ok(Self { intent_digest, - scope, + scope: scope.into_boxed_str(), expires_at, }) } diff --git a/crates/domain/src/identifier.rs b/crates/domain/src/identifier.rs @@ -123,6 +123,18 @@ identifier!( "An exact 256-bit retained operation identifier." ); identifier!( + TransactionId, + "An exact 256-bit retained transaction identity." +); +identifier!( + MessageId, + "An unsigned NIP-17 rumor identity, distinct from its signed carriers." +); +identifier!( + EnvelopeEventId, + "A signed NIP-01 artifact identity, distinct from a logical record or rumor." +); +identifier!( GrantId, "An exact 256-bit scoped grant identifier; not a credential." ); diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs @@ -18,6 +18,7 @@ pub use context::{ CorrelationId, Coverage, ExpectedOrder, Generation, Sequence, UnixSeconds, }; pub use identifier::{ - ApprovalIntentDigest, CheckpointDigest, CommandDigest, ExecutorId, GrantId, IdentifierError, - OperationId, OrderId, RecordId, RouteDigest, SourceId, ThreadId, WorkspaceId, + ApprovalIntentDigest, CheckpointDigest, CommandDigest, EnvelopeEventId, ExecutorId, GrantId, + IdentifierError, MessageId, OperationId, OrderId, RecordId, RouteDigest, SourceId, ThreadId, + TransactionId, WorkspaceId, }; diff --git a/crates/domain/tests/identifier.rs b/crates/domain/tests/identifier.rs @@ -35,6 +35,9 @@ fn captured_context_identities_preserve_full_width_and_canonical_encoding() { check!(radroots_domain::RouteDigest); check!(radroots_domain::CheckpointDigest); check!(radroots_domain::ApprovalIntentDigest); + check!(radroots_domain::TransactionId); + check!(radroots_domain::MessageId); + check!(radroots_domain::EnvelopeEventId); } #[test] diff --git a/crates/protocol/Cargo.toml b/crates/protocol/Cargo.toml @@ -25,7 +25,7 @@ include = [ ] [package.metadata.docs.rs] -features = ["std", "serde"] +features = ["std", "serde", "commands"] [lib] name = "radroots_protocol" @@ -34,8 +34,13 @@ name = "radroots_protocol" default = ["std", "serde"] serde = ["dep:serde"] std = ["serde?/std"] +commands = ["serde", "dep:radroots_domain", "dep:serde_json", "dep:sha2", "dep:zeroize"] [dependencies] +radroots_domain = { workspace = true, default-features = false, features = ["serde"], optional = true } +serde_json = { workspace = true, default-features = false, features = ["alloc", "raw_value"], optional = true } +sha2 = { workspace = true, default-features = false, optional = true } +zeroize = { workspace = true, default-features = false, features = ["alloc"], optional = true } serde = { workspace = true, default-features = false, features = [ "alloc", "derive", diff --git a/crates/protocol/README.md b/crates/protocol/README.md @@ -19,8 +19,12 @@ numbers embedded in wire and schema contracts. | `runtime::v1` | operation descriptors, risk, approval, idempotency, and effects | | `radrootsd::transport_publish::v5` | daemon transport-publish request, job, outcome, and capability DTOs | | `schema` | schema IDs, module generations, descriptors, and aggregate registries | +| `command` (`commands` feature) | bounded closed v1 inquiry/reply data codec and exact command/approval-intent hashes | -All serialized DTOs live below an explicit generation module. The crate root +Versioned DTOs live below an explicit generation module. The command codec +implements its fixed v1 profile without exposing automatic serialization of +captured private commands. Parsed command data supplies no authority or consent. +The crate root does not reexport individual DTOs, so consumers must name the contract version they use. @@ -30,6 +34,7 @@ they use. | --- | --- | --- | | `std` | yes | implements standard-library error integration and enables `serde?/std` | | `serde` | yes | derives serialization and deserialization for wire-contract types | +| `commands` | no | enables the portable closed chat codec, domain values, SHA-256 and zeroizing private command buffers | Disabling default features leaves the catalog and structural validation APIs available with `alloc` only. Enable `serde` without `std` for portable encoded diff --git a/crates/protocol/src/command.rs b/crates/protocol/src/command.rs @@ -0,0 +1,609 @@ +//! 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: +//! every schema key is ASCII, the only JSON number is fixed kind 30402, and +//! exact integers are strings. Field order is explicit and independent of map +//! features. Strings preserve their Unicode contents without normalization. + +use alloc::{boxed::Box, string::String, vec::Vec}; +use core::fmt; +use radroots_domain::{ + ActorRef, ActorRole, Approval, ApprovalIntentDigest, AuthorityRef, CheckpointRef, + CommandContextData, CommandDigest, ExpectedOrder, MessageId, PublicKey, SourceId, ThreadId, +}; +use serde::{Deserialize, Serialize, ser::SerializeStruct}; +use sha2::{Digest, Sha256}; +use zeroize::Zeroizing; + +/// Maximum raw or canonical command bytes accepted by this closed boundary. +pub const COMMAND_MAX_BYTES: usize = 65_536; +/// Maximum plain chat text in UTF-8 bytes, before JSON/encryption expansion. +pub const CHAT_MAX_BYTES: usize = 4096; +const JSON_MAX_DEPTH: usize = 16; + +/// Fixed input-free command data failures. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum CommandError { + /// The closed input shape or a value is invalid. + InvalidInput, + /// This command type is not implemented by the chat profile. + UnsupportedCommand, + /// A byte/depth bound was exceeded. + LimitExceeded, +} +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::LimitExceeded => "command limit exceeded", + }) + } +} +impl core::error::Error for CommandError {} + +/// A captured public listing reference. This descriptor verifies neither its +/// source event nor its availability, terms or stock backing. +#[derive(Clone, Eq, PartialEq)] +pub struct ListingRevisionRef { + author: PublicKey, + d: Box<str>, + event_id: SourceId, +} +impl ListingRevisionRef { + /// Validates the fixed 16-byte lowercase-hex listing coordinate component. + pub fn new(author: PublicKey, d: &str, event_id: SourceId) -> Result<Self, CommandError> { + if d.len() != 32 + || !d + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return Err(CommandError::InvalidInput); + } + Ok(Self { + author, + d: Box::from(d), + event_id, + }) + } + /// Returns the referenced listing author. + pub const fn author(&self) -> PublicKey { + self.author + } + /// Borrows the canonical listing discriminator. + pub fn d(&self) -> &str { + &self.d + } + /// Returns the referenced public event digest. + pub const fn event_id(&self) -> SourceId { + self.event_id + } +} +impl fmt::Debug for ListingRevisionRef { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ListingRevisionRef(<descriptor>)") + } +} + +/// Validated inquiry data, without command or participant authority. +pub struct InquireInput { + thread_id: ThreadId, + peer: PublicKey, + source: Option<ListingRevisionRef>, + text: Zeroizing<String>, +} +impl InquireInput { + /// Checks the plain UTF-8 budget before copying private text. Empty text is + /// representable; nested rumor/encryption budgets remain separately checked. + pub fn new( + thread_id: ThreadId, + peer: PublicKey, + source: Option<ListingRevisionRef>, + text: &str, + ) -> Result<Self, CommandError> { + if text.len() > CHAT_MAX_BYTES { + return Err(CommandError::LimitExceeded); + } + Ok(Self { + thread_id, + peer, + source, + text: Zeroizing::new(String::from(text)), + }) + } + /// Returns the exact application thread. + pub const fn thread_id(&self) -> ThreadId { + self.thread_id + } + /// Returns the intended peer. + pub const fn peer(&self) -> PublicKey { + self.peer + } + /// Borrows the optional untrusted public-source descriptor. + pub fn source(&self) -> Option<&ListingRevisionRef> { + self.source.as_ref() + } + /// Exposes private text for its authorized encoder or participant view. + pub fn text(&self) -> &str { + &self.text + } +} +impl fmt::Debug for InquireInput { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("InquireInput(<redacted>)") + } +} + +/// Validated reply data. A parent selector alone does not authenticate history. +pub struct ReplyInput { + thread_id: ThreadId, + peer: PublicKey, + parent: MessageId, + text: Zeroizing<String>, +} +impl ReplyInput { + /// Captures an exact logical parent and checks private text before copying. + pub fn new( + thread_id: ThreadId, + peer: PublicKey, + parent: MessageId, + text: &str, + ) -> Result<Self, CommandError> { + if text.len() > CHAT_MAX_BYTES { + return Err(CommandError::LimitExceeded); + } + Ok(Self { + thread_id, + peer, + parent, + text: Zeroizing::new(String::from(text)), + }) + } + /// Returns the captured thread. + pub const fn thread_id(&self) -> ThreadId { + self.thread_id + } + /// Returns the intended peer. + pub const fn peer(&self) -> PublicKey { + self.peer + } + /// Returns the logical rumor parent, independently of any outer envelope. + pub const fn parent(&self) -> MessageId { + self.parent + } + /// Exposes private text to an authorized consumer. + pub fn text(&self) -> &str { + &self.text + } +} +impl fmt::Debug for ReplyInput { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ReplyInput(<redacted>)") + } +} + +/// The two assigned known-kind private-chat jobs; no commerce kind is inferred. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ChatKind { + /// A private question, independent of an order. + Inquire, + /// A reply to authenticated thread history. + Reply, +} +impl ChatKind { + /// Returns the exact command-schema discriminator. + pub const fn as_str(self) -> &'static str { + match self { + Self::Inquire => "inbox.inquire", + Self::Reply => "inbox.reply", + } + } +} +enum Input { + Inquire(InquireInput), + Reply(ReplyInput), +} + +/// Immutable, bounded command *data*, not an authenticated command context. +/// The store must authenticate its separate protected proof and enforce every +/// current precondition in the actual admission transaction. This type has no +/// automatic private diagnostics, cloning or serialization. +pub struct CapturedChatCommand { + context: CommandContextData, + input: Input, + wire: Zeroizing<Box<[u8]>>, + digest: CommandDigest, + approval_intent: ApprovalIntentDigest, +} +impl CapturedChatCommand { + /// Captures an inquiry and computes exact profile digests without effects. + pub fn inquire(context: CommandContextData, input: InquireInput) -> Result<Self, CommandError> { + Self::new(context, Input::Inquire(input)) + } + /// Captures a reply without trusting its parent selector as evidence. + pub fn reply(context: CommandContextData, input: ReplyInput) -> Result<Self, CommandError> { + Self::new(context, Input::Reply(input)) + } + fn new(context: CommandContextData, input: Input) -> Result<Self, CommandError> { + let encode = |approval, correlation| -> Result<Zeroizing<Vec<u8>>, CommandError> { + let bytes = Zeroizing::new( + serde_json::to_vec(&CanonicalCommand { + context: &context, + input: &input, + approval, + correlation, + }) + .map_err(|_| CommandError::InvalidInput)?, + ); + if bytes.len() > COMMAND_MAX_BYTES { + return Err(CommandError::LimitExceeded); + } + Ok(bytes) + }; + let wire = Zeroizing::new(Box::from(encode(true, true)?.as_slice())); + let digest = hash(b"radroots.command.v1\0", &encode(true, false)?); + let approval_intent = hash(b"radroots.approval.v1\0", &encode(false, false)?); + Ok(Self { + context, + input, + wire, + digest: CommandDigest::from_bytes(digest), + approval_intent: ApprovalIntentDigest::from_bytes(approval_intent), + }) + } + /// Parses a bounded closed profile. JSON syntax supplies no grant or consent. + pub fn parse(raw: &[u8]) -> Result<Self, CommandError> { + check_frame(raw)?; + let root: RawRoot<'_> = + serde_json::from_slice(raw).map_err(|_| CommandError::InvalidInput)?; + if root.kind.len() > 80 { + return Err(CommandError::LimitExceeded); + } + match root.kind.as_str() { + "inbox.inquire" => { + let raw: RawInquiry = serde_json::from_str(root.input.get()) + .map_err(|_| CommandError::InvalidInput)?; + if raw.text.len() > CHAT_MAX_BYTES { + return Err(CommandError::LimitExceeded); + } + let source = raw.source.map(RawSource::validate).transpose()?; + Self::new( + root.context, + Input::Inquire(InquireInput { + thread_id: raw.thread_id, + peer: raw.peer, + source, + text: raw.text, + }), + ) + } + "inbox.reply" => { + let raw: RawReply = serde_json::from_str(root.input.get()) + .map_err(|_| CommandError::InvalidInput)?; + if raw.text.len() > CHAT_MAX_BYTES { + return Err(CommandError::LimitExceeded); + } + Self::new( + root.context, + Input::Reply(ReplyInput { + thread_id: raw.thread_id, + peer: raw.peer, + parent: raw.parent, + text: raw.text, + }), + ) + } + _ => Err(CommandError::UnsupportedCommand), + } + } + /// Borrows untrusted captured context data for authoritative comparison. + pub const fn context(&self) -> &CommandContextData { + &self.context + } + /// Returns the command digest, with correlation removed entirely. + pub const fn digest(&self) -> CommandDigest { + self.digest + } + /// Returns the approval-intent digest with approval and correlation removed. + /// The digest alone authenticates no consent origin. + pub const fn approval_intent_digest(&self) -> ApprovalIntentDigest { + self.approval_intent + } + /// Returns the known command discriminator. + pub const fn kind(&self) -> ChatKind { + match self.input { + Input::Inquire(_) => ChatKind::Inquire, + Input::Reply(_) => ChatKind::Reply, + } + } + /// Returns the thread selected by this immutable command. + pub const fn thread_id(&self) -> ThreadId { + match &self.input { + Input::Inquire(v) => v.thread_id, + Input::Reply(v) => v.thread_id, + } + } + /// Returns its intended peer. + pub const fn peer(&self) -> PublicKey { + match &self.input { + Input::Inquire(v) => v.peer, + Input::Reply(v) => v.peer, + } + } + /// Borrows its exact logical parent where applicable. + pub const fn parent(&self) -> Option<MessageId> { + match &self.input { + Input::Inquire(_) => None, + Input::Reply(v) => Some(v.parent), + } + } + /// Borrows an optional inquiry source descriptor. + pub fn source(&self) -> Option<&ListingRevisionRef> { + match &self.input { + Input::Inquire(v) => v.source(), + Input::Reply(_) => None, + } + } + /// Exposes private text to its authorized store or wire encoder. + pub fn text(&self) -> &str { + match &self.input { + Input::Inquire(v) => v.text(), + Input::Reply(v) => v.text(), + } + } + /// Exposes complete canonical private command bytes for protected handling. + /// These include the original diagnostic correlation and are not the hash input. + pub fn protected_wire(&self) -> &[u8] { + &self.wire + } +} +impl fmt::Debug for CapturedChatCommand { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CapturedChatCommand(<redacted>)") + } +} + +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> { + if raw.len() > COMMAND_MAX_BYTES { + return Err(CommandError::LimitExceeded); + } + let (mut depth, mut quoted, mut escaped) = (0usize, false, false); + for byte in raw { + if quoted { + if escaped { + escaped = false; + } else if *byte == b'\\' { + escaped = true; + } else if *byte == b'"' { + quoted = false; + } + } else { + match byte { + b'"' => quoted = true, + b'{' | b'[' => { + depth += 1; + if depth > JSON_MAX_DEPTH { + return Err(CommandError::LimitExceeded); + } + } + b'}' | b']' => depth = depth.checked_sub(1).ok_or(CommandError::InvalidInput)?, + _ => {} + } + } + } + if quoted || depth != 0 { + return Err(CommandError::InvalidInput); + } + Ok(()) +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawRoot<'a> { + #[serde(rename = "type")] + kind: String, + context: CommandContextData, + #[serde(borrow)] + input: &'a serde_json::value::RawValue, +} +fn required_nullable<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>( + d: D, +) -> Result<Option<T>, D::Error> { + Option::deserialize(d) +} +fn private_text<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Zeroizing<String>, D::Error> { + String::deserialize(d).map(Zeroizing::new) +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawInquiry { + thread_id: ThreadId, + peer: PublicKey, + #[serde(deserialize_with = "required_nullable")] + source: Option<RawSource>, + #[serde(deserialize_with = "private_text")] + text: Zeroizing<String>, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawReply { + thread_id: ThreadId, + peer: PublicKey, + parent: MessageId, + #[serde(deserialize_with = "private_text")] + text: Zeroizing<String>, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawSource { + coordinate: RawCoordinate, + event_id: SourceId, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawCoordinate { + kind: u32, + author: PublicKey, + d: String, +} +impl RawSource { + fn validate(self) -> Result<ListingRevisionRef, CommandError> { + if self.coordinate.kind != 30402 { + return Err(CommandError::InvalidInput); + } + ListingRevisionRef::new(self.coordinate.author, &self.coordinate.d, self.event_id) + } +} + +struct CanonicalCommand<'a> { + context: &'a CommandContextData, + input: &'a Input, + approval: bool, + correlation: bool, +} +impl Serialize for CanonicalCommand<'_> { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + let mut o = s.serialize_struct("ChatCommand", 3)?; + o.serialize_field( + "context", + &Context(self.context, self.approval, self.correlation), + )?; + o.serialize_field("input", &CanonicalInput(self.input))?; + o.serialize_field( + "type", + match self.input { + Input::Inquire(_) => "inbox.inquire", + Input::Reply(_) => "inbox.reply", + }, + )?; + o.end() + } +} +struct Context<'a>(&'a CommandContextData, bool, bool); +impl Serialize for Context<'_> { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + let v = self.0; + let mut o = s.serialize_struct("Context", 7 + usize::from(self.1) + usize::from(self.2))?; + o.serialize_field("actor", &Actor(v.actor()))?; + if self.1 { + o.serialize_field("approval", &v.approval().map(CanonicalApproval))?; + } + o.serialize_field("authority", &Authority(v.authority()))?; + if self.2 { + o.serialize_field("correlation_id", &v.correlation_id().map(|c| c.as_str()))?; + } + o.serialize_field("expected", &v.expected().map(Expected))?; + o.serialize_field("not_after", &v.not_after())?; + o.serialize_field("operation_id", &v.operation_id())?; + o.serialize_field("route_digest", &v.route_digest())?; + o.serialize_field("workspace_id", &v.workspace_id())?; + o.end() + } +} +struct Actor(ActorRef); +impl Serialize for Actor { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + let role = match self.0.role() { + ActorRole::Buyer => "buyer", + ActorRole::Seller => "seller", + ActorRole::Coordinator => "coordinator", + _ => return Err(serde::ser::Error::custom("unsupported actor role")), + }; + let mut o = s.serialize_struct("Actor", 4)?; + o.serialize_field("grant_id", &self.0.grant_id())?; + o.serialize_field("organization", &self.0.organization())?; + o.serialize_field("participant", &self.0.participant())?; + o.serialize_field("role", role)?; + o.end() + } +} +struct Authority(AuthorityRef); +impl Serialize for Authority { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + let mut o = s.serialize_struct("Authority", 2)?; + o.serialize_field("executor_id", &self.0.executor_id())?; + o.serialize_field("generation", &self.0.generation())?; + o.end() + } +} +struct CanonicalApproval<'a>(&'a Approval); +impl Serialize for CanonicalApproval<'_> { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + let mut o = s.serialize_struct("Approval", 3)?; + o.serialize_field("expires_at", &self.0.expires_at())?; + o.serialize_field("intent_digest", &self.0.intent_digest())?; + o.serialize_field("scope", self.0.scope())?; + o.end() + } +} +struct Expected<'a>(&'a ExpectedOrder); +impl Serialize for Expected<'_> { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + let v = self.0; + let mut o = s.serialize_struct("Expected", 5)?; + o.serialize_field("agreement", &v.agreement())?; + o.serialize_field("buyer_head", &v.buyer_head())?; + o.serialize_field("checkpoint", &Checkpoint(v.checkpoint()))?; + o.serialize_field("order_id", &v.order_id())?; + o.serialize_field("seller_sequence", &v.seller_sequence())?; + o.end() + } +} +struct Checkpoint<'a>(&'a CheckpointRef); +impl Serialize for Checkpoint<'_> { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + let v = self.0; + let mut o = s.serialize_struct("Checkpoint", 4)?; + o.serialize_field("coverage", &v.coverage())?; + o.serialize_field("digest", &v.digest())?; + o.serialize_field("missing", v.missing())?; + o.serialize_field("sequence", &v.sequence())?; + o.end() + } +} +struct CanonicalInput<'a>(&'a Input); +impl Serialize for CanonicalInput<'_> { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + let mut o = s.serialize_struct("ChatInput", 4)?; + match self.0 { + Input::Inquire(v) => { + o.serialize_field("peer", &v.peer)?; + o.serialize_field("source", &v.source)?; + o.serialize_field("text", v.text())?; + o.serialize_field("thread_id", &v.thread_id)?; + } + Input::Reply(v) => { + o.serialize_field("parent", &v.parent)?; + o.serialize_field("peer", &v.peer)?; + o.serialize_field("text", v.text())?; + o.serialize_field("thread_id", &v.thread_id)?; + } + } + o.end() + } +} +impl Serialize for ListingRevisionRef { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + let mut o = s.serialize_struct("ListingRevision", 2)?; + o.serialize_field("coordinate", &Coordinate(self))?; + o.serialize_field("event_id", &self.event_id)?; + o.end() + } +} +struct Coordinate<'a>(&'a ListingRevisionRef); +impl Serialize for Coordinate<'_> { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + let mut o = s.serialize_struct("ListingCoordinate", 3)?; + o.serialize_field("author", &self.0.author)?; + o.serialize_field("d", &self.0.d)?; + o.serialize_field("kind", &30402u32)?; + o.end() + } +} diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs @@ -4,6 +4,11 @@ extern crate alloc; +/// Closed known-kind chat command data and canonical digest input. These +/// values authenticate no principal and perform no command admission. +#[cfg(feature = "commands")] +pub mod command; + #[cfg(all(test, not(feature = "std")))] extern crate std; diff --git a/crates/protocol/tests/command.rs b/crates/protocol/tests/command.rs @@ -0,0 +1,346 @@ +#![cfg(feature = "commands")] + +use radroots_domain::{ + ActorRef, ActorRole, Approval, AuthorityRef, CommandContextData, CorrelationId, ExecutorId, + Generation, GrantId, MessageId, OperationId, PublicKey, RouteDigest, SourceId, ThreadId, + UnixSeconds, WorkspaceId, +}; +use radroots_protocol::command::{ + CHAT_MAX_BYTES, COMMAND_MAX_BYTES, CapturedChatCommand, ChatKind, CommandError, InquireInput, + ListingRevisionRef, ReplyInput, +}; +use serde::Deserialize; +use serde_json::{Value, json}; + +fn alice() -> PublicKey { + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() +} +fn bob() -> PublicKey { + PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5").unwrap() +} +fn context(correlation: Option<&str>, approval: Option<Approval>) -> CommandContextData { + CommandContextData::new( + OperationId::from_bytes([1; 32]), + ActorRef::new( + alice(), + ActorRole::Buyer, + None, + Some(GrantId::from_bytes([2; 32])), + ), + WorkspaceId::from_bytes([3; 32]), + AuthorityRef::new( + ExecutorId::from_bytes([4; 32]), + Generation::new(9_007_199_254_740_993).unwrap(), + ), + RouteDigest::from_bytes([5; 32]), + approval, + None, + UnixSeconds::new(200).unwrap(), + correlation.map(|v| CorrelationId::new(v).unwrap()), + ) + .unwrap() +} +fn inquiry( + correlation: Option<&str>, + approval: Option<Approval>, + text: &str, +) -> CapturedChatCommand { + CapturedChatCommand::inquire( + context(correlation, approval), + InquireInput::new(ThreadId::from_bytes([6; 32]), bob(), None, text).unwrap(), + ) + .unwrap() +} +#[derive(Deserialize)] +struct Vectors { + vectors: Vec<Vector>, +} +#[derive(Deserialize)] +struct Vector { + name: String, + wire: String, + command_digest: String, + approval_intent_digest: String, +} + +#[test] +fn independent_ecmascript_vectors_match_exact_bytes_and_both_hash_domains() { + let vectors: Vectors = + serde_json::from_str(include_str!("fixtures/chat_commands.v1.json")).unwrap(); + assert_eq!(vectors.vectors.len(), 3); + for vector in vectors.vectors { + let command = CapturedChatCommand::parse(vector.wire.as_bytes()).unwrap(); + assert_eq!( + command.protected_wire(), + vector.wire.as_bytes(), + "{}", + vector.name + ); + assert_eq!( + command.digest().to_string(), + vector.command_digest, + "{}", + vector.name + ); + assert_eq!( + command.approval_intent_digest().to_string(), + vector.approval_intent_digest, + "{}", + vector.name + ); + assert_eq!( + command.context().authority().generation().get(), + 9_007_199_254_740_993 + ); + assert_eq!(command.peer(), bob()); + assert_eq!(command.thread_id(), ThreadId::from_bytes([6; 32])); + match command.kind() { + ChatKind::Inquire => assert_eq!(command.parent(), None), + ChatKind::Reply => assert_eq!(command.parent(), Some(MessageId::from_bytes([11; 32]))), + } + if let Some(source) = command.source() { + assert_eq!(source.author(), bob()); + assert_eq!(source.d(), "55".repeat(16)); + assert_eq!(source.event_id(), SourceId::from_bytes([10; 32])); + } + } +} + +#[test] +fn correlation_is_diagnostic_and_approval_is_bound_only_to_the_final_command() { + let original = inquiry(Some("original"), None, "private"); + let other = inquiry(Some("other"), None, "private"); + let absent = inquiry(None, None, "private"); + assert_ne!(original.protected_wire(), other.protected_wire()); + assert_eq!(original.digest(), other.digest()); + assert_eq!(original.digest(), absent.digest()); + let approval = Approval::new( + original.approval_intent_digest(), + "inbox.inquire", + UnixSeconds::new(190).unwrap(), + ) + .unwrap(); + let approved = inquiry(Some("other"), Some(approval), "private"); + assert_eq!( + original.approval_intent_digest(), + approved.approval_intent_digest() + ); + assert_ne!(original.digest(), approved.digest()); + assert_eq!( + CapturedChatCommand::parse(approved.protected_wire()) + .unwrap() + .digest(), + approved.digest() + ); + assert!(!format!("{approved:?}").contains("private")); + assert_eq!(format!("{approved:?}"), "CapturedChatCommand(<redacted>)"); +} + +#[test] +fn each_semantic_change_changes_the_command_commitment_without_unicode_normalization() { + let original = inquiry(None, None, "Ã…"); + let decomposed = inquiry(None, None, "A\u{030a}"); + assert_ne!(original.digest(), decomposed.digest()); + let base: Value = serde_json::from_slice(original.protected_wire()).unwrap(); + for (pointer, replacement) in [ + ("/context/operation_id", json!("10".repeat(32))), + ("/context/actor/role", json!("seller")), + ("/context/actor/participant", json!(bob().to_hex())), + ("/context/actor/organization", json!(bob().to_hex())), + ("/context/actor/grant_id", json!("11".repeat(32))), + ("/context/workspace_id", json!("12".repeat(32))), + ("/context/authority/executor_id", json!("13".repeat(32))), + ("/context/authority/generation", json!("2")), + ("/context/route_digest", json!("14".repeat(32))), + ("/context/not_after", json!("201")), + ("/input/thread_id", json!("15".repeat(32))), + ("/input/peer", json!(alice().to_hex())), + ("/input/text", json!("different")), + ] { + let mut changed = base.clone(); + *changed.pointer_mut(pointer).unwrap() = replacement; + let changed = CapturedChatCommand::parse(&serde_json::to_vec(&changed).unwrap()).unwrap(); + assert_ne!(changed.digest(), original.digest(), "{pointer}"); + } + let source = + ListingRevisionRef::new(bob(), &"55".repeat(16), SourceId::from_bytes([10; 32])).unwrap(); + let sourced = CapturedChatCommand::inquire( + context(None, None), + InquireInput::new(ThreadId::from_bytes([6; 32]), bob(), Some(source), "Ã…").unwrap(), + ) + .unwrap(); + assert_ne!(sourced.digest(), original.digest()); + let reply = CapturedChatCommand::reply( + context(None, None), + ReplyInput::new( + ThreadId::from_bytes([6; 32]), + bob(), + MessageId::from_bytes([11; 32]), + "reply", + ) + .unwrap(), + ) + .unwrap(); + assert_eq!( + CapturedChatCommand::parse(reply.protected_wire()) + .unwrap() + .digest(), + reply.digest() + ); +} + +#[test] +fn closed_json_requires_explicit_null_and_rejects_duplicates_aliases_unknowns_and_bad_sources() { + let command = inquiry(None, None, "private"); + let wire = std::str::from_utf8(command.protected_wire()).unwrap(); + let duplicate = wire.replacen( + "\"type\":\"inbox.inquire\"", + "\"type\":\"inbox.inquire\",\"t\\u0079pe\":\"inbox.inquire\"", + 1, + ); + assert!(matches!( + CapturedChatCommand::parse(duplicate.as_bytes()), + Err(CommandError::InvalidInput) + )); + let duplicate = wire.replacen( + "\"text\":\"private\"", + "\"text\":\"private\",\"te\\u0078t\":\"other\"", + 1, + ); + assert!(matches!( + CapturedChatCommand::parse(duplicate.as_bytes()), + Err(CommandError::InvalidInput) + )); + let base: Value = serde_json::from_slice(command.protected_wire()).unwrap(); + for pointer in [ + "/context/correlation_id", + "/context/approval", + "/context/expected", + "/input/source", + ] { + let mut value = base.clone(); + let (parent, key) = pointer.rsplit_once('/').unwrap(); + value + .pointer_mut(parent) + .unwrap() + .as_object_mut() + .unwrap() + .remove(key); + assert!( + matches!( + CapturedChatCommand::parse(&serde_json::to_vec(&value).unwrap()), + Err(CommandError::InvalidInput) + ), + "{pointer}" + ); + } + let mut extra = base.clone(); + extra["extra"] = json!(true); + assert!(matches!( + CapturedChatCommand::parse(&serde_json::to_vec(&extra).unwrap()), + Err(CommandError::InvalidInput) + )); + let mut extra = base.clone(); + extra["input"]["extra"] = json!(true); + assert!(matches!( + CapturedChatCommand::parse(&serde_json::to_vec(&extra).unwrap()), + Err(CommandError::InvalidInput) + )); + let mut unsupported = base.clone(); + unsupported["type"] = json!("orders.accept"); + assert!(matches!( + CapturedChatCommand::parse(&serde_json::to_vec(&unsupported).unwrap()), + Err(CommandError::UnsupportedCommand) + )); + unsupported["type"] = json!("x".repeat(81)); + assert!(matches!( + CapturedChatCommand::parse(&serde_json::to_vec(&unsupported).unwrap()), + Err(CommandError::LimitExceeded) + )); + for d in ["f".repeat(31), "F".repeat(32), "é".repeat(16)] { + assert!(matches!( + ListingRevisionRef::new(bob(), &d, SourceId::from_bytes([10; 32])), + Err(CommandError::InvalidInput) + )); + } + let mut source = base; + source["input"]["source"] = json!({"coordinate":{"kind":30403,"author":bob().to_hex(),"d":"55".repeat(16)},"event_id":"0a".repeat(32)}); + assert!(matches!( + CapturedChatCommand::parse(&serde_json::to_vec(&source).unwrap()), + Err(CommandError::InvalidInput) + )); + assert!( + !format!( + "{} {:?}", + CommandError::InvalidInput, + CommandError::LimitExceeded + ) + .contains("private") + ); +} + +#[test] +fn byte_and_depth_budgets_are_enforced_before_untrusted_json_materialization() { + let full = "é".repeat(CHAT_MAX_BYTES / 2); + let command = inquiry(None, None, &full); + assert_eq!( + CapturedChatCommand::parse(command.protected_wire()) + .unwrap() + .text(), + full + ); + assert!(matches!( + InquireInput::new( + ThreadId::from_bytes([6; 32]), + bob(), + None, + &(full.clone() + "é") + ), + Err(CommandError::LimitExceeded) + )); + assert!(matches!( + ReplyInput::new( + ThreadId::from_bytes([6; 32]), + bob(), + MessageId::from_bytes([11; 32]), + &"x".repeat(CHAT_MAX_BYTES + 1) + ), + Err(CommandError::LimitExceeded) + )); + assert_eq!(inquiry(None, None, "").text(), ""); + let mut raw = command.protected_wire().to_vec(); + raw.resize(COMMAND_MAX_BYTES + 1, b' '); + assert!(matches!( + CapturedChatCommand::parse(&raw), + Err(CommandError::LimitExceeded) + )); + for (depth, expected) in [ + (16, CommandError::InvalidInput), + (17, CommandError::LimitExceeded), + ] { + let nested = format!("{}0{}", "[".repeat(depth), "]".repeat(depth)); + assert!( + matches!(CapturedChatCommand::parse(nested.as_bytes()), Err(error) if error == expected) + ); + } + let bracket_text = "[ { \\\" ] }"; + let command = inquiry(None, None, bracket_text); + assert_eq!( + CapturedChatCommand::parse(command.protected_wire()) + .unwrap() + .text(), + bracket_text + ); + for raw in [b"}".as_slice(), b"{", b"\"unterminated", b"\xff"] { + assert!(matches!( + CapturedChatCommand::parse(raw), + Err(CommandError::InvalidInput) + )); + } + let mut too_long: Value = serde_json::from_slice(command.protected_wire()).unwrap(); + too_long["input"]["text"] = json!("x".repeat(CHAT_MAX_BYTES + 1)); + assert!(matches!( + CapturedChatCommand::parse(&serde_json::to_vec(&too_long).unwrap()), + Err(CommandError::LimitExceeded) + )); +} diff --git a/crates/protocol/tests/fixtures/chat_commands.v1.json b/crates/protocol/tests/fixtures/chat_commands.v1.json @@ -0,0 +1,26 @@ +{ + "schema": "radroots.chat_command_vectors.v1", + "producer": "Node.js 26.10.0; independent ECMAScript oracle", + "profile": "Closed ASCII schema keys, fixed safe integer kind, exact decimal strings; RFC 8785 string preservation", + "vectors": [ + { + "name": "inquiry_unicode", + "wire": "{\"context\":{\"actor\":{\"grant_id\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"organization\":null,\"participant\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"role\":\"buyer\"},\"approval\":null,\"authority\":{\"executor_id\":\"0404040404040404040404040404040404040404040404040404040404040404\",\"generation\":\"9007199254740993\"},\"correlation_id\":\"first-observer\",\"expected\":null,\"not_after\":\"200\",\"operation_id\":\"0101010101010101010101010101010101010101010101010101010101010101\",\"route_digest\":\"0505050505050505050505050505050505050505050505050505050505050505\",\"workspace_id\":\"0303030303030303030303030303030303030303030303030303030303030303\"},\"input\":{\"peer\":\"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5\",\"source\":null,\"text\":\"private 🥬 \\u000f \\n Ã… AÌŠ 
 🧺\",\"thread_id\":\"0606060606060606060606060606060606060606060606060606060606060606\"},\"type\":\"inbox.inquire\"}", + "command_digest": "1c23a2ebcc4dc4092202fe86d049f5dd241eea7c6883c06a9dc02d38a747bcb8", + "approval_intent_digest": "776c259738edb3629189272dc3b1c829ce40022f7bfdeecf663bcad6549303b6" + }, + { + "name": "inquiry_source_expected", + "wire": "{\"context\":{\"actor\":{\"grant_id\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"organization\":null,\"participant\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"role\":\"buyer\"},\"approval\":null,\"authority\":{\"executor_id\":\"0404040404040404040404040404040404040404040404040404040404040404\",\"generation\":\"9007199254740993\"},\"correlation_id\":\"first-observer\",\"expected\":{\"agreement\":null,\"buyer_head\":null,\"checkpoint\":{\"coverage\":\"partial\",\"digest\":\"0808080808080808080808080808080808080808080808080808080808080808\",\"missing\":[\"0909090909090909090909090909090909090909090909090909090909090909\"],\"sequence\":\"9007199254740993\"},\"order_id\":\"0707070707070707070707070707070707070707070707070707070707070707\",\"seller_sequence\":\"9007199254740993\"},\"not_after\":\"200\",\"operation_id\":\"0101010101010101010101010101010101010101010101010101010101010101\",\"route_digest\":\"0505050505050505050505050505050505050505050505050505050505050505\",\"workspace_id\":\"0303030303030303030303030303030303030303030303030303030303030303\"},\"input\":{\"peer\":\"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5\",\"source\":{\"coordinate\":{\"author\":\"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5\",\"d\":\"55555555555555555555555555555555\",\"kind\":30402},\"event_id\":\"0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a\"},\"text\":\"A public reference does not prove terms or stock.\",\"thread_id\":\"0606060606060606060606060606060606060606060606060606060606060606\"},\"type\":\"inbox.inquire\"}", + "command_digest": "7c66b9c276986cfc4eab5b898f78288bd7350eacbfab904cd1c603ccf632ec3b", + "approval_intent_digest": "9ebb8dd49603987cff8393fe2ac08f54ace8d0b7b3993a8223aabf6ebc9821b0" + }, + { + "name": "reply", + "wire": "{\"context\":{\"actor\":{\"grant_id\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"organization\":null,\"participant\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"role\":\"buyer\"},\"approval\":null,\"authority\":{\"executor_id\":\"0404040404040404040404040404040404040404040404040404040404040404\",\"generation\":\"9007199254740993\"},\"correlation_id\":null,\"expected\":null,\"not_after\":\"200\",\"operation_id\":\"0101010101010101010101010101010101010101010101010101010101010101\",\"route_digest\":\"0505050505050505050505050505050505050505050505050505050505050505\",\"workspace_id\":\"0303030303030303030303030303030303030303030303030303030303030303\"},\"input\":{\"parent\":\"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b\",\"peer\":\"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5\",\"text\":\"reply\",\"thread_id\":\"0606060606060606060606060606060606060606060606060606060606060606\"},\"type\":\"inbox.reply\"}", + "command_digest": "9276d1c7d590287f2d8ea19666cd93a3c0df52f4c1fd2dea75cb4355e454fe0c", + "approval_intent_digest": "1b249ea6f14aa201f0f8001bf1c8d37dd02ce6f8898e15fdc8d1f6ac1be20b2e" + } + ], + "producer_source_sha256": "aa526fd61f7c166b0d17ca60838e2b4104a495ac69e93956d6fa531bf11993d0" +} diff --git a/crates/protocol/tests/package_boundary.rs b/crates/protocol/tests/package_boundary.rs @@ -14,10 +14,11 @@ const VERSIONED_SOURCES: &[&str] = &[ include_str!("../src/radrootsd/transport_publish/v5.rs"), include_str!("../src/runtime/v1.rs"), include_str!("../src/schema.rs"), + include_str!("../src/command.rs"), ]; #[test] -fn manifest_has_final_identity_features_and_no_radroots_dependencies() { +fn manifest_has_approved_data_only_features_and_dependencies() { assert!(MANIFEST.contains("name = \"radroots_protocol\"")); assert!(MANIFEST.contains("version = \"0.1.0-alpha\"")); assert!(MANIFEST.contains("publish = [\"crates-io\"]")); @@ -25,11 +26,11 @@ fn manifest_has_final_identity_features_and_no_radroots_dependencies() { assert!(MANIFEST.contains("default = [\"std\", \"serde\"]")); assert_eq!( table_keys(MANIFEST, "[features]"), - BTreeSet::from(["default", "serde", "std"]) + BTreeSet::from(["commands", "default", "serde", "std"]) ); assert_eq!( table_keys(MANIFEST, "[dependencies]"), - BTreeSet::from(["serde"]) + BTreeSet::from(["radroots_domain", "serde", "serde_json", "sha2", "zeroize"]) ); assert_eq!( table_keys(MANIFEST, "[dev-dependencies]"), @@ -44,6 +45,7 @@ fn crate_root_exposes_only_the_approved_versioned_skeleton() { root_declarations("pub mod "), BTreeSet::from([ "capability", + "command", "error", "event", "radrootsd", diff --git a/crates/protocol/tests/support/chat_command_oracle.mjs b/crates/protocol/tests/support/chat_command_oracle.mjs @@ -0,0 +1,33 @@ +// Independently authored fixture oracle for the closed ASCII-key chat profile. +// It uses ECMAScript JSON serialization and Node's SHA-256, not the Rust codec. +import { createHash } from "node:crypto"; + +const id = (byte) => byte.repeat(32); +const alice = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; +const bob = "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"; +const canonical = (value) => { + if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`; + if (value !== null && typeof value === "object") { + return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`; + } + return JSON.stringify(value); +}; +const hash = (domain, value) => createHash("sha256").update(domain, "utf8").update(canonical(value), "utf8").digest("hex"); +const context = { + operation_id: id("01"), actor: { participant: alice, role: "buyer", organization: null, grant_id: id("02") }, + workspace_id: id("03"), authority: { executor_id: id("04"), generation: "9007199254740993" }, + route_digest: id("05"), approval: null, expected: null, not_after: "200", correlation_id: "first-observer", +}; +const cases = [ + { name: "inquiry_unicode", command: { type: "inbox.inquire", context, input: { thread_id: id("06"), peer: bob, source: null, text: "private 🥬 \u000f \n Ã… A\u030a \u2028 🧺" } } }, + { name: "inquiry_source_expected", command: { type: "inbox.inquire", context: { ...context, expected: { order_id: id("07"), agreement: null, seller_sequence: "9007199254740993", buyer_head: null, checkpoint: { digest: id("08"), sequence: "9007199254740993", coverage: "partial", missing: [id("09")] } } }, input: { thread_id: id("06"), peer: bob, source: { coordinate: { kind: 30402, author: bob, d: "55".repeat(16) }, event_id: id("0a") }, text: "A public reference does not prove terms or stock." } } }, + { name: "reply", command: { type: "inbox.reply", context: { ...context, correlation_id: null }, input: { thread_id: id("06"), peer: bob, parent: id("0b"), text: "reply" } } }, +]; +const records = cases.map(({ name, command }) => { + const semantic = structuredClone(command); + delete semantic.context.correlation_id; + const intent = structuredClone(semantic); + delete intent.context.approval; + return { name, wire: canonical(command), command_digest: hash("radroots.command.v1\0", semantic), approval_intent_digest: hash("radroots.approval.v1\0", intent) }; +}); +process.stdout.write(JSON.stringify({ schema: "radroots.chat_command_vectors.v1", producer: `Node.js ${process.versions.node}; independent ECMAScript oracle`, profile: "Closed ASCII schema keys, fixed safe integer kind, exact decimal strings; RFC 8785 string preservation", vectors: records }, null, 2) + "\n"); diff --git a/crates/storage/Cargo.toml b/crates/storage/Cargo.toml @@ -35,6 +35,7 @@ name = "radroots_storage" [features] default = ["memory", "serde"] memory = [] +command_journal = ["radroots_protocol/commands"] serde = [ "dep:serde", "radroots_domain/serde", diff --git a/crates/storage/src/command.rs b/crates/storage/src/command.rs @@ -0,0 +1,250 @@ +//! Typed authoritative admission/query transactions. The SPI is not a command +//! engine or a qualification claim. Concrete hosts must execute the specified +//! transactions and classify their actual completion; descriptors mint nothing. + +use crate::workspace::{AttachmentProof, WorkspaceBinding, WorkspaceError, WorkspaceStore}; +use core::fmt; +use radroots_domain::{CommandDigest, OperationId, Sequence, TransactionId, WorkspaceId}; +use radroots_protocol::command::CapturedChatCommand; +use radroots_transport::BoxFuture; + +/// Fixed operation-store failures known before a successful admission commit. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum OperationError { + /// Current workspace authentication or ownership failed. + Workspace(WorkspaceError), + /// Captured fields do not match the selected authenticated scope. + InvalidCommand, + /// This concrete authority cannot execute the requested action. + Unauthorized, + /// Required authenticated thread/order history is unavailable. + MissingHistory, + /// No qualified protected origin verifies the supplied approval descriptor. + UnverifiedApproval, + /// The first-admission deadline has passed; retained operations remain queryable. + DeadlineExceeded, + /// The retained operation identity binds a different command commitment. + IdempotencyConflict, + /// A known storage failure preceded writes or had confirmed rollback. + StorageFailure, + /// State, completion or decoding requires explicit reconciliation. + RecoveryRequired, +} +impl OperationError { + /// Returns an input-free diagnostic code. + pub const fn code(self) -> &'static str { + match self { + Self::Workspace(e) => e.code(), + Self::InvalidCommand => "invalid_command", + Self::Unauthorized => "unauthorized", + Self::MissingHistory => "missing_history", + Self::UnverifiedApproval => "unverified_approval", + Self::DeadlineExceeded => "deadline_exceeded", + Self::IdempotencyConflict => "idempotency_conflict", + Self::StorageFailure => "storage_failure", + Self::RecoveryRequired => "recovery_required", + } + } +} +impl fmt::Display for OperationError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.code()) + } +} +impl core::error::Error for OperationError {} +impl From<WorkspaceError> for OperationError { + fn from(value: WorkspaceError) -> Self { + Self::Workspace(value) + } +} + +/// Captured command and original authenticated binding. Construction compares +/// descriptors only. The separate protected proof must authenticate current +/// persisted state inside the actual admission transaction. +pub struct AdmissionRequest { + binding: WorkspaceBinding, + command: CapturedChatCommand, +} +impl AdmissionRequest { + /// Refuses substituted workspace, actor/grant, authority or route data. + /// Deadline and current grant checks belong to the concrete transaction; + /// an expired original command may still be queried/reconciled by identity. + pub fn new( + binding: WorkspaceBinding, + command: CapturedChatCommand, + ) -> Result<Self, OperationError> { + let context = command.context(); + let input = binding.input(); + if context.actor() != binding.actor() + || context.workspace_id() != input.workspace_id() + || context.authority() != input.authority() + || context.route_digest() != input.route_digest() + { + return Err(OperationError::InvalidCommand); + } + Ok(Self { binding, command }) + } + /// Decodes protected retained command data and compares its captured scope. + /// This remains structural; current access is independently authenticated. + pub fn from_protected_wire( + binding: WorkspaceBinding, + wire: &[u8], + ) -> Result<Self, OperationError> { + let command = + CapturedChatCommand::parse(wire).map_err(|_| OperationError::RecoveryRequired)?; + Self::new(binding, command) + } + /// Borrows the captured attachment observation, without claiming it is current. + pub const fn binding(&self) -> &WorkspaceBinding { + &self.binding + } + /// Borrows exact immutable command data. + pub const fn command(&self) -> &CapturedChatCommand { + &self.command + } + /// Transfers both owned descriptors to the concrete transaction owner. + pub fn into_parts(self) -> (WorkspaceBinding, CapturedChatCommand) { + (self.binding, self.command) + } +} +impl fmt::Debug for AdmissionRequest { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("AdmissionRequest(<redacted>)") + } +} + +/// Immutable anchor for one attempted admission. It is not proof of commit. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct CommitAttempt { + workspace_id: WorkspaceId, + operation_id: OperationId, + command_digest: CommandDigest, + transaction_id: Option<TransactionId>, +} +impl CommitAttempt { + /// Captures full original identities without creating an operation. + pub const fn new( + workspace_id: WorkspaceId, + operation_id: OperationId, + command_digest: CommandDigest, + transaction_id: Option<TransactionId>, + ) -> Self { + Self { + workspace_id, + operation_id, + command_digest, + transaction_id, + } + } + /// Returns the selected workspace. + pub const fn workspace_id(self) -> WorkspaceId { + self.workspace_id + } + /// Returns the original caller-provided operation identity. + pub const fn operation_id(self) -> OperationId { + self.operation_id + } + /// Returns its exact semantic command commitment. + pub const fn command_digest(self) -> CommandDigest { + self.command_digest + } + /// Returns the exact attempted transaction when observed. A lost owner + /// reply may leave only the original operation/digest anchor available. + pub const fn transaction_id(self) -> Option<TransactionId> { + self.transaction_id + } +} + +/// Owned observation of actual retained Prepared state. It is not an installed +/// business result, signature, delivery fact, stock hold or readiness flag. +/// A custom adapter's report does not qualify that adapter's persistence. +pub struct PreparedOperation { + request: Box<AdmissionRequest>, + transaction_id: TransactionId, + revision: Sequence, +} +impl PreparedOperation { + /// Validates a concrete store's structural report. The adapter must first + /// confirm its real commit or read the matching committed row after reopen. + pub fn from_committed_store( + request: AdmissionRequest, + transaction_id: TransactionId, + revision: Sequence, + ) -> Result<Self, OperationError> { + if revision.get() == 0 { + return Err(OperationError::RecoveryRequired); + } + Ok(Self { + request: Box::new(request), + transaction_id, + revision, + }) + } + /// Borrows the captured original request, including its diagnostic correlation. + pub const fn request(&self) -> &AdmissionRequest { + &self.request + } + /// Returns the original confirmed admission transaction identity. + pub const fn transaction_id(&self) -> TransactionId { + self.transaction_id + } + /// Returns the retained monotonic operation revision. + pub const fn revision(&self) -> Sequence { + self.revision + } + /// Returns the exact retained identity/commitment anchor. + pub fn identity(&self) -> CommitAttempt { + let context = self.request.command().context(); + CommitAttempt::new( + context.workspace_id(), + context.operation_id(), + self.request.command().digest(), + Some(self.transaction_id), + ) + } +} +impl fmt::Debug for PreparedOperation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("PreparedOperation(<redacted>)") + } +} + +/// Actual initial transaction completion, separate from signing/installation. +pub enum AdmissionOutcome { + /// The exact row commit or an existing committed row was confirmed. + Committed(PreparedOperation), + /// Completion is unknown. Reconcile this original anchor after safe reopen; + /// never infer rollback, discard the ID or issue from another preparation. + Unknown(CommitAttempt), +} +impl fmt::Debug for AdmissionOutcome { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Committed(_) => "AdmissionOutcome::Committed(<redacted>)", + Self::Unknown(_) => "AdmissionOutcome::Unknown(<retained>)", + }) + } +} + +/// Typed transaction port, implemented by actual shared storage adapters. +/// Applications do not implement a second orchestration or stock engine here. +pub trait OperationJournal: WorkspaceStore { + /// Authenticates current grant/fences, checks the original operation first, + /// and confirms atomic retained preparation before any signing. Chat has no + /// physical hold. Only confirmed rollback may return a known-failure error. + fn admit_command_and_hold( + &self, + request: AdmissionRequest, + proof: AttachmentProof, + ) -> BoxFuture<'_, Result<AdmissionOutcome, OperationError>>; + /// Queries original committed state under current access. Absence is not a + /// generic proof that an unknown external effect never happened. + fn operation( + &self, + binding: WorkspaceBinding, + operation_id: OperationId, + expected_digest: Option<CommandDigest>, + proof: AttachmentProof, + ) -> BoxFuture<'_, Result<Option<PreparedOperation>, OperationError>>; +} diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs @@ -10,6 +10,8 @@ pub mod authored_draft_pair; pub mod authored_draft_query; pub mod authored_draft_submission; pub mod backup; +#[cfg(feature = "command_journal")] +pub mod command; mod error; pub mod event; pub mod journal; diff --git a/crates/storage/src/workspace.rs b/crates/storage/src/workspace.rs @@ -208,7 +208,7 @@ impl<'de> serde::Deserialize<'de> for AttachmentInput { pub struct WorkspaceBinding { input: AttachmentInput, actor: ActorRef, - principal_id: String, + principal_id: Box<str>, grant_revision: Sequence, expires_at: UnixSeconds, observed_at: UnixSeconds, @@ -241,7 +241,7 @@ impl WorkspaceBinding { Ok(Self { input, actor, - principal_id, + principal_id: principal_id.into_boxed_str(), grant_revision, expires_at, observed_at, diff --git a/crates/storage/tests/command.rs b/crates/storage/tests/command.rs @@ -0,0 +1,169 @@ +#![cfg(feature = "command_journal")] + +use radroots_domain::{ + ActorRef, ActorRole, AuthorityRef, CheckpointDigest, CheckpointRef, CommandContextData, + Coverage, ExecutorId, Generation, GrantId, OperationId, PublicKey, RouteDigest, Sequence, + TransactionId, UnixSeconds, WorkspaceId, +}; +use radroots_storage::{ + command::{AdmissionRequest, CommitAttempt, OperationError, PreparedOperation}, + workspace::{AttachmentInput, WorkspaceBinding, WorkspaceError}, +}; + +fn binding() -> WorkspaceBinding { + let key = + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798") + .unwrap(); + let grant = GrantId::from_bytes([3; 32]); + let input = AttachmentInput::new( + WorkspaceId::from_bytes([1; 32]), + AuthorityRef::new(ExecutorId::from_bytes([2; 32]), Generation::new(1).unwrap()), + key, + "local://workspace/selector", + key, + grant, + CheckpointRef::new( + CheckpointDigest::from_bytes([4; 32]), + Sequence::new(0).unwrap(), + Coverage::Partial, + vec![], + ) + .unwrap(), + RouteDigest::from_bytes([5; 32]), + ) + .unwrap(); + WorkspaceBinding::from_authenticated_host( + input, + ActorRef::new(key, ActorRole::Buyer, None, Some(grant)), + "device", + Sequence::new(1).unwrap(), + UnixSeconds::new(200).unwrap(), + UnixSeconds::new(100).unwrap(), + ) + .unwrap() +} +fn request() -> AdmissionRequest { + let binding = binding(); + let input = binding.input(); + let context = CommandContextData::new( + OperationId::from_bytes([6; 32]), + binding.actor(), + input.workspace_id(), + input.authority(), + input.route_digest(), + None, + None, + UnixSeconds::new(150).unwrap(), + None, + ) + .unwrap(); + let command = radroots_protocol::command::CapturedChatCommand::inquire( + context, + radroots_protocol::command::InquireInput::new( + radroots_domain::ThreadId::from_bytes([7; 32]), + input.participant(), + None, + "private field", + ) + .unwrap(), + ) + .unwrap(); + AdmissionRequest::new(binding, command).unwrap() +} + +#[test] +fn structural_reports_preserve_full_original_anchor_without_minting_commit_proof() { + let captured = request(); + let digest = captured.command().digest(); + let wire = captured.command().protected_wire().to_vec(); + let (binding, command) = captured.into_parts(); + assert_eq!(command.protected_wire(), wire); + let parsed = AdmissionRequest::from_protected_wire(binding, &wire).unwrap(); + let transaction = TransactionId::from_bytes([8; 32]); + assert!(matches!( + PreparedOperation::from_committed_store(request(), transaction, Sequence::new(0).unwrap()), + Err(OperationError::RecoveryRequired) + )); + let reported = + PreparedOperation::from_committed_store(parsed, transaction, Sequence::new(1).unwrap()) + .unwrap(); + let anchor = reported.identity(); + assert_eq!(reported.transaction_id(), transaction); + assert_eq!(reported.revision().get(), 1); + assert_eq!( + anchor.workspace_id(), + reported.request().binding().input().workspace_id() + ); + assert_eq!(anchor.operation_id(), OperationId::from_bytes([6; 32])); + assert_eq!(anchor.command_digest(), digest); + assert_eq!(anchor.transaction_id(), Some(transaction)); + assert_eq!( + CommitAttempt::new(anchor.workspace_id(), anchor.operation_id(), digest, None) + .transaction_id(), + None + ); + assert!(!format!("{reported:?}").contains("private field")); +} + +#[test] +fn a_data_constructor_refuses_substituted_scope_but_never_authenticates_descriptors() { + let original = request(); + let wire: serde_json::Value = + serde_json::from_slice(original.command().protected_wire()).unwrap(); + for (pointer, value) in [ + ("/context/workspace_id", serde_json::json!("99".repeat(32))), + ("/context/authority/generation", serde_json::json!("2")), + ("/context/route_digest", serde_json::json!("99".repeat(32))), + ("/context/actor/role", serde_json::json!("seller")), + ] { + let mut changed = wire.clone(); + *changed.pointer_mut(pointer).unwrap() = value; + assert!(matches!( + AdmissionRequest::from_protected_wire( + binding(), + &serde_json::to_vec(&changed).unwrap() + ), + Err(OperationError::InvalidCommand) + )); + } + assert!(matches!( + AdmissionRequest::from_protected_wire(binding(), b"{bad}"), + Err(OperationError::RecoveryRequired) + )); + assert!(!format!("{original:?}").contains("private field")); +} + +#[test] +fn operation_failures_are_fixed_redacted_and_distinguish_uncertainty() { + let errors = [ + OperationError::from(WorkspaceError::Closed), + OperationError::InvalidCommand, + OperationError::Unauthorized, + OperationError::MissingHistory, + OperationError::UnverifiedApproval, + OperationError::DeadlineExceeded, + OperationError::IdempotencyConflict, + OperationError::StorageFailure, + OperationError::RecoveryRequired, + ]; + let mut codes = std::collections::BTreeSet::new(); + for error in errors { + assert!(codes.insert(error.code())); + assert!(error.to_string().len() < 64); + assert_eq!(error.to_string(), error.code()); + assert!(std::error::Error::source(&error).is_none()); + } + let attempt = CommitAttempt::new( + WorkspaceId::from_bytes([1; 32]), + OperationId::from_bytes([2; 32]), + radroots_domain::CommandDigest::from_bytes([3; 32]), + None, + ); + assert_eq!( + format!( + "{:?}", + radroots_storage::command::AdmissionOutcome::Unknown(attempt) + ), + "AdmissionOutcome::Unknown(<retained>)" + ); +} diff --git a/crates/storage_sqlite/Cargo.toml b/crates/storage_sqlite/Cargo.toml @@ -44,13 +44,14 @@ radroots_event_codec = { workspace = true, default-features = false, features = radroots_secrets = { workspace = true, default-features = false } radroots_storage = { workspace = true, default-features = false, features = [ "serde", + "command_journal", ] } radroots_transport = { workspace = true, default-features = false, features = [ "serde", "std", ] } serde = { workspace = true, features = ["derive", "std"] } -serde_json = { workspace = true, features = ["std"] } +serde_json = { workspace = true, features = ["std", "raw_value"] } sha2 = { workspace = true, features = ["std"] } rustix = { workspace = true } subtle = { workspace = true } diff --git a/crates/storage_sqlite/src/workspace/admission.rs b/crates/storage_sqlite/src/workspace/admission.rs @@ -0,0 +1,242 @@ +use super::{ + AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceCrypto, + fs::Namespace, operation, record::GrantRecord, worker, +}; +use radroots_domain::{CommandDigest, OperationId, TransactionId}; +use radroots_storage::command::{ + AdmissionOutcome, AdmissionRequest, CommitAttempt, OperationError, PreparedOperation, +}; +use sqlx::{Connection, Sqlite, SqliteConnection, Transaction}; + +/// One borrowed turn on the existing connection owner, never a second runtime. +pub(super) struct Journal<'a> { + pub connection: &'a mut SqliteConnection, + pub namespace: &'a Namespace, + pub selected: &'a AttachmentInput, + pub crypto: &'a WorkspaceCrypto, + pub clock: &'a dyn WorkspaceClock, + pub uncertain: &'a mut bool, +} +impl Journal<'_> { + async fn access( + &mut self, + binding: &WorkspaceBinding, + proof: &AttachmentProof, + ) -> Result<(GrantRecord, Vec<u8>), OperationError> { + if *self.uncertain { + return Err(OperationError::RecoveryRequired); + } + self.namespace.validate()?; + let protected = worker::read(self.connection, self.selected).await?; + let plaintext = self + .crypto + .open( + self.selected.workspace_id(), + self.selected.grant_id(), + &protected, + ) + .await?; + let record = plaintext.expose_secret(GrantRecord::decode)?; + let current = record.authenticate(binding.input(), proof, self.clock.now()?)?; + same_binding(binding, ¤t)?; + self.namespace.validate()?; + Ok((record, protected)) + } + + pub(super) async fn admit( + &mut self, + request: AdmissionRequest, + proof: AttachmentProof, + ) -> Result<AdmissionOutcome, OperationError> { + let (record, grant) = self.access(request.binding(), &proof).await?; + let context = request.command().context(); + let workspace = context.workspace_id(); + let operation_id = context.operation_id(); + let digest = request.command().digest(); + // Exact replay precedes fresh deadline, allocation, entropy and encoding. + let existing = + 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))?; + let anchor = snapshot.identity(); + let mut transaction = self + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let checked = async { + recheck( + &mut transaction, + self.namespace, + self.selected, + &grant, + &record, + request.binding(), + &proof, + self.clock, + ) + .await?; + operation::unchanged(&mut transaction, &snapshot, &protected).await + } + .await; + if transaction.rollback().await.is_err() { + *self.uncertain = true; + return Ok(AdmissionOutcome::Unknown(anchor)); + } + checked?; + return Ok(AdmissionOutcome::Committed(snapshot)); + } + + // This fresh local buyer namespace 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); + } + let transaction_id = TransactionId::from_bytes(super::random()?); + let anchor = CommitAttempt::new(workspace, operation_id, digest, Some(transaction_id)); + // Encryption/provider work finishes before opening the write transaction. + let protected = operation::protect(&request, transaction_id, self.crypto).await?; + let mut transaction = self + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let inserted = async { + let current = recheck( + &mut transaction, + self.namespace, + self.selected, + &grant, + &record, + request.binding(), + &proof, + self.clock, + ) + .await?; + if context.not_after() <= current.observed_at() + || context.not_after() > current.expires_at() + { + return Err(OperationError::DeadlineExceeded); + } + operation::insert(&mut transaction, &request, transaction_id, &protected).await + } + .await; + if let Err(error) = inserted { + if transaction.rollback().await.is_err() { + *self.uncertain = true; + return Ok(AdmissionOutcome::Unknown(anchor)); + } + return Err(error); + } + if transaction.commit().await.is_err() { + *self.uncertain = true; + return Ok(AdmissionOutcome::Unknown(anchor)); + } + Ok(AdmissionOutcome::Committed( + PreparedOperation::from_committed_store( + request, + transaction_id, + radroots_domain::Sequence::new(1).map_err(|_| OperationError::RecoveryRequired)?, + )?, + )) + } + + pub(super) async fn query( + &mut self, + binding: WorkspaceBinding, + operation_id: OperationId, + digest: Option<CommandDigest>, + proof: AttachmentProof, + ) -> Result<Option<PreparedOperation>, OperationError> { + let (record, grant) = self.access(&binding, &proof).await?; + let result = + operation::read(self.connection, self.selected, operation_id, self.crypto).await?; + if let Some((snapshot, _)) = &result { + operation::check_digest(snapshot, binding.actor(), digest)?; + } + let mut transaction = self + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let checked = async { + recheck( + &mut transaction, + self.namespace, + self.selected, + &grant, + &record, + &binding, + &proof, + self.clock, + ) + .await?; + if let Some((snapshot, protected)) = &result { + operation::unchanged(&mut transaction, snapshot, protected).await?; + } else { + let count: i64 = sqlx::query_scalar( + "SELECT count(*) FROM operations WHERE workspace=? AND operation_id=?", + ) + .bind(self.selected.workspace_id().as_bytes().as_slice()) + .bind(operation_id.as_bytes().as_slice()) + .fetch_one(&mut *transaction) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + if count != 0 { + return Err(OperationError::RecoveryRequired); + } + } + Ok(()) + } + .await; + if transaction.rollback().await.is_err() { + *self.uncertain = true; + return Err(OperationError::RecoveryRequired); + } + checked?; + Ok(result.map(|(snapshot, _)| snapshot)) + } +} + +fn same_binding( + captured: &WorkspaceBinding, + current: &WorkspaceBinding, +) -> Result<(), OperationError> { + if captured.input() != current.input() + || captured.actor() != current.actor() + || captured.principal_id() != current.principal_id() + || captured.grant_revision() != current.grant_revision() + || captured.expires_at() != current.expires_at() + { + return Err(OperationError::Unauthorized); + } + Ok(()) +} + +#[expect( + clippy::too_many_arguments, + reason = "Private transaction recheck borrows only the existing owner inputs" +)] +async fn recheck( + transaction: &mut Transaction<'_, Sqlite>, + namespace: &Namespace, + selected: &AttachmentInput, + protected: &[u8], + record: &GrantRecord, + binding: &WorkspaceBinding, + proof: &AttachmentProof, + clock: &dyn WorkspaceClock, +) -> Result<WorkspaceBinding, OperationError> { + namespace.validate()?; + if worker::read(transaction, selected).await? != protected { + return Err(OperationError::RecoveryRequired); + } + // No provider await occurs under this transaction: the exact protected row + // has just matched the authenticated pre-transaction plaintext. + let current = record.authenticate(binding.input(), proof, clock.now()?)?; + same_binding(binding, ¤t)?; + Ok(current) +} diff --git a/crates/storage_sqlite/src/workspace/crypto.rs b/crates/storage_sqlite/src/workspace/crypto.rs @@ -1,5 +1,5 @@ use super::WorkspaceError; -use radroots_domain::{GrantId, WorkspaceId}; +use radroots_domain::{GrantId, OperationId, WorkspaceId}; use radroots_secrets::{ EncryptedEnvelope, SecretRef, context::{EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId}, @@ -48,7 +48,29 @@ impl WorkspaceCrypto { grant: GrantId, plaintext: &[u8], ) -> Result<Vec<u8>, WorkspaceError> { - if plaintext.len() > PRIVATE_PAYLOAD_MAX_BYTES { + self.seal_bound( + context(workspace, grant)?, + PRIVATE_PAYLOAD_MAX_BYTES, + plaintext, + ) + .await + } + pub(super) async fn seal_operation( + &self, + workspace: WorkspaceId, + operation: OperationId, + plaintext: &[u8], + ) -> Result<Vec<u8>, WorkspaceError> { + self.seal_bound(operation_context(workspace, operation)?, 65_536, plaintext) + .await + } + async fn seal_bound( + &self, + context: EnvelopeContext, + max_bytes: usize, + plaintext: &[u8], + ) -> Result<Vec<u8>, WorkspaceError> { + if plaintext.len() > max_bytes { return Err(WorkspaceError::InvalidInput); } let plaintext = @@ -67,7 +89,7 @@ impl WorkspaceCrypto { self.reference.backend(), self.reference.key_version(), ), - context(workspace, grant)?, + context, &plaintext, SealMaterial::new(key, Nonce::new(nonce)), ), @@ -84,6 +106,28 @@ impl WorkspaceCrypto { grant: GrantId, protected: &[u8], ) -> Result<SecretMaterial, WorkspaceError> { + self.open_bound( + context(workspace, grant)?, + PRIVATE_PAYLOAD_MAX_BYTES, + protected, + ) + .await + } + pub(super) async fn open_operation( + &self, + workspace: WorkspaceId, + operation: OperationId, + protected: &[u8], + ) -> Result<SecretMaterial, WorkspaceError> { + self.open_bound(operation_context(workspace, operation)?, 65_536, protected) + .await + } + async fn open_bound( + &self, + context: EnvelopeContext, + max_bytes: usize, + protected: &[u8], + ) -> Result<SecretMaterial, WorkspaceError> { if protected.len() > PROTECTED_MAX_BYTES { return Err(WorkspaceError::RecoveryRequired); } @@ -92,7 +136,7 @@ impl WorkspaceCrypto { self.provider .wrap(radroots_secrets::wrapping::WrapRequest::new( &self.reference, - &context(workspace, grant)?, + &context, &self.key, )) .await @@ -106,10 +150,10 @@ impl WorkspaceCrypto { return Err(WorkspaceError::RecoveryRequired); } let plaintext = envelope - .open(self.provider.as_ref(), &context(workspace, grant)?) + .open(self.provider.as_ref(), &context) .await .map_err(|_| WorkspaceError::RecoveryRequired)?; - if plaintext.len() > PRIVATE_PAYLOAD_MAX_BYTES { + if plaintext.len() > max_bytes { return Err(WorkspaceError::RecoveryRequired); } Ok(plaintext) @@ -133,3 +177,17 @@ fn context(workspace: WorkspaceId, grant: GrantId) -> Result<EnvelopeContext, Wo .map_err(|_| WorkspaceError::InvalidInput)?, )) } + +fn operation_context( + workspace: WorkspaceId, + operation: OperationId, +) -> Result<EnvelopeContext, WorkspaceError> { + Ok(EnvelopeContext::new( + EnvelopePurpose::parse("radroots.workspace.operation") + .map_err(|_| WorkspaceError::InvalidInput)?, + EnvelopeSubject::parse("workspace_operation", format!("{workspace}{operation}")) + .map_err(|_| WorkspaceError::InvalidInput)?, + PayloadSchemaId::parse("radroots.workspace.operation.v1") + .map_err(|_| WorkspaceError::InvalidInput)?, + )) +} diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs @@ -5,8 +5,10 @@ //! single connection and persistent writer lock belong to one bounded worker. //! Losing an observer never drops that lock ahead of the SQLite connection. +mod admission; mod crypto; mod fs; +mod operation; mod record; mod worker; @@ -210,6 +212,36 @@ impl WorkspaceStore for NativeWorkspace { Box::pin(self.close()) } } +impl radroots_storage::command::OperationJournal for NativeWorkspace { + fn admit_command_and_hold( + &self, + request: radroots_storage::command::AdmissionRequest, + proof: AttachmentProof, + ) -> BoxFuture< + '_, + Result< + radroots_storage::command::AdmissionOutcome, + radroots_storage::command::OperationError, + >, + > { + Box::pin(self.worker.admit(request, proof)) + } + fn operation( + &self, + binding: WorkspaceBinding, + operation_id: radroots_domain::OperationId, + digest: Option<radroots_domain::CommandDigest>, + proof: AttachmentProof, + ) -> BoxFuture< + '_, + Result< + Option<radroots_storage::command::PreparedOperation>, + radroots_storage::command::OperationError, + >, + > { + Box::pin(self.worker.operation(binding, operation_id, digest, proof)) + } +} fn random() -> Result<[u8; 32], WorkspaceError> { let mut value = [0; 32]; getrandom::getrandom(&mut value).map_err(|_| WorkspaceError::Unavailable)?; diff --git a/crates/storage_sqlite/src/workspace/operation.rs b/crates/storage_sqlite/src/workspace/operation.rs @@ -0,0 +1,214 @@ +//! Retained non-stock command preparation. No signing or delivery occurs here. + +use super::{AttachmentInput, WorkspaceBinding, crypto::WorkspaceCrypto}; +use radroots_domain::{CommandDigest, OperationId, Sequence, TransactionId, UnixSeconds}; +use radroots_storage::command::{AdmissionRequest, OperationError, PreparedOperation}; +use serde::{Deserialize, Serialize}; +use sqlx::{Row, SqliteConnection}; +use zeroize::Zeroizing; + +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 INDEX: &str = + "CREATE UNIQUE INDEX operation_transaction_identity ON operations(workspace,transaction_id)"; + +#[derive(Serialize)] +struct Encoded<'a> { + version: u8, + selection: &'a AttachmentInput, + principal: &'a str, + grant_revision: Sequence, + grant_expires_at: UnixSeconds, + captured_observed_at: UnixSeconds, + transaction_id: TransactionId, + revision: Sequence, + command: &'a serde_json::value::RawValue, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Decoded<'a> { + version: u8, + selection: AttachmentInput, + principal: String, + grant_revision: Sequence, + grant_expires_at: UnixSeconds, + captured_observed_at: UnixSeconds, + transaction_id: TransactionId, + revision: Sequence, + #[serde(borrow)] + command: &'a serde_json::value::RawValue, +} + +pub(super) async fn protect( + request: &AdmissionRequest, + transaction_id: TransactionId, + crypto: &WorkspaceCrypto, +) -> Result<Vec<u8>, OperationError> { + let binding = request.binding(); + let encoded = Encoded { + version: 1, + selection: binding.input(), + principal: binding.principal_id(), + grant_revision: binding.grant_revision(), + grant_expires_at: binding.expires_at(), + captured_observed_at: binding.observed_at(), + transaction_id, + revision: Sequence::new(1).map_err(|_| OperationError::RecoveryRequired)?, + command: serde_json::from_slice(request.command().protected_wire()) + .map_err(|_| OperationError::InvalidCommand)?, + }; + let plaintext = + Zeroizing::new(serde_json::to_vec(&encoded).map_err(|_| OperationError::InvalidCommand)?); + if plaintext.len() > 65_536 { + return Err(OperationError::InvalidCommand); + } + Ok(crypto + .seal_operation( + binding.input().workspace_id(), + request.command().context().operation_id(), + &plaintext, + ) + .await?) +} + +pub(super) async fn read( + connection: &mut SqliteConnection, + selected: &AttachmentInput, + operation_id: OperationId, + crypto: &WorkspaceCrypto, +) -> Result<Option<(PreparedOperation, Vec<u8>)>, OperationError> { + let row = sqlx::query("SELECT CASE WHEN length(actor)=32 THEN actor END,CASE WHEN length(grant_id)=32 THEN grant_id END,CASE WHEN length(command_type)<=80 THEN command_type END,CASE WHEN length(command_digest)=32 THEN command_digest END,CASE WHEN length(transaction_id)=32 THEN transaction_id END,CASE WHEN length(phase)<=32 THEN phase END,revision,CASE WHEN length(protected)>0 AND length(protected)<=262144 THEN protected END FROM operations WHERE workspace=? AND operation_id=?") + .bind(selected.workspace_id().as_bytes().as_slice()).bind(operation_id.as_bytes().as_slice()) + .fetch_optional(&mut *connection).await.map_err(|_| OperationError::RecoveryRequired)?; + let Some(row) = row else { + return Ok(None); + }; + let bytes = |index| -> Result<Vec<u8>, OperationError> { + row.try_get::<Option<Vec<u8>>, _>(index) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired) + }; + let actor = bytes(0)?; + let grant = bytes(1)?; + let kind: String = row + .try_get::<Option<String>, _>(2) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)?; + let digest = bytes(3)?; + let transaction = bytes(4)?; + let phase: String = row + .try_get::<Option<String>, _>(5) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)?; + let revision: i64 = row + .try_get(6) + .map_err(|_| OperationError::RecoveryRequired)?; + let protected = bytes(7)?; + let plaintext = crypto + .open_operation(selected.workspace_id(), operation_id, &protected) + .await?; + let snapshot = plaintext.expose_secret(|bytes| { + let decoded: Decoded<'_> = + serde_json::from_slice(bytes).map_err(|_| OperationError::RecoveryRequired)?; + if decoded.version != 1 + || decoded.revision.get() == 0 + || phase != "prepared" + || revision != 1 + || decoded.revision.get() != revision as u64 + { + return Err(OperationError::RecoveryRequired); + } + let command_context: radroots_domain::CommandContextData = { + #[derive(Deserialize)] + struct ContextOnly { + context: radroots_domain::CommandContextData, + } + serde_json::from_str::<ContextOnly>(decoded.command.get()) + .map_err(|_| OperationError::RecoveryRequired)? + .context + }; + let binding = WorkspaceBinding::from_authenticated_host( + decoded.selection, + command_context.actor(), + decoded.principal, + decoded.grant_revision, + decoded.grant_expires_at, + decoded.captured_observed_at, + )?; + if binding.input() != selected { + return Err(OperationError::RecoveryRequired); + } + let request = + AdmissionRequest::from_protected_wire(binding, decoded.command.get().as_bytes())?; + let context = request.command().context(); + if context.workspace_id() != selected.workspace_id() + || context.operation_id() != operation_id + || actor != context.actor().participant().as_bytes() + || grant != request.binding().input().grant_id().as_bytes() + || digest != request.command().digest().as_bytes() + || transaction != decoded.transaction_id.as_bytes() + || kind != request.command().kind().as_str() + { + return Err(OperationError::RecoveryRequired); + } + let snapshot = PreparedOperation::from_committed_store( + request, + decoded.transaction_id, + decoded.revision, + )?; + Ok::<_, OperationError>(snapshot) + })?; + Ok(Some((snapshot, protected))) +} + +pub(super) async fn insert( + connection: &mut SqliteConnection, + request: &AdmissionRequest, + transaction_id: TransactionId, + protected: &[u8], +) -> Result<(), OperationError> { + let context = request.command().context(); + sqlx::query("INSERT INTO operations(workspace,operation_id,actor,grant_id,command_type,command_digest,transaction_id,phase,revision,protected,grant_singleton) VALUES(?,?,?,?,?,?,?,'prepared',1,?,1)") + .bind(context.workspace_id().as_bytes().as_slice()).bind(context.operation_id().as_bytes().as_slice()) + .bind(context.actor().participant().as_bytes().as_slice()).bind(request.binding().input().grant_id().as_bytes().as_slice()) + .bind(request.command().kind().as_str()).bind(request.command().digest().as_bytes().as_slice()) + .bind(transaction_id.as_bytes().as_slice()).bind(protected) + .execute(connection).await.map_err(|_| OperationError::StorageFailure)?; + Ok(()) +} + +/// Rechecks the retained ciphertext and every indexed fact in one transaction, +/// without awaiting a provider, signer or network capability under it. +pub(super) async fn unchanged( + connection: &mut SqliteConnection, + snapshot: &PreparedOperation, + expected: &[u8], +) -> Result<(), OperationError> { + let request = snapshot.request(); + let context = request.command().context(); + let matched: i64 = sqlx::query_scalar("SELECT count(*) FROM operations WHERE workspace=? AND operation_id=? AND actor=? AND grant_id=? AND command_type=? AND command_digest=? AND transaction_id=? AND phase='prepared' AND revision=? AND protected=?") + .bind(context.workspace_id().as_bytes().as_slice()).bind(context.operation_id().as_bytes().as_slice()) + .bind(context.actor().participant().as_bytes().as_slice()).bind(request.binding().input().grant_id().as_bytes().as_slice()) + .bind(request.command().kind().as_str()).bind(request.command().digest().as_bytes().as_slice()) + .bind(snapshot.transaction_id().as_bytes().as_slice()) + // Sequence construction enforces the signed 64-bit storage bound. + .bind(snapshot.revision().get() as i64).bind(expected) + .fetch_one(connection).await.map_err(|_| OperationError::RecoveryRequired)?; + if matched != 1 { + return Err(OperationError::RecoveryRequired); + } + Ok(()) +} + +pub(super) fn check_digest( + snapshot: &PreparedOperation, + actor: radroots_domain::ActorRef, + expected: Option<CommandDigest>, +) -> Result<(), OperationError> { + if snapshot.request().command().context().actor().participant() != actor.participant() { + return Err(OperationError::Unauthorized); + } + if expected.is_some_and(|digest| digest != snapshot.request().command().digest()) { + return Err(OperationError::IdempotencyConflict); + } + Ok(()) +} diff --git a/crates/storage_sqlite/src/workspace/tests/mod.rs b/crates/storage_sqlite/src/workspace/tests/mod.rs @@ -1,4 +1,5 @@ use super::*; +mod operation_records; use radroots_domain::{ActorRef, SourceId}; use radroots_secrets::{ EncryptedEnvelope, SecretId, SecretRef, @@ -555,7 +556,7 @@ async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_r .await .unwrap(); let statement = match fault { - 0 => "PRAGMA user_version=2", + 0 => "PRAGMA user_version=3", 1 => "DELETE FROM workspace_grant", 2 => "UPDATE workspace_grant SET grant_id=zeroblob(31)", 3 => "UPDATE workspace_grant SET protected=zeroblob(0)", @@ -601,7 +602,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 { 2 } else { 1 }); + assert_eq!(version, if fault == 0 { 3 } else { 2 }); assert_eq!(rows, if fault == 1 { 0 } else { 1 }); if (3..=5).contains(&fault) { let size: i64 = sqlx::query_scalar("SELECT length(protected) FROM workspace_grant") diff --git a/crates/storage_sqlite/src/workspace/tests/operation_records.rs b/crates/storage_sqlite/src/workspace/tests/operation_records.rs @@ -0,0 +1,186 @@ +use super::*; +use crate::workspace::operation; +use radroots_domain::{CommandContextData, OperationId}; +use radroots_storage::command::{ + AdmissionOutcome, AdmissionRequest, OperationError, OperationJournal, +}; +use serde_json::{Value, json}; +use sqlx::{Connection, SqliteConnection}; + +#[tokio::test] +async fn protected_operation_read_refuses_each_inconsistent_payload_and_sql_projection_without_repair() + { + let fixture = CryptoFixture::new(); + let path = fixture + ._temp + .path() + .canonicalize() + .unwrap() + .join("operation-records"); + let (store, selected, proof) = NativeWorkspace::initialize_local_outbox( + &path, + LocalOutboxConfig::new( + participant(), + participant(), + "device", + UnixSeconds::new(200).unwrap(), + ) + .unwrap(), + fixture.crypto(), + Arc::new(FixedClock(100)), + ) + .await + .unwrap(); + let binding = store.authenticate(selected.clone(), &proof).await.unwrap(); + let operation_id = OperationId::from_bytes([11; 32]); + let context = CommandContextData::new( + operation_id, + binding.actor(), + selected.workspace_id(), + selected.authority(), + selected.route_digest(), + None, + None, + UnixSeconds::new(150).unwrap(), + None, + ) + .unwrap(); + let wire = serde_json::to_vec(&json!({"type": "inbox.inquire", "context": context, + "input": {"thread_id": "66".repeat(32), "peer": participant(), "source": null, "text": "synthetic private record"}})).unwrap(); + let request = AdmissionRequest::from_protected_wire(binding, &wire).unwrap(); + let copied = proof.with_secret(|secret| AttachmentProof::from_protected_input(secret).unwrap()); + let retained = match store.admit_command_and_hold(request, copied).await.unwrap() { + AdmissionOutcome::Committed(snapshot) => snapshot, + AdmissionOutcome::Unknown(_) => panic!("fixture preparation must confirm its commit"), + }; + store.close().await.unwrap(); + let mut database = SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .filename(path.join("execution_v1.sqlite")) + .create_if_missing(false), + ) + .await + .unwrap(); + let original: Vec<u8> = sqlx::query_scalar("SELECT protected FROM operations") + .fetch_one(&mut database) + .await + .unwrap(); + let crypto = fixture.crypto(); + let opened = crypto + .open_operation(selected.workspace_id(), operation_id, &original) + .await + .unwrap(); + let value: Value = opened.expose_secret(|bytes| serde_json::from_slice(bytes).unwrap()); + for (pointer, replacement) in [ + ("/version", json!(2)), + ("/revision", json!("0")), + ("/revision", json!("2")), + ("/selection/endpoint", json!("local://changed")), + ("/command/context/operation_id", json!("77".repeat(32))), + ] { + let mut changed = value.clone(); + *changed.pointer_mut(pointer).unwrap() = replacement; + let ciphertext = crypto + .seal_operation( + selected.workspace_id(), + operation_id, + &serde_json::to_vec(&changed).unwrap(), + ) + .await + .unwrap(); + sqlx::query("UPDATE operations SET protected=?") + .bind(&ciphertext) + .execute(&mut database) + .await + .unwrap(); + assert!( + matches!( + operation::read(&mut database, &selected, operation_id, &crypto).await, + Err(OperationError::RecoveryRequired) + ), + "{pointer}" + ); + let unchanged: Vec<u8> = sqlx::query_scalar("SELECT protected FROM operations") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(unchanged, ciphertext); + } + // The following corruption is confined to this owned fixture database. + // Reads must validate independently of SQLite's original CHECK constraints. + sqlx::query("PRAGMA ignore_check_constraints=ON") + .execute(&mut database) + .await + .unwrap(); + for assignment in [ + "UPDATE operations SET phase='other'", + "UPDATE operations SET revision=2", + "UPDATE operations SET actor=zeroblob(32)", + "UPDATE operations SET grant_id=zeroblob(32)", + "UPDATE operations SET command_digest=zeroblob(32)", + "UPDATE operations SET transaction_id=zeroblob(32)", + "UPDATE operations SET command_type='inbox.reply'", + "UPDATE operations SET actor=zeroblob(31)", + "UPDATE operations SET protected=zeroblob(262145)", + ] { + sqlx::query("UPDATE operations SET actor=?,grant_id=?,command_digest=?,transaction_id=?,command_type='inbox.inquire',phase='prepared',revision=1,protected=?") + .bind(participant().as_bytes().as_slice()).bind(selected.grant_id().as_bytes().as_slice()) + .bind(retained.identity().command_digest().as_bytes().as_slice()).bind(retained.transaction_id().as_bytes().as_slice()) + .bind(&original).execute(&mut database).await.unwrap(); + sqlx::query(assignment) + .execute(&mut database) + .await + .unwrap(); + assert!( + matches!( + operation::read(&mut database, &selected, operation_id, &crypto).await, + Err(OperationError::RecoveryRequired) + ), + "{assignment}" + ); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM operations") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(count, 1); + } + let mut transaction = database.begin_with("BEGIN IMMEDIATE").await.unwrap(); + assert!(matches!( + operation::unchanged(&mut transaction, &retained, &original).await, + Err(OperationError::RecoveryRequired) + )); + transaction.rollback().await.unwrap(); + let length: i64 = sqlx::query_scalar("SELECT length(protected) FROM operations") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(length, 262145); + let other = + PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5") + .unwrap(); + assert_eq!( + operation::check_digest( + &retained, + ActorRef::new(other, ActorRole::Buyer, None, Some(selected.grant_id())), + None + ), + Err(OperationError::Unauthorized) + ); + // A retained ciphertext alone cannot confirm unchanged indexed facts. + let mut different_digest = retained.identity().command_digest().into_bytes(); + different_digest[0] ^= 1; + sqlx::query("UPDATE operations SET protected=?,command_digest=?") + .bind(&original) + .bind(different_digest.as_slice()) + .execute(&mut database) + .await + .unwrap(); + let mut transaction = database.begin_with("BEGIN IMMEDIATE").await.unwrap(); + let checked = operation::unchanged(&mut transaction, &retained, &original).await; + transaction.rollback().await.unwrap(); + database.close().await.unwrap(); + assert!( + matches!(checked, Err(OperationError::RecoveryRequired)), + "unchanged ciphertext must not hide changed indexed facts" + ); +} diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -1,6 +1,10 @@ use super::{ AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceCrypto, - WorkspaceError, fs::Namespace, record::GrantRecord, + WorkspaceError, admission::Journal, fs::Namespace, operation, record::GrantRecord, +}; +use radroots_domain::{CommandDigest, OperationId}; +use radroots_storage::command::{ + AdmissionOutcome, AdmissionRequest, CommitAttempt, OperationError, PreparedOperation, }; use sqlx::{ Connection, Row, SqliteConnection, @@ -19,13 +23,26 @@ use tokio::sync::{oneshot, watch}; // Each request holds bounded descriptors and one 32-byte proof. With 32 // queued requests and a single in-flight request this is below the 4 MiB -// contract. No raw event/command/SQL or unbounded payload enters this queue. +// contract. Command data has a 64 KiB canonical bound, 4 KiB decoded text and +// bounded exact-sized descriptors; no unbounded event/SQL enters this queue. const QUEUE_CAPACITY: usize = 32; const TABLE: &str = "CREATE TABLE workspace_grant (singleton INTEGER PRIMARY KEY CHECK(singleton=1), workspace BLOB NOT NULL CHECK(length(workspace)=32), grant_id BLOB NOT NULL CHECK(length(grant_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT"; -type Reply<T> = oneshot::Sender<Result<T, WorkspaceError>>; +type Reply<T, E = WorkspaceError> = oneshot::Sender<Result<T, E>>; enum Job { Authenticate(AttachmentInput, AttachmentProof, Reply<WorkspaceBinding>), Revoke(AttachmentInput, AttachmentProof, Reply<()>), + Admit( + Box<AdmissionRequest>, + AttachmentProof, + Reply<AdmissionOutcome, OperationError>, + ), + Operation( + Box<WorkspaceBinding>, + OperationId, + Option<CommandDigest>, + AttachmentProof, + Reply<Option<PreparedOperation>, OperationError>, + ), } pub(super) struct Handle { sender: Mutex<Option<SyncSender<Job>>>, @@ -98,6 +115,7 @@ impl Handle { let _ = connection.close().await; return Err(error); } + let mut uncertain = false; if ready.send(Ok(())).is_ok() { while let Ok(job) = requests.recv() { match job { @@ -128,6 +146,32 @@ impl Handle { .await; let _ = reply.send(result); } + Job::Admit(request, proof, reply) => { + let result = Journal { + connection: &mut connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + } + .admit(*request, proof) + .await; + let _ = reply.send(result); + } + Job::Operation(binding, operation_id, digest, proof, reply) => { + let result = Journal { + connection: &mut connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + } + .query(*binding, operation_id, digest, proof) + .await; + let _ = reply.send(result); + } } } } @@ -197,6 +241,42 @@ impl Handle { self.send(Job::Revoke(input, proof, reply))?; result.await.map_err(|_| WorkspaceError::CommitUnknown)? } + pub(super) async fn admit( + &self, + request: AdmissionRequest, + proof: AttachmentProof, + ) -> Result<AdmissionOutcome, OperationError> { + let context = request.command().context(); + let anchor = CommitAttempt::new( + context.workspace_id(), + context.operation_id(), + request.command().digest(), + None, + ); + let (reply, result) = oneshot::channel(); + self.send(Job::Admit(Box::new(request), proof, reply))?; + match result.await { + Ok(result) => result, + Err(_) => Ok(AdmissionOutcome::Unknown(anchor)), + } + } + pub(super) async fn operation( + &self, + binding: WorkspaceBinding, + operation_id: OperationId, + digest: Option<CommandDigest>, + proof: AttachmentProof, + ) -> Result<Option<PreparedOperation>, OperationError> { + let (reply, result) = oneshot::channel(); + self.send(Job::Operation( + Box::new(binding), + operation_id, + digest, + proof, + reply, + ))?; + result.await.map_err(|_| OperationError::RecoveryRequired)? + } pub(super) async fn close(&self) -> Result<(), WorkspaceError> { self.sender .lock() @@ -269,7 +349,15 @@ async fn initialize( .execute(&mut *transaction) .await .map_err(|_| WorkspaceError::StorageFailure)?; - sqlx::query("PRAGMA user_version=1") + sqlx::raw_sql(operation::TABLE) + .execute(&mut *transaction) + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + sqlx::raw_sql(operation::INDEX) + .execute(&mut *transaction) + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + sqlx::query("PRAGMA user_version=2") .execute(&mut *transaction) .await .map_err(|_| WorkspaceError::StorageFailure)?; @@ -291,11 +379,11 @@ async fn initialize( .fetch_one(&mut *connection) .await .map_err(|_| WorkspaceError::RecoveryRequired)?; - if version != 1 { + if version != 2 { return Err(WorkspaceError::RecoveryRequired); } - let catalog_matches: i64 = sqlx::query_scalar("SELECT CASE WHEN count(*)=1 AND sum(CASE WHEN type='table' AND name='workspace_grant' AND tbl_name='workspace_grant' AND sql=? THEN 1 ELSE 0 END)=1 THEN 1 ELSE 0 END FROM sqlite_schema") - .bind(TABLE).fetch_one(&mut *connection).await.map_err(|_| WorkspaceError::RecoveryRequired)?; + let catalog_matches: i64 = sqlx::query_scalar("SELECT CASE WHEN count(*)=3 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='index' AND name='operation_transaction_identity' AND tbl_name='operations' AND sql=? THEN 1 ELSE 0 END)=3 THEN 1 ELSE 0 END FROM sqlite_schema") + .bind(TABLE).bind(operation::TABLE).bind(operation::INDEX).fetch_one(&mut *connection).await.map_err(|_| WorkspaceError::RecoveryRequired)?; if catalog_matches != 1 { return Err(WorkspaceError::RecoveryRequired); } @@ -313,7 +401,7 @@ async fn initialize( plaintext.expose_secret(GrantRecord::decode)?; namespace.validate() } -async fn read( +pub(super) async fn read( connection: &mut SqliteConnection, expected: &AttachmentInput, ) -> Result<Vec<u8>, WorkspaceError> { diff --git a/crates/storage_sqlite/tests/workspace_admission.rs b/crates/storage_sqlite/tests/workspace_admission.rs @@ -0,0 +1,806 @@ +#![cfg(unix)] + +use radroots_domain::{ + CommandContextData, CommandDigest, CorrelationId, OperationId, PublicKey, UnixSeconds, +}; +use radroots_secrets::{ + SecretId, SecretRef, + envelope::Nonce, + file::{FileOpenMode, FileProvider}, + id::{BackendKind, KeyVersion}, + provider::AccessPolicy, + wrapping::SecretMaterial, +}; +use radroots_storage::{ + command::{ + AdmissionOutcome, AdmissionRequest, OperationError, OperationJournal, PreparedOperation, + }, + workspace::{ + AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceError, + }, +}; +use radroots_storage_sqlite::workspace::{LocalOutboxConfig, NativeWorkspace, WorkspaceCrypto}; +use serde_json::json; +use sqlx::{Connection, SqliteConnection}; +use std::{ + path::PathBuf, + sync::{ + Arc, Mutex, + atomic::{AtomicU64, Ordering}, + mpsc, + }, + time::Duration, +}; + +struct Pause { + skip: usize, + reached: mpsc::SyncSender<()>, + resume: mpsc::Receiver<()>, +} +struct Clock { + now: AtomicU64, + pause: Mutex<Option<Pause>>, +} +impl Clock { + fn arm(&self, skip: usize) -> (mpsc::Receiver<()>, mpsc::SyncSender<()>) { + let (reached, receive) = mpsc::sync_channel(1); + let (resume, released) = mpsc::sync_channel(1); + *self.pause.lock().unwrap() = Some(Pause { + skip, + reached, + resume: released, + }); + (receive, resume) + } +} +impl WorkspaceClock for Clock { + fn now(&self) -> Result<UnixSeconds, WorkspaceError> { + let pause = { + let mut selected = self.pause.lock().unwrap(); + if let Some(pause) = selected.as_mut() { + if pause.skip == 0 { + selected.take() + } else { + pause.skip -= 1; + None + } + } else { + None + } + }; + if let Some(pause) = pause { + pause + .reached + .send(()) + .map_err(|_| WorkspaceError::Unavailable)?; + pause + .resume + .recv_timeout(Duration::from_secs(10)) + .map_err(|_| WorkspaceError::Unavailable)?; + } + UnixSeconds::new(self.now.load(Ordering::SeqCst)).map_err(|_| WorkspaceError::Unavailable) + } +} +struct Fixture { + _root: tempfile::TempDir, + path: PathBuf, + provider: Arc<FileProvider>, + clock: Arc<Clock>, +} +impl Fixture { + fn new() -> Self { + let root = tempfile::tempdir().unwrap(); + let base = root.path().canonicalize().unwrap(); + let provider = Arc::new( + FileProvider::open( + base.join("vault"), + FileOpenMode::CreateNew, + SecretMaterial::from_slice(&[0xa5; 32]).unwrap(), + ) + .unwrap(), + ); + provider + .provision( + &reference(), + &SecretMaterial::from_slice(&[0x41; 32]).unwrap(), + Nonce::new([0x11; 24]), + ) + .unwrap(); + Self { + _root: root, + path: base.join("outbox"), + provider, + clock: Arc::new(Clock { + now: AtomicU64::new(100), + pause: Mutex::new(None), + }), + } + } + fn crypto(&self) -> WorkspaceCrypto { + WorkspaceCrypto::new( + self.provider.clone(), + reference(), + SecretMaterial::from_slice(&[0x41; 32]).unwrap(), + AccessPolicy::standard(), + ) + .unwrap() + } + async fn create( + &self, + ) -> ( + Arc<NativeWorkspace>, + AttachmentInput, + AttachmentProof, + WorkspaceBinding, + ) { + let (store, input, proof) = NativeWorkspace::initialize_local_outbox( + &self.path, + LocalOutboxConfig::new( + key(), + key(), + "synthetic-device", + UnixSeconds::new(200).unwrap(), + ) + .unwrap(), + self.crypto(), + self.clock.clone(), + ) + .await + .unwrap(); + let binding = store.authenticate(input.clone(), &proof).await.unwrap(); + (Arc::new(store), input, proof, binding) + } + async fn database(&self) -> SqliteConnection { + SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .filename(self.path.join("execution_v1.sqlite")) + .create_if_missing(false), + ) + .await + .unwrap() + } + async fn reopen(&self, input: AttachmentInput) -> NativeWorkspace { + NativeWorkspace::open_existing(&self.path, input, self.crypto(), self.clock.clone()) + .await + .unwrap() + } +} +fn reference() -> SecretRef { + SecretRef::new( + SecretId::parse("workspace-key").unwrap(), + BackendKind::File, + KeyVersion::new(1).unwrap(), + ) +} +fn key() -> PublicKey { + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() +} +fn copy(proof: &AttachmentProof) -> AttachmentProof { + proof.with_secret(|secret| AttachmentProof::from_protected_input(secret).unwrap()) +} +fn request(binding: &WorkspaceBinding, id: u8, text: &str, correlation: &str) -> AdmissionRequest { + let input = binding.input(); + let context = CommandContextData::new( + OperationId::from_bytes([id; 32]), + binding.actor(), + input.workspace_id(), + input.authority(), + input.route_digest(), + None, + None, + UnixSeconds::new(150).unwrap(), + Some(CorrelationId::new(correlation).unwrap()), + ) + .unwrap(); + let bytes = serde_json::to_vec(&json!({"type": "inbox.inquire", "context": context, + "input": {"thread_id": "66".repeat(32), "peer": key(), "source": null, "text": text}})) + .unwrap(); + AdmissionRequest::from_protected_wire(binding.clone(), &bytes).unwrap() +} +fn committed(outcome: AdmissionOutcome) -> PreparedOperation { + match outcome { + AdmissionOutcome::Committed(result) => result, + AdmissionOutcome::Unknown(_) => panic!("unexpected unknown completion"), + } +} +async fn reached(receiver: mpsc::Receiver<()>) { + tokio::task::spawn_blocking(move || receiver.recv_timeout(Duration::from_secs(10))) + .await + .unwrap() + .unwrap(); +} + +#[tokio::test] +async fn actual_commit_reopen_and_replay_preserve_original_identity_and_private_command() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let captured = request( + &binding, + 1, + "private-cabbage-inquiry-🧺", + "original-observer", + ); + let digest = captured.command().digest(); + let original = committed( + store + .admit_command_and_hold(captured, copy(&proof)) + .await + .unwrap(), + ); + let anchor = original.identity(); + assert_eq!(original.revision().get(), 1); + assert_eq!( + original.request().command().text(), + "private-cabbage-inquiry-🧺" + ); + assert_eq!(original.request().binding().input(), &input); + assert!( + store + .operation( + binding.clone(), + OperationId::from_bytes([9; 32]), + None, + copy(&proof) + ) + .await + .unwrap() + .is_none() + ); + 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"private-cabbage-inquiry".len()) + .any(|value| value == b"private-cabbage-inquiry") + ); + } + } + 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); + let replay = committed( + reopened + .admit_command_and_hold( + request(&binding, 1, "private-cabbage-inquiry-🧺", "new-observer"), + copy(&proof), + ) + .await + .unwrap(), + ); + assert_eq!(replay.identity(), anchor); + assert_eq!( + replay + .request() + .command() + .context() + .correlation_id() + .unwrap() + .as_str(), + "original-observer" + ); + assert!(matches!( + reopened + .admit_command_and_hold(request(&binding, 1, "changed", "new"), copy(&proof)) + .await, + Err(OperationError::IdempotencyConflict) + )); + assert!(matches!( + reopened + .operation( + binding.clone(), + anchor.operation_id(), + Some(CommandDigest::from_bytes([0; 32])), + copy(&proof) + ) + .await, + Err(OperationError::IdempotencyConflict) + )); + assert!(matches!( + reopened + .admit_command_and_hold( + request(&binding, 2, "new expired command", "new"), + copy(&proof) + ) + .await, + Err(OperationError::DeadlineExceeded) + )); + let mut database = fixture.database().await; + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM operations") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(count, 1); + database.close().await.unwrap(); + reopened.close().await.unwrap(); +} + +#[tokio::test] +async fn current_proof_and_revocation_are_checked_for_admission_and_retained_queries() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let wrong = AttachmentProof::from_protected_input(&[0; 32]).unwrap(); + assert!(matches!( + store + .admit_command_and_hold(request(&binding, 3, "private", "one"), wrong) + .await, + Err(OperationError::Workspace(WorkspaceError::Unauthorized)) + )); + committed( + store + .admit_command_and_hold(request(&binding, 3, "private", "one"), copy(&proof)) + .await + .unwrap(), + ); + store.revoke(input, &proof).await.unwrap(); + assert!(matches!( + store + .operation( + binding.clone(), + OperationId::from_bytes([3; 32]), + None, + copy(&proof) + ) + .await, + Err(OperationError::Workspace(WorkspaceError::GrantRevoked)) + )); + assert!(matches!( + store + .admit_command_and_hold(request(&binding, 3, "private", "retry"), copy(&proof)) + .await, + Err(OperationError::Workspace(WorkspaceError::GrantRevoked)) + )); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn transaction_time_clock_rejects_expiry_after_capture_and_rolls_back() { + let fixture = Fixture::new(); + let (store, _, proof, binding) = fixture.create().await; + let captured = request(&binding, 4, "late", "one"); + let (arrived, resume) = fixture.clock.arm(1); + let owner = store.clone(); + let secret = copy(&proof); + let task = tokio::spawn(async move { owner.admit_command_and_hold(captured, secret).await }); + reached(arrived).await; + fixture.clock.now.store(150, Ordering::SeqCst); + resume.send(()).unwrap(); + assert!(matches!( + task.await.unwrap(), + Err(OperationError::DeadlineExceeded) + )); + assert!( + store + .operation( + binding, + OperationId::from_bytes([4; 32]), + None, + copy(&proof) + ) + .await + .unwrap() + .is_none() + ); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn lost_observer_does_not_cancel_admitted_transaction_and_close_drains_it() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let captured = request(&binding, 5, "retained after observer cancellation", "gone"); + let digest = captured.command().digest(); + let (arrived, resume) = fixture.clock.arm(1); + let owner = store.clone(); + let secret = copy(&proof); + let task = tokio::spawn(async move { owner.admit_command_and_hold(captured, secret).await }); + reached(arrived).await; + task.abort(); + assert!(task.await.unwrap_err().is_cancelled()); + resume.send(()).unwrap(); + store.close().await.unwrap(); + let reopened = fixture.reopen(input).await; + let result = reopened + .operation( + binding, + OperationId::from_bytes([5; 32]), + Some(digest), + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!( + result.request().command().text(), + "retained after observer cancellation" + ); + reopened.close().await.unwrap(); +} + +#[tokio::test] +async fn actual_sqlite_statement_failure_confirms_rollback_before_known_failure() { + let fixture = Fixture::new(); + let (store, _, proof, binding) = fixture.create().await; + let mut database = fixture.database().await; + sqlx::raw_sql("CREATE TRIGGER fail_admission BEFORE INSERT ON operations BEGIN SELECT RAISE(ABORT,'isolated fixture'); END") + .execute(&mut database).await.unwrap(); + assert!(matches!( + store + .admit_command_and_hold(request(&binding, 6, "rollback", "one"), copy(&proof)) + .await, + Err(OperationError::StorageFailure) + )); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM operations") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(count, 0); + sqlx::raw_sql("DROP TRIGGER fail_admission") + .execute(&mut database) + .await + .unwrap(); + committed( + store + .admit_command_and_hold(request(&binding, 6, "rollback", "two"), copy(&proof)) + .await + .unwrap(), + ); + database.close().await.unwrap(); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn actual_sqlite_commit_failure_stays_unknown_until_safe_close_and_reopen() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let mut database = fixture.database().await; + sqlx::raw_sql("CREATE TABLE deferred_fault(value INTEGER REFERENCES workspace_grant(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_commit AFTER INSERT ON operations BEGIN INSERT INTO deferred_fault VALUES(2); END") + .execute(&mut database).await.unwrap(); + let captured = request(&binding, 7, "uncertain completion", "one"); + let digest = captured.command().digest(); + let anchor = match store + .admit_command_and_hold(captured, copy(&proof)) + .await + .unwrap() + { + AdmissionOutcome::Unknown(anchor) => anchor, + AdmissionOutcome::Committed(_) => panic!("deferred constraint should fail COMMIT"), + }; + assert_eq!(anchor.operation_id(), OperationId::from_bytes([7; 32])); + assert_eq!(anchor.command_digest(), digest); + assert!(anchor.transaction_id().is_some()); + assert!(matches!( + store + .operation( + binding.clone(), + anchor.operation_id(), + Some(digest), + copy(&proof) + ) + .await, + Err(OperationError::RecoveryRequired) + )); + assert!(matches!( + store + .admit_command_and_hold(request(&binding, 8, "blocked", "two"), copy(&proof)) + .await, + Err(OperationError::RecoveryRequired) + )); + store.close().await.unwrap(); + sqlx::raw_sql("DROP TRIGGER fail_commit; DROP TABLE deferred_fault") + .execute(&mut database) + .await + .unwrap(); + database.close().await.unwrap(); + let reopened = fixture.reopen(input).await; + // No signer or transport has run in this Prepared-only component. This is + // reconciliation of this original T0, not a general no-external-effect proof. + assert!( + reopened + .operation(binding, anchor.operation_id(), Some(digest), copy(&proof)) + .await + .unwrap() + .is_none() + ); + reopened.close().await.unwrap(); +} + +#[tokio::test] +async fn protected_grant_is_rechecked_inside_t0_after_the_pretransaction_observation() { + let fixture = Fixture::new(); + let (store, _, proof, binding) = fixture.create().await; + let captured = request(&binding, 9, "fenced", "one"); + let mut database = fixture.database().await; + let original: Vec<u8> = sqlx::query_scalar("SELECT protected FROM workspace_grant") + .fetch_one(&mut database) + .await + .unwrap(); + let (arrived, resume) = fixture.clock.arm(0); + let owner = store.clone(); + let secret = copy(&proof); + let task = tokio::spawn(async move { owner.admit_command_and_hold(captured, secret).await }); + reached(arrived).await; + sqlx::query("UPDATE workspace_grant SET protected=?") + .bind([0; 8].as_slice()) + .execute(&mut database) + .await + .unwrap(); + resume.send(()).unwrap(); + assert!(matches!( + task.await.unwrap(), + Err(OperationError::RecoveryRequired) + )); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM operations") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(count, 0); + let retained: Vec<u8> = sqlx::query_scalar("SELECT protected FROM workspace_grant") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(retained, [0; 8]); + sqlx::query("UPDATE workspace_grant SET protected=?") + .bind(original) + .execute(&mut database) + .await + .unwrap(); + database.close().await.unwrap(); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn unqualified_history_and_approval_descriptors_never_become_admitted_commands() { + let fixture = Fixture::new(); + let (store, _, proof, binding) = fixture.create().await; + let base = request(&binding, 10, "untrusted selectors", "one"); + let wire: serde_json::Value = serde_json::from_slice(base.command().protected_wire()).unwrap(); + let mut reply = wire.clone(); + reply["type"] = json!("inbox.reply"); + reply["input"].as_object_mut().unwrap().remove("source"); + reply["input"]["parent"] = json!("11".repeat(32)); + let captured = AdmissionRequest::from_protected_wire( + binding.clone(), + &serde_json::to_vec(&reply).unwrap(), + ) + .unwrap(); + assert!(matches!( + store.admit_command_and_hold(captured, copy(&proof)).await, + Err(OperationError::MissingHistory) + )); + let mut approval = wire.clone(); + approval["context"]["approval"] = + json!({"intent_digest": "22".repeat(32), "scope": "caller-supplied", "expires_at": "150"}); + let captured = AdmissionRequest::from_protected_wire( + binding.clone(), + &serde_json::to_vec(&approval).unwrap(), + ) + .unwrap(); + assert!(matches!( + store.admit_command_and_hold(captured, copy(&proof)).await, + Err(OperationError::UnverifiedApproval) + )); + let other = WorkspaceBinding::from_authenticated_host( + binding.input().clone(), + binding.actor(), + "substituted-device", + binding.grant_revision(), + binding.expires_at(), + binding.observed_at(), + ) + .unwrap(); + assert!(matches!( + store + .admit_command_and_hold(request(&other, 10, "private", "one"), copy(&proof)) + .await, + Err(OperationError::Unauthorized) + )); + for (actor, revision, expiry) in [ + ( + radroots_domain::ActorRef::new( + binding.actor().participant(), + radroots_domain::ActorRole::Seller, + None, + binding.actor().grant_id(), + ), + binding.grant_revision(), + binding.expires_at(), + ), + ( + binding.actor(), + radroots_domain::Sequence::new(2).unwrap(), + binding.expires_at(), + ), + ( + binding.actor(), + binding.grant_revision(), + UnixSeconds::new(201).unwrap(), + ), + ] { + let substituted = WorkspaceBinding::from_authenticated_host( + binding.input().clone(), + actor, + binding.principal_id(), + revision, + expiry, + binding.observed_at(), + ) + .unwrap(); + assert!(matches!( + store + .admit_command_and_hold(request(&substituted, 10, "private", "one"), copy(&proof)) + .await, + Err(OperationError::Unauthorized) + )); + } + let mut expected = wire.clone(); + expected["context"]["expected"] = json!({"order_id": "33".repeat(32), "agreement": null, + "seller_sequence": "0", "buyer_head": null, "checkpoint": binding.input().checkpoint()}); + let captured = AdmissionRequest::from_protected_wire( + binding.clone(), + &serde_json::to_vec(&expected).unwrap(), + ) + .unwrap(); + assert!(matches!( + store.admit_command_and_hold(captured, copy(&proof)).await, + Err(OperationError::MissingHistory) + )); + let mut beyond_grant = wire; + beyond_grant["context"]["not_after"] = json!("201"); + let captured = AdmissionRequest::from_protected_wire( + binding.clone(), + &serde_json::to_vec(&beyond_grant).unwrap(), + ) + .unwrap(); + assert!(matches!( + store.admit_command_and_hold(captured, copy(&proof)).await, + Err(OperationError::DeadlineExceeded) + )); + let mut database = fixture.database().await; + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM operations") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(count, 0); + database.close().await.unwrap(); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn retained_ciphertext_is_bound_to_the_original_operation_and_never_repaired_by_query() { + let fixture = Fixture::new(); + let (store, _, proof, binding) = fixture.create().await; + committed( + store + .admit_command_and_hold( + request(&binding, 11, "first private command", "one"), + copy(&proof), + ) + .await + .unwrap(), + ); + committed( + store + .admit_command_and_hold( + request(&binding, 12, "second private command", "two"), + copy(&proof), + ) + .await + .unwrap(), + ); + let mut database = fixture.database().await; + let protected: Vec<u8> = + sqlx::query_scalar("SELECT protected FROM operations WHERE operation_id=?") + .bind([11; 32].as_slice()) + .fetch_one(&mut database) + .await + .unwrap(); + sqlx::query("UPDATE operations SET protected=? WHERE operation_id=?") + .bind(&protected) + .bind([12; 32].as_slice()) + .execute(&mut database) + .await + .unwrap(); + assert!(matches!( + store + .operation( + binding, + OperationId::from_bytes([12; 32]), + None, + copy(&proof) + ) + .await, + Err(OperationError::Workspace(WorkspaceError::RecoveryRequired)) + )); + let unchanged: Vec<u8> = + sqlx::query_scalar("SELECT protected FROM operations WHERE operation_id=?") + .bind([12; 32].as_slice()) + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(unchanged, protected); + database.close().await.unwrap(); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn predecessor_grant_only_schema_is_preserved_for_explicit_cutover() { + let fixture = Fixture::new(); + let (store, input, _, _) = fixture.create().await; + store.close().await.unwrap(); + let mut database = fixture.database().await; + sqlx::raw_sql( + "DROP INDEX operation_transaction_identity; DROP TABLE operations; PRAGMA user_version=1", + ) + .execute(&mut database) + .await + .unwrap(); + database.close().await.unwrap(); + let path = fixture.path.join("execution_v1.sqlite"); + let before = std::fs::read(&path).unwrap(); + assert!(matches!( + NativeWorkspace::open_existing( + &fixture.path, + input, + fixture.crypto(), + fixture.clock.clone() + ) + .await, + Err(WorkspaceError::RecoveryRequired) + )); + assert_eq!(std::fs::read(path).unwrap(), before); +} + +#[tokio::test] +async fn bounded_admission_queue_refuses_overflow_and_drains_every_accepted_request() { + let fixture = Fixture::new(); + let (store, _, proof, binding) = fixture.create().await; + let (arrived, resume) = fixture.clock.arm(1); + let owner = store.clone(); + let first = request(&binding, 64, "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(); + for id in 1..=32 { + let mut future = + store.admit_command_and_hold(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(request(&binding, 33, "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 { + committed(future.await.unwrap()); + } + let mut database = fixture.database().await; + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM operations") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(count, 33); + database.close().await.unwrap(); + assert!(matches!( + store + .admit_command_and_hold(request(&binding, 65, "closed", "one"), copy(&proof)) + .await, + Err(OperationError::Workspace(WorkspaceError::Closed)) + )); +} diff --git a/tools/xtask/src/architecture/dependency_boundary.rs b/tools/xtask/src/architecture/dependency_boundary.rs @@ -578,6 +578,8 @@ mod tests { include_str!("../../tests/fixtures/dependency-boundaries/service-to-sdk.json"); const VALID_DOWNWARD: &str = include_str!("../../tests/fixtures/dependency-boundaries/valid-downward.json"); + const PROTOCOL_TO_DOMAIN: &str = + include_str!("../../tests/fixtures/dependency-boundaries/protocol-to-domain.json"); #[derive(Deserialize)] struct ArchitectureCatalog { @@ -612,6 +614,33 @@ mod tests { } #[test] + fn approved_passive_protocol_domain_edge_matches_current_placement() { + let policy = policy(); + validate_metadata(&policy, &placements(&policy), &metadata(PROTOCOL_TO_DOMAIN)) + .expect("approved protocol data edge must use canonical domain values"); + } + + #[test] + fn protocol_data_placement_does_not_allow_storage() { + let policy = policy(); + let changed = PROTOCOL_TO_DOMAIN.replace("radroots_domain", "radroots_storage"); + let error = validate_metadata(&policy, &placements(&policy), &metadata(&changed)) + .expect_err("passive protocol cannot import storage"); + assert!(error.contains("radroots_protocol (tier=domain rank=1)")); + assert!(error.contains("radroots_storage (tier=spi rank=2)")); + } + + #[test] + fn foundation_identity_does_not_gain_an_upward_domain_edge() { + let policy = policy(); + let changed = PROTOCOL_TO_DOMAIN.replace("radroots_protocol", "radroots_identity"); + let error = validate_metadata(&policy, &placements(&policy), &metadata(&changed)) + .expect_err("identity remains below domain"); + assert!(error.contains("radroots_identity (tier=foundation rank=0)")); + assert!(error.contains("radroots_domain (tier=domain rank=1)")); + } + + #[test] fn domain_to_storage_reports_resolved_alias_kind_target_and_features() { let policy = policy(); let error = validate_metadata(&policy, &placements(&policy), &metadata(DOMAIN_TO_STORAGE)) diff --git a/tools/xtask/tests/fixtures/dependency-boundaries/protocol-to-domain.json b/tools/xtask/tests/fixtures/dependency-boundaries/protocol-to-domain.json @@ -0,0 +1,40 @@ +{ + "packages": [ + { + "id": "path+file:///workspace/crates/protocol#radroots_protocol@0.1.0-alpha", + "name": "radroots_protocol", + "dependencies": [ + { + "name": "radroots_domain", + "kind": null, + "features": ["serde"], + "target": null, + "uses_default_features": false + } + ] + }, + { + "id": "path+file:///workspace/crates/domain#radroots_domain@0.1.0-alpha", + "name": "radroots_domain", + "dependencies": [] + } + ], + "resolve": { + "nodes": [ + { + "id": "path+file:///workspace/crates/protocol#radroots_protocol@0.1.0-alpha", + "deps": [ + { + "name": "radroots_domain", + "pkg": "path+file:///workspace/crates/domain#radroots_domain@0.1.0-alpha", + "dep_kinds": [{"kind": null, "target": null}] + } + ] + }, + { + "id": "path+file:///workspace/crates/domain#radroots_domain@0.1.0-alpha", + "deps": [] + } + ] + } +}