commit c79337d8851ee6da0b18aa7d7e97bc5b83d537ce parent dd493e1502e17a5725c03736d9d826456e6d0c79 Author: triesap <tyson@radroots.org> Date: Sun, 25 Oct 2026 05:10:24 +0000 storage: issue exact native stock command consent - Retain existing catalogs with protected multipart operations. - Bind administrative consent to exact commands, grants and resources. - Prove original identities across physical and consent history. - Verify replay, atomic failures, cancellation and provider races. Diffstat:
27 files changed, 3618 insertions(+), 148 deletions(-)
diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -2419,6 +2419,7 @@ pub fn radroots_storage::workspace::seller_stock::StockGrantRecord::encode(&self pub fn radroots_storage::workspace::seller_stock::StockGrantRecord::expires_at(&self) -> radroots_domain::context::UnixSeconds pub fn radroots_storage::workspace::seller_stock::StockGrantRecord::from_enrollment(radroots_storage::workspace::grant::WorkspaceGrant) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> pub fn radroots_storage::workspace::seller_stock::StockGrantRecord::input(&self) -> &radroots_storage::workspace::AttachmentInput +pub fn radroots_storage::workspace::seller_stock::StockGrantRecord::is_revoked(&self) -> bool pub fn radroots_storage::workspace::seller_stock::StockGrantRecord::new(radroots_storage::workspace::AttachmentInput, alloc::string::String, radroots_domain::context::UnixSeconds, radroots_storage::workspace::seller_stock::StockGrantScope, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> pub fn radroots_storage::workspace::seller_stock::StockGrantRecord::permissions(&self) -> &radroots_storage::workspace::seller_stock::StockGrantScope pub fn radroots_storage::workspace::seller_stock::StockGrantRecord::revoke(&mut self) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -368,6 +368,16 @@ pub use radroots_storage_sqlite::workspace::WorkspaceBinding pub use radroots_storage_sqlite::workspace::WorkspaceClock pub use radroots_storage_sqlite::workspace::WorkspaceError pub use radroots_storage_sqlite::workspace::WorkspaceScope +pub enum radroots_storage_sqlite::workspace::StockConsentMode +pub radroots_storage_sqlite::workspace::StockConsentMode::ExecuteAndRecover +pub radroots_storage_sqlite::workspace::StockConsentMode::RecoverOnly +pub enum radroots_storage_sqlite::workspace::StockConsentOutcome +pub radroots_storage_sqlite::workspace::StockConsentOutcome::Committed(alloc::boxed::Box<radroots_storage_sqlite::workspace::StockConsentReceipt>) +pub radroots_storage_sqlite::workspace::StockConsentOutcome::Unknown +pub radroots_storage_sqlite::workspace::StockConsentOutcome::Unknown::command_operation: radroots_domain::identifier::OperationId +pub radroots_storage_sqlite::workspace::StockConsentOutcome::Unknown::control_operation: radroots_domain::identifier::OperationId +pub radroots_storage_sqlite::workspace::StockConsentOutcome::Unknown::subject: radroots_domain::identifier::GrantId +pub radroots_storage_sqlite::workspace::StockConsentOutcome::Unknown::transaction: radroots_domain::identifier::TransactionId pub enum radroots_storage_sqlite::workspace::StockGrantOutcome pub radroots_storage_sqlite::workspace::StockGrantOutcome::Committed(radroots_storage_sqlite::workspace::StockGrantReceipt) pub radroots_storage_sqlite::workspace::StockGrantOutcome::Unknown(radroots_domain::identifier::TransactionId) @@ -395,6 +405,9 @@ pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::initialize_sel pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::open_seller_stock(&std::path::Path, radroots_storage::workspace::AttachmentInput, radroots_storage_sqlite::workspace::WorkspaceCrypto, alloc::sync::Arc<dyn radroots_storage::workspace::WorkspaceClock>) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_authority(&self, radroots_storage::workspace::AttachmentInput, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::StockAuthorityReceipt, radroots_storage::workspace::WorkspaceError> impl radroots_storage_sqlite::workspace::NativeWorkspace +pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::issue_stock_consent(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, &radroots_storage_sqlite::workspace::StockConsentCapture, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::StockConsentOutcome, radroots_storage::command::OperationError> +pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_consent(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::GrantId, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage_sqlite::workspace::StockConsentReceipt>, radroots_storage::command::OperationError> +impl radroots_storage_sqlite::workspace::NativeWorkspace pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::retain_stock_source(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::seller_stock::source::StockSourceCheckpointRef, &radroots_storage_sqlite::workspace::StockSourceCapture, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::StockSourceOutcome, radroots_storage::command::OperationError> pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_source(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::seller_stock::source::StockSourceCheckpointRef, radroots_domain::identifier::EnvelopeEventId, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage_sqlite::workspace::StockSourceSnapshot>, radroots_storage::command::OperationError> impl core::fmt::Debug for radroots_storage_sqlite::workspace::NativeWorkspace @@ -430,6 +443,30 @@ pub const fn radroots_storage_sqlite::workspace::StockAuthorityReceipt::inventor pub const fn radroots_storage_sqlite::workspace::StockAuthorityReceipt::revocation_generation(&self) -> radroots_domain::context::Sequence pub const fn radroots_storage_sqlite::workspace::StockAuthorityReceipt::source_checkpoint(&self) -> core::option::Option<radroots_storage::workspace::seller_stock::source::StockSourceCheckpointRef> pub const fn radroots_storage_sqlite::workspace::StockAuthorityReceipt::transaction_id(&self) -> radroots_domain::identifier::TransactionId +pub struct radroots_storage_sqlite::workspace::StockConsentCapture +impl radroots_storage_sqlite::workspace::StockConsentCapture +pub fn radroots_storage_sqlite::workspace::StockConsentCapture::command(&self) -> &radroots_protocol::command::order_acceptance::CapturedOrderAcceptance +pub const fn radroots_storage_sqlite::workspace::StockConsentCapture::control_operation_id(&self) -> radroots_domain::identifier::OperationId +pub const fn radroots_storage_sqlite::workspace::StockConsentCapture::expires_at(&self) -> radroots_domain::context::UnixSeconds +pub const fn radroots_storage_sqlite::workspace::StockConsentCapture::mode(&self) -> radroots_storage_sqlite::workspace::StockConsentMode +pub fn radroots_storage_sqlite::workspace::StockConsentCapture::prepare(radroots_storage::workspace::seller_stock::selection::SellerAuthoritySelection, radroots_domain::identifier::GrantId, radroots_storage_sqlite::workspace::StockConsentMode, radroots_storage::workspace::seller_stock::permissions::StockResources, radroots_domain::context::UnixSeconds, radroots_protocol::command::order_acceptance::CapturedOrderAcceptance) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub fn radroots_storage_sqlite::workspace::StockConsentCapture::resources(&self) -> &radroots_storage::workspace::seller_stock::permissions::StockResources +pub const fn radroots_storage_sqlite::workspace::StockConsentCapture::subject_grant(&self) -> radroots_domain::identifier::GrantId +pub const fn radroots_storage_sqlite::workspace::StockConsentCapture::transaction_id(&self) -> radroots_domain::identifier::TransactionId +impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockConsentCapture +pub fn radroots_storage_sqlite::workspace::StockConsentCapture::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_sqlite::workspace::StockConsentReceipt +impl radroots_storage_sqlite::workspace::StockConsentReceipt +pub const fn radroots_storage_sqlite::workspace::StockConsentReceipt::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef +pub const fn radroots_storage_sqlite::workspace::StockConsentReceipt::command_digest(&self) -> radroots_domain::identifier::CommandDigest +pub const fn radroots_storage_sqlite::workspace::StockConsentReceipt::command_operation_id(&self) -> radroots_domain::identifier::OperationId +pub const fn radroots_storage_sqlite::workspace::StockConsentReceipt::control_operation_id(&self) -> radroots_domain::identifier::OperationId +pub const fn radroots_storage_sqlite::workspace::StockConsentReceipt::expires_at(&self) -> radroots_domain::context::UnixSeconds +pub const fn radroots_storage_sqlite::workspace::StockConsentReceipt::mode(&self) -> radroots_storage_sqlite::workspace::StockConsentMode +pub const fn radroots_storage_sqlite::workspace::StockConsentReceipt::order_id(&self) -> radroots_domain::identifier::OrderId +pub fn radroots_storage_sqlite::workspace::StockConsentReceipt::resources(&self) -> &radroots_storage::workspace::seller_stock::permissions::StockResources +pub const fn radroots_storage_sqlite::workspace::StockConsentReceipt::subject_grant(&self) -> radroots_domain::identifier::GrantId +pub const fn radroots_storage_sqlite::workspace::StockConsentReceipt::transaction_id(&self) -> radroots_domain::identifier::TransactionId pub struct radroots_storage_sqlite::workspace::StockEnrollment impl radroots_storage_sqlite::workspace::StockEnrollment pub fn radroots_storage_sqlite::workspace::StockEnrollment::input(&self) -> &radroots_storage::workspace::AttachmentInput diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json @@ -75,7 +75,7 @@ "scope": "seller_stock_owner", "database": "stock_execution_v1.sqlite", "lock": ".stock_execution_v1.lock", - "schema_version": 6, + "schema_version": 7, "retained_enrollment_versions": [ 1 ], @@ -83,10 +83,23 @@ 2, 3, 4, - 5 + 5, + 6 ], - "authority_payload_schema": "radroots.seller_stock.authority.v6", - "inventory_operation_payload_schema": "radroots.seller_stock.operation.v4", + "authority_payload_schema": "radroots.seller_stock.authority.v7", + "inventory_operation_payload_schema": "radroots.seller_stock.operation.v5", + "operation_part_payload_schema": "radroots.seller_stock.operation_part.v1", + "operation_body_max_bytes": 262144, + "operation_part_max_bytes": 16384, + "operation_part_max_count": 16, + "operation_identity_requires_protected_ancestry": true, + "business_consent_payload_version": 1, + "business_consent_action": "orders.accept", + "business_consent_modes": ["execute_and_recover", "recover_only"], + "business_consent_admin_issuance_required": true, + "business_consent_binds_exact_command_and_subject_grant": true, + "business_consent_issuance_has_order_or_stock_effects": false, + "business_consent_worker_charge_bytes": 524288, "mapping_payload_schema": "radroots.seller_stock.mapping.v1", "mapping_owner_administration_required": true, "mapping_changes_physical_stock": false, diff --git a/crates/storage/src/workspace/grant.rs b/crates/storage/src/workspace/grant.rs @@ -39,6 +39,9 @@ impl Drop for WorkspaceGrant { } } impl WorkspaceGrant { + pub(super) const fn is_revoked(&self) -> bool { + self.wire.revoked + } pub(super) fn expires_at(&self) -> UnixSeconds { self.wire.expires_at } diff --git a/crates/storage/src/workspace/seller_stock/authorization.rs b/crates/storage/src/workspace/seller_stock/authorization.rs @@ -160,6 +160,11 @@ impl StockGrantRecord { pub fn expires_at(&self) -> UnixSeconds { self.credential.expires_at() } + /// Returns the decoded revocation claim. Current protected provenance and + /// grant-set membership must be authenticated by the concrete owner. + pub fn is_revoked(&self) -> bool { + self.credential.is_revoked() + } pub fn permissions(&self) -> &StockGrantScope { &self.permissions } diff --git a/crates/storage_sqlite/src/workspace/crypto.rs b/crates/storage_sqlite/src/workspace/crypto.rs @@ -709,7 +709,7 @@ fn stock_root_context( input: &super::AttachmentInput, version: i64, ) -> Result<EnvelopeContext, WorkspaceError> { - if matches!(version, 4..=6) { + if matches!(version, 4..=7) { use sha2::{Digest, Sha256}; let namespace = radroots_storage::workspace::seller_stock::SellerAuthoritySelection::from_attachment( @@ -726,8 +726,10 @@ fn stock_root_context( b"radroots.seller_stock.authority_context.v4\0" } else if version == 5 { b"radroots.seller_stock.authority_context.v5\0" - } else { + } else if version == 6 { b"radroots.seller_stock.authority_context.v6\0" + } else { + b"radroots.seller_stock.authority_context.v7\0" }); hash.update(wire.as_slice()); let subject = radroots_domain::CommandDigest::from_bytes(hash.finalize().into()); @@ -740,8 +742,10 @@ fn stock_root_context( "radroots.seller_stock.authority.v4" } else if version == 5 { "radroots.seller_stock.authority.v5" - } else { + } else if version == 6 { "radroots.seller_stock.authority.v6" + } else { + "radroots.seller_stock.authority.v7" }) .map_err(|_| WorkspaceError::InvalidInput)?, )); @@ -778,6 +782,10 @@ fn stock_record_context( "radroots.seller_stock.source_record", "radroots.seller_stock.source_record.v1", ), + "operation_part" => ( + "radroots.seller_stock.operation_part", + "radroots.seller_stock.operation_part.v1", + ), "source_evidence" => ( "radroots.seller_stock.source_evidence", "radroots.seller_stock.source_evidence.v1", @@ -827,11 +835,12 @@ fn stock_record_context_for_catalog( ) -> Result<EnvelopeContext, WorkspaceError> { let original = stock_record_context(input, kind, id)?; let schema = match (catalog, kind) { - (2, _) | (3..=6, "pool") => return Ok(original), + (2, _) | (3..=7, "pool") => return Ok(original), (3, "operation") => "radroots.seller_stock.operation.v2", (4, "operation") => "radroots.seller_stock.operation.v3", (5 | 6, "operation") => "radroots.seller_stock.operation.v4", - (3..=6, "movement") => "radroots.seller_stock.movement.v2", + (7, "operation") => "radroots.seller_stock.operation.v5", + (3..=7, "movement") => "radroots.seller_stock.movement.v2", _ => return Err(WorkspaceError::RecoveryRequired), }; Ok(EnvelopeContext::new( diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs @@ -23,7 +23,8 @@ mod schema; mod snapshot; mod stock; pub use stock::{ - SellerStockConfig, StockAuthorityReceipt, StockEnrollment, StockGrantEnrollment, + SellerStockConfig, StockAuthorityReceipt, StockConsentCapture, StockConsentMode, + StockConsentOutcome, StockConsentReceipt, StockEnrollment, StockGrantEnrollment, StockGrantOutcome, StockGrantReceipt, StockSourceCapture, StockSourceOutcome, StockSourceProfile, StockSourceReceipt, StockSourceSnapshot, }; diff --git a/crates/storage_sqlite/src/workspace/stock.rs b/crates/storage_sqlite/src/workspace/stock.rs @@ -8,7 +8,12 @@ pub use radroots_storage::workspace::seller_stock::SellerStockConfig; use radroots_storage::workspace::seller_stock::{ SellerAuthoritySelection, StockAction, StockAuthorizationRef, StockGrantRecord, StockGrantScope, }; +pub(in crate::workspace) mod consent; +pub use consent::{ + StockConsentCapture, StockConsentMode, StockConsentOutcome, StockConsentReceipt, +}; pub(in crate::workspace) mod grants; +mod ledger; pub(in crate::workspace) mod source; use grants::StockRecord; pub use grants::{StockGrantEnrollment, StockGrantOutcome, StockGrantReceipt}; @@ -191,6 +196,7 @@ struct InventoryCheckpoint { movements: Sequence, head: Option<radroots_domain::CheckpointDigest>, mappings: Option<Sequence>, + orders: Option<Sequence>, } #[derive(Clone, Copy, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -202,6 +208,17 @@ struct InventoryCheckpointCurrent { #[serde(deserialize_with = "required_nullable")] head: Option<radroots_domain::CheckpointDigest>, } +#[derive(Clone, Copy, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct InventoryCheckpointUnified { + revision: Sequence, + pools: Sequence, + movements: Sequence, + mappings: Sequence, + orders: Sequence, + #[serde(deserialize_with = "required_nullable")] + head: Option<radroots_domain::CheckpointDigest>, +} impl From<InventoryCheckpointLegacy> for InventoryCheckpoint { fn from(value: InventoryCheckpointLegacy) -> Self { Self { @@ -210,6 +227,7 @@ impl From<InventoryCheckpointLegacy> for InventoryCheckpoint { movements: value.movements, head: value.head, mappings: None, + orders: None, } } } @@ -221,6 +239,19 @@ impl From<InventoryCheckpointCurrent> for InventoryCheckpoint { movements: value.movements, head: value.head, mappings: Some(value.mappings), + orders: None, + } + } +} +impl From<InventoryCheckpointUnified> for InventoryCheckpoint { + fn from(value: InventoryCheckpointUnified) -> Self { + Self { + revision: value.revision, + pools: value.pools, + movements: value.movements, + head: value.head, + mappings: Some(value.mappings), + orders: Some(value.orders), } } } @@ -245,6 +276,16 @@ impl InventoryCheckpoint { mappings: self.mappings.ok_or(WorkspaceError::RecoveryRequired)?, }) } + fn unified(self) -> Result<InventoryCheckpointUnified, WorkspaceError> { + Ok(InventoryCheckpointUnified { + revision: self.revision, + pools: self.pools, + movements: self.movements, + head: self.head, + mappings: self.mappings.ok_or(WorkspaceError::RecoveryRequired)?, + orders: self.orders.ok_or(WorkspaceError::RecoveryRequired)?, + }) + } } fn required_nullable<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>( d: D, @@ -305,8 +346,45 @@ struct AuthorityV6 { sources: SourceCheckpoint, authorization: StockAuthorizationRef, } +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct AuthorityV7 { + version: u8, + #[serde(deserialize_with = "object")] + namespace: SellerAuthoritySelection, + administrator: GrantId, + transaction: TransactionId, + revocation: Sequence, + #[serde(deserialize_with = "object")] + inventory: InventoryCheckpointUnified, + #[serde(deserialize_with = "object")] + sources: SourceCheckpoint, + authorization: StockAuthorizationRef, +} impl Authority { fn encode(&self) -> Result<zeroize::Zeroizing<Vec<u8>>, WorkspaceError> { + if self.catalog == 7 { + let bytes = zeroize::Zeroizing::new( + serde_json::to_vec(&AuthorityV7 { + version: 7, + namespace: SellerAuthoritySelection::from_attachment(&self.input), + administrator: self.input.grant_id(), + transaction: self.transaction, + revocation: self.revocation, + inventory: self + .inventory + .ok_or(WorkspaceError::RecoveryRequired)? + .unified()?, + sources: self.sources.ok_or(WorkspaceError::RecoveryRequired)?, + authorization: self.authorization.ok_or(WorkspaceError::RecoveryRequired)?, + }) + .map_err(|_| WorkspaceError::StorageFailure)?, + ); + if bytes.len() > 16 * 1024 { + return Err(WorkspaceError::Capacity); + } + return Ok(bytes); + } if self.catalog == 6 { let bytes = serde_json::to_vec(&AuthorityV6 { version: 6, @@ -476,6 +554,34 @@ impl Authority { sources: Some(value.sources), } } + 7 => { + let value: AuthorityV7 = closed_record(bytes)?; + if value.version != 7 + || value.authorization.generation() != value.revocation + || (value.inventory.revision.get() == 0) != value.inventory.head.is_none() + || value.inventory.orders.get() > value.inventory.revision.get() + || value.inventory.pools.get() > value.inventory.revision.get() + || value.inventory.mappings.get() > value.inventory.revision.get() + || value.inventory.movements.get() + > value.inventory.revision.get().saturating_mul(64) + || (value.sources.revision.get() == 0) != value.sources.head.is_none() + || (value.sources.revision.get() == 0) != (value.sources.parts.get() == 0) + || value.sources.records.get() > value.sources.revision.get() + || value.sources.parts.get() / 3 < value.sources.revision.get() + || value.sources.parts.get() > value.sources.revision.get().saturating_mul(12) + { + return Err(WorkspaceError::RecoveryRequired); + } + Self { + catalog, + input: value.namespace.attachment(value.administrator)?, + transaction: value.transaction, + revocation: value.revocation, + inventory: Some(value.inventory.into()), + authorization: Some(value.authorization), + sources: Some(value.sources), + } + } _ => return Err(WorkspaceError::RecoveryRequired), }; if value.revocation.get() == 0 { @@ -517,6 +623,11 @@ pub(super) async fn initialize( transaction: initial.transaction, revocation: Sequence::new(1).map_err(|_| WorkspaceError::InvalidInput)?, inventory: Some(InventoryCheckpoint { + orders: if schema::CURRENT == 7 { + Some(Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?) + } else { + None + }, mappings: Some(Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?), revision: Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?, head: None, @@ -564,7 +675,7 @@ pub(super) async fn initialize( .await .map_err(|_| WorkspaceError::StorageFailure)?; } - sqlx::query("PRAGMA user_version=6") + sqlx::query("PRAGMA user_version=7") .execute(&mut *tx) .await .map_err(|_| WorkspaceError::StorageFailure)?; diff --git a/crates/storage_sqlite/src/workspace/stock/consent.rs b/crates/storage_sqlite/src/workspace/stock/consent.rs @@ -0,0 +1,793 @@ +//! Explicit per-operation business scopes. Preparation is untrusted data; +//! only an authenticated administrative transaction can issue these scopes. +#[cfg(test)] +mod tests; +use super::*; +use radroots_domain::{ActorRole, CommandDigest, OperationId, OrderId, UnixSeconds}; +use radroots_protocol::command::CapturedOrderAcceptance; +use radroots_storage::{ + command::OperationError, inventory::InventoryCheckpointRef, + workspace::seller_stock::StockResources, +}; +use sha2::{Digest, Sha256}; +use zeroize::Zeroizing; + +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum StockConsentMode { + /// Explicit consent to this exact acceptance and access to its retained + /// operation. This supplies no signer or publication capability. + ExecuteAndRecover, + /// Access to an existing original operation under the named current grant; + /// it can never admit a missing operation or acquire fresh stock. + RecoverOnly, +} + +/// Prepared before store IO. No constructor verifies consent or issues rights. +pub struct StockConsentCapture { + namespace: SellerAuthoritySelection, + operation: OperationId, + transaction: TransactionId, + subject: GrantId, + mode: StockConsentMode, + resources: StockResources, + expires: UnixSeconds, + command: CapturedOrderAcceptance, + digest: CommandDigest, +} +impl StockConsentCapture { + pub fn prepare( + namespace: SellerAuthoritySelection, + subject: GrantId, + mode: StockConsentMode, + resources: StockResources, + expires: UnixSeconds, + command: CapturedOrderAcceptance, + ) -> Result<Self, OperationError> { + validate_capture(&namespace, subject, mode, expires, &command)?; + let digest = scope_digest( + &namespace, + subject, + mode, + &resources, + expires, + command.digest(), + )?; + let operation = OperationId::from_bytes(super::super::random()?); + if operation == command.context().operation_id() { + return Err(WorkspaceError::Unavailable.into()); + } + Ok(Self { + namespace, + operation, + transaction: TransactionId::from_bytes(super::super::random()?), + subject, + mode, + resources, + expires, + command, + digest, + }) + } + pub const fn control_operation_id(&self) -> OperationId { + self.operation + } + pub const fn transaction_id(&self) -> TransactionId { + self.transaction + } + pub const fn subject_grant(&self) -> GrantId { + self.subject + } + pub const fn mode(&self) -> StockConsentMode { + self.mode + } + pub const fn expires_at(&self) -> UnixSeconds { + self.expires + } + pub fn command(&self) -> &CapturedOrderAcceptance { + &self.command + } + pub fn resources(&self) -> &StockResources { + &self.resources + } + pub(super) fn retained_copy(&self) -> Result<Self, OperationError> { + Ok(Self { + namespace: self.namespace.clone(), + operation: self.operation, + transaction: self.transaction, + subject: self.subject, + mode: self.mode, + resources: self.resources.clone(), + expires: self.expires, + command: CapturedOrderAcceptance::parse(self.command.protected_wire()) + .map_err(|_| OperationError::InvalidCommand)?, + digest: self.digest, + }) + } +} +impl std::fmt::Debug for StockConsentCapture { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("StockConsentCapture(<unissued scope>)") + } +} +fn validate_capture( + namespace: &SellerAuthoritySelection, + subject: GrantId, + mode: StockConsentMode, + expires: UnixSeconds, + command: &CapturedOrderAcceptance, +) -> Result<(), OperationError> { + let context = command.context(); + let approval = context + .approval() + .ok_or(OperationError::UnverifiedApproval)?; + if context.actor().participant() != namespace.participant() + || context.actor().role() != ActorRole::Seller + || context.actor().organization().is_some() + || context.actor().grant_id().is_none() + || context.workspace_id() != namespace.workspace_id() + || context.authority() != namespace.authority() + || context.route_digest() != namespace.route_digest() + || context.expected().is_none() + || expires.get() == 0 + || approval.scope() != "orders.accept" + || approval.intent_digest() != command.approval_intent_digest() + || (mode == StockConsentMode::ExecuteAndRecover + && (context.actor().grant_id() != Some(subject) + || expires > context.not_after() + || expires > approval.expires_at())) + { + return Err(OperationError::InvalidCommand); + } + Ok(()) +} +fn scope_digest( + namespace: &SellerAuthoritySelection, + subject: GrantId, + mode: StockConsentMode, + resources: &StockResources, + expires: UnixSeconds, + command: CommandDigest, +) -> Result<CommandDigest, OperationError> { + #[derive(Serialize)] + struct Scope<'a> { + version: u8, + namespace: &'a SellerAuthoritySelection, + subject: GrantId, + mode: StockConsentMode, + resources: &'a StockResources, + expires: UnixSeconds, + command: CommandDigest, + } + let bytes = Zeroizing::new( + serde_json::to_vec(&Scope { + version: 1, + namespace, + subject, + mode, + resources, + expires, + command, + }) + .map_err(|_| OperationError::InvalidCommand)?, + ); + if bytes.len() > 16 * 1024 { + return Err(WorkspaceError::Capacity.into()); + } + let mut hash = Sha256::new(); + hash.update(b"radroots.seller_stock.consent_scope.v1\0"); + hash.update(bytes.as_slice()); + Ok(CommandDigest::from_bytes(hash.finalize().into())) +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct StockConsentReceipt { + operation: OperationId, + transaction: TransactionId, + subject: GrantId, + command_operation: OperationId, + command_digest: CommandDigest, + order: OrderId, + mode: StockConsentMode, + expires: UnixSeconds, + resources: StockResources, + checkpoint: InventoryCheckpointRef, +} +impl StockConsentReceipt { + /// The exact resource claim at issuance, without current execution authority. + pub fn resources(&self) -> &StockResources { + &self.resources + } + pub const fn control_operation_id(&self) -> OperationId { + self.operation + } + pub const fn transaction_id(&self) -> TransactionId { + self.transaction + } + pub const fn subject_grant(&self) -> GrantId { + self.subject + } + pub const fn command_operation_id(&self) -> OperationId { + self.command_operation + } + pub const fn command_digest(&self) -> CommandDigest { + self.command_digest + } + pub const fn order_id(&self) -> OrderId { + self.order + } + pub const fn mode(&self) -> StockConsentMode { + self.mode + } + pub const fn expires_at(&self) -> UnixSeconds { + self.expires + } + pub const fn checkpoint(&self) -> InventoryCheckpointRef { + self.checkpoint + } +} +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum StockConsentOutcome { + Committed(Box<StockConsentReceipt>), + Unknown { + control_operation: OperationId, + transaction: TransactionId, + command_operation: OperationId, + subject: GrantId, + }, +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Body<'a> { + version: u8, + selection: AttachmentInput, + principal: String, + grant_revision: Sequence, + grant_expires: UnixSeconds, + observed_at: UnixSeconds, + authorization: StockAuthorizationRef, + minimum_revision: Sequence, + #[serde(deserialize_with = "super::required_nullable")] + minimum_head: Option<radroots_domain::CheckpointDigest>, + subject: GrantId, + subject_digest: [u8; 32], + mode: StockConsentMode, + resources: StockResources, + expires: UnixSeconds, + #[serde(borrow)] + command: &'a serde_json::value::RawValue, +} +pub(super) struct Retained { + pub frame: ledger::Retained, + pub command: CapturedOrderAcceptance, + pub mode: StockConsentMode, + pub resources: StockResources, + pub subject: GrantId, + pub expires: UnixSeconds, + pub authorization: StockAuthorizationRef, +} +impl Retained { + fn identity(&self) -> inventory::checkpoint::EntryIdentity { + inventory::checkpoint::EntryIdentity { + operation: self.frame.header.operation, + revision: self.frame.header.revision, + head: self.frame.header.head, + protected_digest: Sha256::digest(&self.frame.protected).into(), + } + } + pub fn receipt(&self) -> Result<StockConsentReceipt, OperationError> { + let header = &self.frame.header; + Ok(StockConsentReceipt { + operation: header.operation, + transaction: header.transaction, + subject: self.subject, + command_operation: self.command.context().operation_id(), + command_digest: self.command.digest(), + order: header.order.ok_or(OperationError::RecoveryRequired)?, + mode: self.mode, + expires: self.expires, + resources: self.resources.clone(), + checkpoint: InventoryCheckpointRef::from_host_metadata( + self.command.context().authority(), + header.revision, + Some(header.head), + )? + .with_authorization(self.authorization), + }) + } +} +fn chain_head( + namespace: &SellerAuthoritySelection, + header: &ledger::Header, + subject_digest: [u8; 32], +) -> Result<radroots_domain::CheckpointDigest, OperationError> { + let mut hash = Sha256::new(); + hash.update(b"radroots.seller_stock.consent_chain.v1\0"); + hash.update(namespace.workspace_id().as_bytes()); + hash.update(namespace.authority().executor_id().as_bytes()); + hash.update(namespace.authority().generation().get().to_be_bytes()); + hash.update(namespace.route_digest().as_bytes()); + hash.update([u8::from(header.previous.is_some())]); + hash.update(header.previous.map(|v| *v.as_bytes()).unwrap_or([0; 32])); + hash.update(header.revision.get().to_be_bytes()); + hash.update(header.actor.participant().as_bytes()); + hash.update( + header + .actor + .grant_id() + .ok_or(OperationError::RecoveryRequired)? + .as_bytes(), + ); + hash.update(header.operation.as_bytes()); + hash.update(header.transaction.as_bytes()); + hash.update(header.digest.as_bytes()); + hash.update(subject_digest); + Ok(radroots_domain::CheckpointDigest::from_bytes( + hash.finalize().into(), + )) +} +pub(super) async fn read( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + administrator: GrantId, + operation: OperationId, +) -> Result<Option<Retained>, OperationError> { + let Some(frame) = ledger::read(connection, input, crypto, operation).await? else { + return Ok(None); + }; + let mut parser = serde_json::Deserializer::from_slice(frame.body.as_slice()); + let body: Body<'_> = + super::object(&mut parser).map_err(|_| OperationError::RecoveryRequired)?; + parser.end().map_err(|_| OperationError::RecoveryRequired)?; + let command = CapturedOrderAcceptance::parse(body.command.get().as_bytes()) + .map_err(|_| OperationError::RecoveryRequired)?; + let namespace = SellerAuthoritySelection::from_attachment(input); + validate_capture(&namespace, body.subject, body.mode, body.expires, &command) + .map_err(|_| OperationError::RecoveryRequired)?; + let header = &frame.header; + if header.family != ledger::Family::Consent + || header.actor.grant_id() != Some(administrator) + || body.version != 1 + || !namespace.matches_attachment(&body.selection) + || body.selection.grant_id() != administrator + || header.subject_grant != Some(body.subject) + || header.related_operation != Some(command.context().operation_id()) + || header.order != command.context().expected().map(|v| v.order_id()) + || body.principal.is_empty() + || body.principal.len() > 128 + || body.principal.chars().any(char::is_control) + || body.grant_revision.get() == 0 + || body.observed_at.get() == 0 + || body.grant_expires <= body.observed_at + || body.expires <= body.observed_at + || body.expires > body.grant_expires + || body.minimum_revision.get() >= header.revision.get() + || (body.minimum_revision.get() == 0) != body.minimum_head.is_none() + || header.digest + != scope_digest( + &namespace, + body.subject, + body.mode, + &body.resources, + body.expires, + command.digest(), + )? + || header.head != chain_head(&namespace, header, body.subject_digest)? + { + return Err(OperationError::RecoveryRequired); + } + let mode = body.mode; + let resources = body.resources; + let subject = body.subject; + let expires = body.expires; + let authorization = body.authorization; + Ok(Some(Retained { + frame, + command, + mode, + resources, + subject, + expires, + authorization, + })) +} + +async fn natural( + connection: &mut SqliteConnection, + participant: radroots_domain::PublicKey, + operation: OperationId, + subject: GrantId, +) -> Result<Option<OperationId>, OperationError> { + let id:Option<Vec<u8>>=sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE actor=? AND family=1 AND related_operation=? AND subject_grant=?") + .bind(participant.as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(subject.as_bytes().as_slice()) + .fetch_optional(connection).await.map_err(|_|OperationError::RecoveryRequired)?; + id.map(|bytes| { + bytes + .try_into() + .map(OperationId::from_bytes) + .map_err(|_| OperationError::RecoveryRequired) + }) + .transpose() +} +pub(in crate::workspace) async fn issue( + turn: &mut inventory::Turn<'_>, + binding: WorkspaceBinding, + minimum: InventoryCheckpointRef, + capture: StockConsentCapture, + proof: AttachmentProof, +) -> Result<StockConsentOutcome, OperationError> { + let access = turn.access(&binding, minimum, &proof).await?; + if access.authority.catalog != 7 { + return Err(OperationError::UnsupportedOperation); + } + if !access.record.administrator() + || capture.namespace != SellerAuthoritySelection::from_attachment(turn.selected) + { + return Err(OperationError::Unauthorized); + } + let command_operation = capture.command.context().operation_id(); + if let Some(operation) = natural( + turn.connection, + turn.selected.participant(), + command_operation, + capture.subject, + ) + .await? + { + let original = read( + turn.connection, + turn.selected, + turn.crypto, + access.authority.input.grant_id(), + operation, + ) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let identity = inventory::checkpoint::authenticate_identity( + turn.connection, + turn.selected, + turn.crypto, + &access.current, + &access.authority, + inventory::checkpoint::IdentityTarget::Consent { + operation: command_operation, + subject: capture.subject, + expected: Some(original.identity()), + }, + ) + .await?; + if original.frame.header.digest != capture.digest { + return Err(OperationError::IdempotencyConflict); + } + let receipt = original.receipt()?; + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let checked: Result<(), OperationError> = async { + access + .confirm(&mut tx, turn.namespace, turn.clock, &proof) + .await?; + identity.confirm(&mut tx).await?; + ledger::confirm_header(&mut tx, &original.frame.header, &original.frame.protected) + .await?; + ledger::confirm_parts( + &mut tx, + original.frame.header.actor, + operation, + original.frame.parts_witness, + original.frame.header.parts, + ) + .await?; + Ok(()) + } + .await; + if tx.rollback().await.is_err() { + *turn.uncertain = true; + return Err(OperationError::RecoveryRequired); + } + checked?; + return Ok(StockConsentOutcome::Committed(Box::new(receipt))); + } + let identity = inventory::checkpoint::authenticate_identity( + turn.connection, + turn.selected, + turn.crypto, + &access.current, + &access.authority, + inventory::checkpoint::IdentityTarget::Consent { + operation: command_operation, + subject: capture.subject, + expected: None, + }, + ) + .await?; + if access.current.observed_at() >= capture.expires + || capture.expires > access.current.expires_at() + { + return Err(OperationError::DeadlineExceeded); + } + let target:Vec<u8>=sqlx::query_scalar("SELECT protected FROM stock_grants WHERE grant_id=? AND length(protected) BETWEEN 1 AND 262144") + .bind(capture.subject.as_bytes().as_slice()).fetch_optional(&mut *turn.connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::Unauthorized)?; + let target_input = capture.namespace.attachment(capture.subject)?; + let clear = turn + .crypto + .open_stock_record(&target_input, "grant", capture.subject.as_bytes(), &target) + .await?; + let target_record = clear.expose_secret(StockGrantRecord::decode)?; + if target_record.input() != &target_input + || !target_record.belongs_to(&capture.namespace)? + || target_record.is_revoked() + || capture.expires > target_record.expires_at() + { + return Err(OperationError::Unauthorized); + } + let subject_digest: [u8; 32] = Sha256::digest(&target).into(); + let before = access + .authority + .inventory + .ok_or(OperationError::RecoveryRequired)?; + let revision = Sequence::new( + before + .revision + .get() + .checked_add(1) + .ok_or(WorkspaceError::Capacity)?, + ) + .map_err(|_| WorkspaceError::Capacity)?; + let authorization = access + .authority + .authorization + .ok_or(OperationError::RecoveryRequired)?; + let command: &serde_json::value::RawValue = + serde_json::from_slice(capture.command.protected_wire()) + .map_err(|_| OperationError::InvalidCommand)?; + let body = Body { + version: 1, + selection: access.current.input().clone(), + principal: access.current.principal_id().into(), + grant_revision: access.current.grant_revision(), + grant_expires: access.current.expires_at(), + observed_at: access.current.observed_at(), + authorization, + minimum_revision: minimum.revision(), + minimum_head: minimum.head(), + subject: capture.subject, + subject_digest, + mode: capture.mode, + resources: capture.resources.clone(), + expires: capture.expires, + command, + }; + let body = + Zeroizing::new(serde_json::to_vec(&body).map_err(|_| OperationError::StorageFailure)?); + let mut header = ledger::Header { + version: 5, + family: ledger::Family::Consent, + namespace: capture.namespace.clone(), + actor: access.current.actor(), + operation: capture.operation, + digest: capture.digest, + transaction: capture.transaction, + revision, + previous: before.head, + head: radroots_domain::CheckpointDigest::from_bytes([0; 32]), + pool: None, + order: capture + .command + .context() + .expected() + .map(|value| value.order_id()), + related_operation: Some(command_operation), + subject_grant: Some(capture.subject), + bytes: 0, + parts: 0, + body_digest: [0; 32], + }; + header.head = chain_head(&capture.namespace, &header, subject_digest)?; + let head = header.head; + let prepared = ledger::prepare(turn.crypto, turn.selected, header, &body).await?; + let mut next = access.authority.clone(); + next.inventory = Some(InventoryCheckpoint { + revision, + head: Some(head), + ..before + }); + let root = turn + .crypto + .seal_stock_root(turn.selected, 7, &next.encode()?) + .await?; + let receipt = StockConsentReceipt { + operation: capture.operation, + transaction: capture.transaction, + subject: capture.subject, + command_operation, + command_digest: capture.command.digest(), + order: capture + .command + .context() + .expected() + .ok_or(OperationError::InvalidCommand)? + .order_id(), + mode: capture.mode, + expires: capture.expires, + resources: capture.resources.clone(), + checkpoint: InventoryCheckpointRef::from_host_metadata( + turn.selected.authority(), + revision, + Some(head), + )? + .with_authorization(authorization), + }; + turn.namespace.validate()?; + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let changed:Result<(),OperationError>=async { + let current=access.confirm(&mut tx,turn.namespace,turn.clock,&proof).await?; + identity.confirm(&mut tx).await?; + if !access.record.administrator() {return Err(OperationError::Unauthorized);} + if current.observed_at()>=capture.expires {return Err(OperationError::DeadlineExceeded);} + let target_matches:i64=sqlx::query_scalar("SELECT count(*) FROM stock_grants WHERE grant_id=? AND protected=?") + .bind(capture.subject.as_bytes().as_slice()).bind(&target).fetch_one(&mut *tx).await.map_err(|_|OperationError::RecoveryRequired)?; + if target_matches!=1 {return Err(OperationError::RecoveryRequired);} + if natural(&mut tx,turn.selected.participant(),command_operation,capture.subject).await?.is_some() {return Err(OperationError::StaleState);} + let absent:i64=sqlx::query_scalar("SELECT count(*) FROM stock_operations WHERE actor=? AND operation_id=?") + .bind(current.actor().participant().as_bytes().as_slice()).bind(capture.operation.as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_|OperationError::RecoveryRequired)?; + if absent!=0 {return Err(OperationError::IdempotencyConflict);} + sqlx::query("INSERT INTO stock_operations(actor,grant_id,operation_id,command_digest,transaction_id,pool_id,revision,chain_head,protected,family,order_id,related_operation,subject_grant) VALUES(?,?,?,?,?,NULL,?,?,?,1,?,?,?)") + .bind(current.actor().participant().as_bytes().as_slice()).bind(current.input().grant_id().as_bytes().as_slice()) + .bind(capture.operation.as_bytes().as_slice()).bind(capture.digest.as_bytes().as_slice()).bind(capture.transaction.as_bytes().as_slice()) + .bind(revision.get() as i64).bind(head.as_bytes().as_slice()).bind(&prepared.protected) + .bind(receipt.order.as_bytes().as_slice()).bind(command_operation.as_bytes().as_slice()).bind(capture.subject.as_bytes().as_slice()) + .execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + prepared.insert_parts(&mut tx,current.actor(),capture.operation).await?; + let updated=sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?") + .bind(root).bind(&access.root).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + if updated.rows_affected()!=1 {return Err(OperationError::RecoveryRequired);}turn.namespace.validate()?;Ok(()) + }.await; + let unknown = || StockConsentOutcome::Unknown { + control_operation: capture.operation, + transaction: capture.transaction, + command_operation, + subject: capture.subject, + }; + if let Err(error) = changed { + if tx.rollback().await.is_err() { + *turn.uncertain = true; + return Ok(unknown()); + } + return Err(error); + } + if tx.commit().await.is_err() { + *turn.uncertain = true; + return Ok(unknown()); + } + Ok(StockConsentOutcome::Committed(Box::new(receipt))) +} + +pub(in crate::workspace) async fn query( + turn: &mut inventory::Turn<'_>, + binding: WorkspaceBinding, + minimum: InventoryCheckpointRef, + command_operation: OperationId, + subject: GrantId, + proof: AttachmentProof, +) -> Result<Option<StockConsentReceipt>, OperationError> { + let access = turn.access(&binding, minimum, &proof).await?; + if access.authority.catalog != 7 { + return Err(OperationError::UnsupportedOperation); + } + if !access.record.administrator() && access.current.input().grant_id() != subject { + return Err(OperationError::Unauthorized); + } + let original = if let Some(operation) = natural( + turn.connection, + turn.selected.participant(), + command_operation, + subject, + ) + .await? + { + Some( + read( + turn.connection, + turn.selected, + turn.crypto, + access.authority.input.grant_id(), + operation, + ) + .await? + .ok_or(OperationError::RecoveryRequired)?, + ) + } else { + None + }; + let identity = inventory::checkpoint::authenticate_identity( + turn.connection, + turn.selected, + turn.crypto, + &access.current, + &access.authority, + inventory::checkpoint::IdentityTarget::Consent { + operation: command_operation, + subject, + expected: original.as_ref().map(Retained::identity), + }, + ) + .await?; + let receipt = original.as_ref().map(Retained::receipt).transpose()?; + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let checked: Result<(), OperationError> = async { + access + .confirm(&mut tx, turn.namespace, turn.clock, &proof) + .await?; + identity.confirm(&mut tx).await?; + if let Some(original) = &original { + ledger::confirm_header(&mut tx, &original.frame.header, &original.frame.protected) + .await?; + ledger::confirm_parts( + &mut tx, + original.frame.header.actor, + original.frame.header.operation, + original.frame.parts_witness, + original.frame.header.parts, + ) + .await?; + } + turn.namespace.validate()?; + Ok(()) + } + .await; + if tx.rollback().await.is_err() { + *turn.uncertain = true; + return Err(OperationError::RecoveryRequired); + } + checked?; + Ok(receipt) +} + +impl NativeWorkspace { + /// Issues an explicit scope for one captured business command, using the + /// current administrative grant. The borrowed capture preserves its original + /// recovery identity if this observer is lost. Issuance performs no order, + /// stock, signing or publication effect. + pub async fn issue_stock_consent( + &self, + binding: WorkspaceBinding, + minimum: InventoryCheckpointRef, + capture: &StockConsentCapture, + proof: &AttachmentProof, + ) -> Result<StockConsentOutcome, OperationError> { + let proof = proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?; + self.worker + .issue_stock_consent(binding, minimum, capture.retained_copy()?, proof) + .await + } + + /// Reads a retained issuance under current administrator or subject access. + /// A receipt describes its original issuance; it does not establish that its + /// expiry, target grant or business preconditions still permit execution. + pub async fn stock_consent( + &self, + binding: WorkspaceBinding, + minimum: InventoryCheckpointRef, + command_operation: OperationId, + subject: GrantId, + proof: &AttachmentProof, + ) -> Result<Option<StockConsentReceipt>, OperationError> { + let proof = proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?; + self.worker + .stock_consent(binding, minimum, command_operation, subject, proof) + .await + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/consent/test_provider.rs b/crates/storage_sqlite/src/workspace/stock/consent/test_provider.rs @@ -0,0 +1,217 @@ +use super::*; +use radroots_secrets::{ + Error, + file::FileProvider, + id::BackendKind, + provider::{SecretCapabilities, SecretProvider}, + wrapping::{KeyWrapping, SecretMaterial, UnwrapRequest, WrapRequest, WrappedSecret}, +}; +use radroots_transport::BoxFuture; +use std::sync::{Condvar, Mutex}; +use std::time::Duration; + +struct Gate { + state: Mutex<(bool, bool, bool)>, + changed: Condvar, +} +impl Gate { + fn new() -> Self { + Self { + state: Mutex::new((false, false, false)), + changed: Condvar::new(), + } + } + fn arm(&self) { + *self.state.lock().unwrap() = (true, false, false); + } + fn pause(&self) { + let mut state = self.state.lock().unwrap(); + if !state.0 { + return; + } + state.0 = false; + state.1 = true; + self.changed.notify_all(); + let (state, timeout) = self + .changed + .wait_timeout_while(state, Duration::from_secs(20), |s| !s.2) + .unwrap(); + assert!( + !timeout.timed_out() && state.2, + "test must release provider" + ); + } + fn entered(&self) { + let (state, timeout) = self + .changed + .wait_timeout_while(self.state.lock().unwrap(), Duration::from_secs(20), |s| { + !s.1 + }) + .unwrap(); + assert!( + !timeout.timed_out() && state.1, + "worker must enter actual provider IO" + ); + } + fn release(&self) { + self.state.lock().unwrap().2 = true; + self.changed.notify_all(); + } +} +struct Provider { + inner: Arc<FileProvider>, + gate: Gate, +} +impl SecretProvider for Provider { + fn backend_kind(&self) -> BackendKind { + self.inner.backend_kind() + } + fn capabilities(&self) -> SecretCapabilities { + self.inner.capabilities() + } +} +impl KeyWrapping for Provider { + fn wrap<'a>(&'a self, request: WrapRequest<'a>) -> BoxFuture<'a, Result<WrappedSecret, Error>> { + Box::pin(async move { + let result = self.inner.wrap(request).await; + if request.context().payload_schema().as_str() == "radroots.seller_stock.authority.v7" { + self.gate.pause(); + } + result + }) + } + fn unwrap<'a>( + &'a self, + request: UnwrapRequest<'a>, + ) -> BoxFuture<'a, Result<SecretMaterial, Error>> { + self.inner.unwrap(request) + } +} +async fn reopen(r: &mut Rig) -> Arc<Provider> { + r.store.close().await.unwrap(); + let provider = Arc::new(Provider { + inner: r.fixture.provider.clone(), + gate: Gate::new(), + }); + r.store = NativeWorkspace::open_seller_stock( + &r.path, + r.input.clone(), + r.fixture.crypto_with_provider(provider.clone()), + r.clock.clone(), + ) + .await + .unwrap(); + provider +} + +#[tokio::test] +async fn current_time_and_target_are_rechecked_after_actual_provider_io() { + for changed_target in [false, true] { + let mut r = Rig::new().await; + let provider = reopen(&mut r).await; + let capture = r.capture(&r.binding, 0x31); + let mut raw = SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .filename(r.path.join("stock_execution_v1.sqlite")), + ) + .await + .unwrap(); + provider.gate.arm(); + let mut future = + Box::pin( + r.store + .issue_stock_consent(r.binding.clone(), r.minimum, &capture, &r.proof), + ); + assert!(futures::poll!(future.as_mut()).is_pending()); + provider.gate.entered(); + if changed_target { + // This write succeeds while the real wrapping provider is paused: + // the worker must not hold a SQL transaction across provider IO. + sqlx::query( + "UPDATE stock_grants SET protected=randomblob(length(protected)) WHERE grant_id=?", + ) + .bind(r.input.grant_id().as_bytes().as_slice()) + .execute(&mut raw) + .await + .unwrap(); + } else { + r.clock.0.store(151, Ordering::SeqCst); + } + provider.gate.release(); + let result = future.await; + if changed_target { + assert!(result.is_err()); + } else { + assert_eq!(result, Err(OperationError::DeadlineExceeded)); + } + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_operations") + .fetch_one(&mut raw) + .await + .unwrap(); + assert_eq!(count, 0); + raw.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn cancelled_issuance_observer_cannot_release_owner_before_drain_and_original_recovery() { + let mut r = Rig::new().await; + let provider = reopen(&mut r).await; + let capture = r.capture(&r.binding, 0x31); + provider.gate.arm(); + let mut future = + Box::pin( + r.store + .issue_stock_consent(r.binding.clone(), r.minimum, &capture, &r.proof), + ); + assert!(futures::poll!(future.as_mut()).is_pending()); + provider.gate.entered(); + drop(future); + assert!(matches!( + NativeWorkspace::open_seller_stock( + &r.path, + r.input.clone(), + r.fixture.crypto(), + r.clock.clone() + ) + .await, + Err(WorkspaceError::WriterActive) + )); + provider.gate.release(); + r.store.close().await.unwrap(); + let store = NativeWorkspace::open_seller_stock( + &r.path, + r.input.clone(), + r.fixture.crypto(), + r.clock.clone(), + ) + .await + .unwrap(); + let receipt = store + .stock_consent( + r.binding.clone(), + r.minimum, + capture.command().context().operation_id(), + r.input.grant_id(), + &r.proof, + ) + .await + .unwrap() + .unwrap(); + assert_eq!( + receipt.control_operation_id(), + capture.control_operation_id() + ); + assert_eq!(receipt.transaction_id(), capture.transaction_id()); + assert_eq!( + committed( + store + .issue_stock_consent(r.binding.clone(), receipt.checkpoint(), &capture, &r.proof) + .await + .unwrap() + ), + receipt + ); + store.close().await.unwrap(); +} diff --git a/crates/storage_sqlite/src/workspace/stock/consent/tests.rs b/crates/storage_sqlite/src/workspace/stock/consent/tests.rs @@ -0,0 +1,648 @@ +//! Actual native issuance tests. The captured request is deliberately only +//! command data; these tests do not assert causal admission or stock holds. +use super::*; +use crate::workspace::{tests::CryptoFixture, tests::participant}; +use radroots_domain::{CommandContextData, PoolId}; +use radroots_storage::inventory::{InventoryOutcome, InventoryRequest, InventoryStore}; +use std::sync::atomic::{AtomicU64, Ordering}; +#[path = "test_provider.rs"] +mod provider; + +struct Clock(AtomicU64); +impl WorkspaceClock for Clock { + fn now(&self) -> Result<UnixSeconds, WorkspaceError> { + UnixSeconds::new(self.0.load(Ordering::SeqCst)).map_err(|_| WorkspaceError::Unavailable) + } +} +struct Rig { + fixture: CryptoFixture, + path: std::path::PathBuf, + store: NativeWorkspace, + input: AttachmentInput, + proof: AttachmentProof, + binding: WorkspaceBinding, + minimum: InventoryCheckpointRef, + clock: Arc<Clock>, +} +impl Rig { + async fn new() -> Self { + let fixture = CryptoFixture::new(); + let path = fixture.root().join("consent"); + let clock = Arc::new(Clock(AtomicU64::new(100))); + let enrollment = StockEnrollment::prepare( + SellerStockConfig::new( + participant(), + participant(), + "consent-owner", + UnixSeconds::new(200).unwrap(), + ) + .unwrap(), + clock.as_ref(), + ) + .unwrap(); + let input = enrollment.input().clone(); + let proof = enrollment + .proof() + .with_secret(|v| AttachmentProof::from_protected_input(v)) + .unwrap(); + let store = NativeWorkspace::initialize_seller_stock( + &path, + &enrollment, + fixture.crypto(), + clock.clone(), + ) + .await + .unwrap(); + let binding = store.authenticate(input.clone(), &proof).await.unwrap(); + let minimum = store + .stock_authority(input.clone(), &proof) + .await + .unwrap() + .inventory_checkpoint() + .unwrap(); + Self { + fixture, + path, + store, + input, + proof, + binding, + minimum, + clock, + } + } + fn command(&self, binding: &WorkspaceBinding, id: u8) -> CapturedOrderAcceptance { + let context = CommandContextData::new( + OperationId::from_bytes([id; 32]), + binding.actor(), + self.input.workspace_id(), + self.input.authority(), + self.input.route_digest(), + None, + None, + UnixSeconds::new(150).unwrap(), + None, + ) + .unwrap(); + let mut wire = serde_json::json!({"type":"orders.accept","context":context,"input":{"request":"21".repeat(32),"terms_digest":"24".repeat(32),"allocation":{"type":"automatic"}}}); + wire["context"]["expected"] = serde_json::json!({"agreement":null,"buyer_head":"21".repeat(32),"checkpoint":{"coverage":"scope_satisfied","digest":"22".repeat(32),"missing":[],"sequence":"1"},"order_id":"23".repeat(32),"seller_sequence":"0"}); + let captured = CapturedOrderAcceptance::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); + wire["context"]["approval"] = serde_json::json!({"intent_digest":captured.approval_intent_digest(),"scope":"orders.accept","expires_at":"150"}); + CapturedOrderAcceptance::parse(&serde_json::to_vec(&wire).unwrap()).unwrap() + } + fn capture(&self, binding: &WorkspaceBinding, id: u8) -> StockConsentCapture { + StockConsentCapture::prepare( + SellerAuthoritySelection::from_attachment(&self.input), + binding.input().grant_id(), + StockConsentMode::ExecuteAndRecover, + StockResources::all_pools(), + UnixSeconds::new(150).unwrap(), + self.command(binding, id), + ) + .unwrap() + } + async fn physical(&self, id: u8, minimum: InventoryCheckpointRef) -> InventoryCheckpointRef { + let context = CommandContextData::new( + OperationId::from_bytes([id; 32]), + self.binding.actor(), + self.input.workspace_id(), + self.input.authority(), + self.input.route_digest(), + None, + None, + UnixSeconds::new(190).unwrap(), + None, + ) + .unwrap(); + let wire = serde_json::json!({"type":"stock.create_pool","context":context,"input":{"id":PoolId::from_bytes([id;32]),"label":"consent-boundary","unit":"each","tick_scale":"0","initial_quantity":"1"}}); + let request = InventoryRequest::from_protected_wire( + self.binding.clone(), + minimum, + &serde_json::to_vec(&wire).unwrap(), + ) + .unwrap(); + match self + .store + .execute_inventory( + request, + self.proof + .with_secret(|v| AttachmentProof::from_protected_input(v)) + .unwrap(), + ) + .await + .unwrap() + { + InventoryOutcome::Committed(receipt) => receipt.checkpoint(), + _ => panic!("physical operation must confirm"), + } + } +} +fn committed(outcome: StockConsentOutcome) -> StockConsentReceipt { + match outcome { + StockConsentOutcome::Committed(value) => *value, + _ => panic!("issuance must confirm"), + } +} + +#[tokio::test] +async fn original_consent_replays_after_expiry_and_survives_physical_progress_and_reopen() { + let r = Rig::new().await; + let capture = r.capture(&r.binding, 0x31); + let receipt = committed( + r.store + .issue_stock_consent(r.binding.clone(), r.minimum, &capture, &r.proof) + .await + .unwrap(), + ); + assert_eq!( + receipt.control_operation_id(), + capture.control_operation_id() + ); + assert_eq!(receipt.transaction_id(), capture.transaction_id()); + assert_eq!(receipt.command_digest(), capture.command().digest()); + assert_eq!(receipt.checkpoint().revision().get(), 1); + let minimum = r.physical(0x41, receipt.checkpoint()).await; + assert_eq!(minimum.revision().get(), 2); + let replay = r.capture(&r.binding, 0x31); + assert_ne!( + replay.control_operation_id(), + capture.control_operation_id() + ); + r.clock.0.store(160, Ordering::SeqCst); + assert_eq!( + committed( + r.store + .issue_stock_consent(r.binding.clone(), minimum, &replay, &r.proof) + .await + .unwrap() + ), + receipt + ); + let fresh = r.capture(&r.binding, 0x32); + assert_eq!( + r.store + .issue_stock_consent(r.binding.clone(), minimum, &fresh, &r.proof) + .await, + Err(OperationError::DeadlineExceeded) + ); + assert_eq!( + r.store + .stock_consent( + r.binding.clone(), + minimum, + capture.command().context().operation_id(), + r.input.grant_id(), + &r.proof + ) + .await + .unwrap(), + Some(receipt.clone()) + ); + assert_eq!( + r.store + .inventory_operation( + r.binding.clone(), + minimum, + capture.control_operation_id(), + None, + r.proof + .with_secret(|v| AttachmentProof::from_protected_input(v)) + .unwrap() + ) + .await, + Err(OperationError::IdempotencyConflict) + ); + r.store.close().await.unwrap(); + let store = NativeWorkspace::open_seller_stock( + &r.path, + r.input.clone(), + r.fixture.crypto(), + r.clock.clone(), + ) + .await + .unwrap(); + let binding = store.authenticate(r.input.clone(), &r.proof).await.unwrap(); + assert_eq!( + store + .stock_consent( + binding, + minimum, + capture.command().context().operation_id(), + r.input.grant_id(), + &r.proof + ) + .await + .unwrap(), + Some(receipt) + ); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn physical_grant_cannot_issue_business_consent_but_can_read_its_own_issuance() { + let r = Rig::new().await; + let subject = StockGrantEnrollment::prepare( + &SellerAuthoritySelection::from_attachment(&r.input), + "physical-device".into(), + UnixSeconds::new(190).unwrap(), + StockGrantScope::full_inventory(), + ) + .unwrap(); + assert!(matches!( + r.store + .enroll_stock_grant(r.binding.clone(), r.minimum, &r.proof, &subject) + .await + .unwrap(), + StockGrantOutcome::Committed(_) + )); + let minimum = r + .store + .stock_authority(r.input.clone(), &r.proof) + .await + .unwrap() + .inventory_checkpoint() + .unwrap(); + let child = r + .store + .authenticate(subject.input().clone(), subject.proof()) + .await + .unwrap(); + let capture = r.capture(&child, 0x31); + assert_eq!( + r.store + .issue_stock_consent(child.clone(), minimum, &capture, subject.proof()) + .await, + Err(OperationError::Unauthorized) + ); + let admin = r + .store + .authenticate(r.input.clone(), &r.proof) + .await + .unwrap(); + let receipt = committed( + r.store + .issue_stock_consent(admin, minimum, &capture, &r.proof) + .await + .unwrap(), + ); + assert_eq!( + r.store + .stock_consent( + child, + receipt.checkpoint(), + capture.command().context().operation_id(), + subject.input().grant_id(), + subject.proof() + ) + .await + .unwrap(), + Some(receipt.clone()) + ); + assert_eq!( + r.store + .stock_consent( + r.binding.clone(), + receipt.checkpoint(), + OperationId::from_bytes([0x55; 32]), + r.input.grant_id(), + &r.proof + ) + .await + .unwrap(), + None + ); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn changed_natural_index_cannot_turn_retained_consent_into_absence() { + let r = Rig::new().await; + let capture = r.capture(&r.binding, 0x31); + let receipt = committed( + r.store + .issue_stock_consent(r.binding.clone(), r.minimum, &capture, &r.proof) + .await + .unwrap(), + ); + let minimum = r.physical(0x41, receipt.checkpoint()).await; + let mut raw = SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .filename(r.path.join("stock_execution_v1.sqlite")), + ) + .await + .unwrap(); + sqlx::query("UPDATE stock_operations SET related_operation=? WHERE operation_id=?") + .bind([0x77_u8; 32].as_slice()) + .bind(receipt.control_operation_id().as_bytes().as_slice()) + .execute(&mut raw) + .await + .unwrap(); + assert_eq!( + r.store + .stock_consent( + r.binding.clone(), + minimum, + capture.command().context().operation_id(), + r.input.grant_id(), + &r.proof + ) + .await, + Err(OperationError::RecoveryRequired) + ); + assert_eq!( + r.store + .issue_stock_consent(r.binding.clone(), minimum, &capture, &r.proof) + .await, + Err(OperationError::RecoveryRequired) + ); + sqlx::query("UPDATE stock_operations SET related_operation=? WHERE operation_id=?") + .bind( + capture + .command() + .context() + .operation_id() + .as_bytes() + .as_slice(), + ) + .bind(receipt.control_operation_id().as_bytes().as_slice()) + .execute(&mut raw) + .await + .unwrap(); + assert_eq!( + r.store + .stock_consent( + r.binding.clone(), + minimum, + capture.command().context().operation_id(), + r.input.grant_id(), + &r.proof + ) + .await + .unwrap(), + Some(receipt) + ); + raw.close().await.unwrap(); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn every_issuance_write_window_rolls_back_without_advancing_the_root() { + for trigger in [ + "CREATE TRIGGER fault BEFORE INSERT ON stock_operations BEGIN SELECT RAISE(ABORT,'fixture'); END", + "CREATE TRIGGER fault BEFORE INSERT ON stock_operation_parts BEGIN SELECT RAISE(ABORT,'fixture'); END", + "CREATE TRIGGER fault BEFORE UPDATE ON stock_authority BEGIN SELECT RAISE(ABORT,'fixture'); END", + ] { + let r = Rig::new().await; + let capture = r.capture(&r.binding, 0x31); + let mut raw = SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .filename(r.path.join("stock_execution_v1.sqlite")), + ) + .await + .unwrap(); + sqlx::raw_sql(trigger).execute(&mut raw).await.unwrap(); + assert_eq!( + r.store + .issue_stock_consent(r.binding.clone(), r.minimum, &capture, &r.proof) + .await, + Err(OperationError::StorageFailure) + ); + assert_eq!( + r.store + .stock_authority(r.input.clone(), &r.proof) + .await + .unwrap() + .inventory_checkpoint() + .unwrap(), + r.minimum + ); + let count:i64=sqlx::query_scalar("SELECT (SELECT count(*) FROM stock_operations)+(SELECT count(*) FROM stock_operation_parts)").fetch_one(&mut raw).await.unwrap(); + assert_eq!(count, 0); + sqlx::raw_sql("DROP TRIGGER fault") + .execute(&mut raw) + .await + .unwrap(); + assert_eq!( + committed( + r.store + .issue_stock_consent(r.binding.clone(), r.minimum, &capture, &r.proof) + .await + .unwrap() + ) + .transaction_id(), + capture.transaction_id() + ); + raw.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn failed_commit_keeps_the_original_anchor_and_fences_until_close_and_reopen() { + let r = Rig::new().await; + let capture = r.capture(&r.binding, 0x31); + let mut raw = SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .filename(r.path.join("stock_execution_v1.sqlite")), + ) + .await + .unwrap(); + sqlx::raw_sql("CREATE TABLE deferred_fault(value INTEGER REFERENCES stock_authority(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fault AFTER INSERT ON stock_operations BEGIN INSERT INTO deferred_fault VALUES(2); END").execute(&mut raw).await.unwrap(); + assert_eq!( + r.store + .issue_stock_consent(r.binding.clone(), r.minimum, &capture, &r.proof) + .await + .unwrap(), + StockConsentOutcome::Unknown { + control_operation: capture.control_operation_id(), + transaction: capture.transaction_id(), + command_operation: capture.command().context().operation_id(), + subject: r.input.grant_id() + } + ); + assert_eq!( + r.store + .stock_consent( + r.binding.clone(), + r.minimum, + capture.command().context().operation_id(), + r.input.grant_id(), + &r.proof + ) + .await, + Err(OperationError::RecoveryRequired) + ); + r.store.close().await.unwrap(); + sqlx::raw_sql("DROP TRIGGER fault; DROP TABLE deferred_fault") + .execute(&mut raw) + .await + .unwrap(); + raw.close().await.unwrap(); + let store = NativeWorkspace::open_seller_stock( + &r.path, + r.input.clone(), + r.fixture.crypto(), + r.clock.clone(), + ) + .await + .unwrap(); + assert_eq!( + store + .stock_consent( + r.binding.clone(), + r.minimum, + capture.command().context().operation_id(), + r.input.grant_id(), + &r.proof + ) + .await + .unwrap(), + None + ); + assert_eq!( + committed( + store + .issue_stock_consent(r.binding.clone(), r.minimum, &capture, &r.proof) + .await + .unwrap() + ) + .transaction_id(), + capture.transaction_id() + ); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn exact_resources_are_immutable_and_current_access_precedes_replay() { + let r = Rig::new().await; + let capture = r.capture(&r.binding, 0x31); + let receipt = committed( + r.store + .issue_stock_consent(r.binding.clone(), r.minimum, &capture, &r.proof) + .await + .unwrap(), + ); + let changed = StockConsentCapture::prepare( + SellerAuthoritySelection::from_attachment(&r.input), + r.input.grant_id(), + StockConsentMode::ExecuteAndRecover, + StockResources::pools(vec![PoolId::from_bytes([0x41; 32])]).unwrap(), + UnixSeconds::new(150).unwrap(), + r.command(&r.binding, 0x31), + ) + .unwrap(); + assert_eq!( + r.store + .issue_stock_consent(r.binding.clone(), receipt.checkpoint(), &changed, &r.proof) + .await, + Err(OperationError::IdempotencyConflict) + ); + let wrong = AttachmentProof::from_protected_input(&[0xA7; 32]).unwrap(); + assert_eq!( + r.store + .issue_stock_consent(r.binding.clone(), receipt.checkpoint(), &capture, &wrong) + .await, + Err(OperationError::Workspace(WorkspaceError::Unauthorized)) + ); + r.clock.0.store(99, Ordering::SeqCst); + assert!( + r.store + .issue_stock_consent(r.binding.clone(), receipt.checkpoint(), &capture, &r.proof) + .await + .is_err() + ); + r.clock.0.store(200, Ordering::SeqCst); + assert_eq!( + r.store + .stock_consent( + r.binding.clone(), + receipt.checkpoint(), + capture.command().context().operation_id(), + r.input.grant_id(), + &r.proof + ) + .await, + Err(OperationError::Workspace(WorkspaceError::GrantExpired)) + ); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn recovery_only_can_bind_an_expired_original_command_to_an_explicit_replacement() { + let r = Rig::new().await; + let replacement = StockGrantEnrollment::prepare( + &SellerAuthoritySelection::from_attachment(&r.input), + "replacement".into(), + UnixSeconds::new(190).unwrap(), + StockGrantScope::full_inventory(), + ) + .unwrap(); + assert!(matches!( + r.store + .enroll_stock_grant(r.binding.clone(), r.minimum, &r.proof, &replacement) + .await + .unwrap(), + StockGrantOutcome::Committed(_) + )); + let minimum = r + .store + .stock_authority(r.input.clone(), &r.proof) + .await + .unwrap() + .inventory_checkpoint() + .unwrap(); + let command = r.command(&r.binding, 0x31); + assert!( + StockConsentCapture::prepare( + SellerAuthoritySelection::from_attachment(&r.input), + replacement.input().grant_id(), + StockConsentMode::ExecuteAndRecover, + StockResources::all_pools(), + UnixSeconds::new(150).unwrap(), + r.command(&r.binding, 0x31) + ) + .is_err() + ); + let capture = StockConsentCapture::prepare( + SellerAuthoritySelection::from_attachment(&r.input), + replacement.input().grant_id(), + StockConsentMode::RecoverOnly, + StockResources::all_pools(), + UnixSeconds::new(180).unwrap(), + command, + ) + .unwrap(); + r.clock.0.store(160, Ordering::SeqCst); + let admin = r + .store + .authenticate(r.input.clone(), &r.proof) + .await + .unwrap(); + let receipt = committed( + r.store + .issue_stock_consent(admin, minimum, &capture, &r.proof) + .await + .unwrap(), + ); + assert_eq!(receipt.mode(), StockConsentMode::RecoverOnly); + assert_eq!(receipt.command_digest(), capture.command().digest()); + let subject = r + .store + .authenticate(replacement.input().clone(), replacement.proof()) + .await + .unwrap(); + assert_eq!( + r.store + .stock_consent( + subject, + receipt.checkpoint(), + capture.command().context().operation_id(), + replacement.input().grant_id(), + replacement.proof() + ) + .await + .unwrap(), + Some(receipt) + ); + r.store.close().await.unwrap(); +} diff --git a/crates/storage_sqlite/src/workspace/stock/grants.rs b/crates/storage_sqlite/src/workspace/stock/grants.rs @@ -324,7 +324,7 @@ pub(in crate::workspace) async fn change( } let (mut authority, record, old_root, old_grant) = super::read(turn.connection, change.caller.input(), turn.crypto).await?; - if !(4..=6).contains(&authority.catalog) { + if !(4..=7).contains(&authority.catalog) { return Err(WorkspaceError::Unauthorized); } let catalog = authority.catalog; @@ -347,9 +347,7 @@ pub(in crate::workspace) async fn change( turn.selected, turn.crypto, ¤t, - authority - .inventory - .ok_or(WorkspaceError::RecoveryRequired)?, + &authority, change.minimum, ) .await?; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory.rs b/crates/storage_sqlite/src/workspace/stock/inventory.rs @@ -1,5 +1,5 @@ //! Owner-private inventory effects on the existing connection owner. -mod checkpoint; +pub(super) mod checkpoint; mod codec; mod mapping; mod plan; @@ -10,10 +10,10 @@ pub(super) async fn grant_minimum( input: &AttachmentInput, crypto: &WorkspaceCrypto, binding: &WorkspaceBinding, - current: InventoryCheckpoint, + authority: &Authority, minimum: radroots_storage::inventory::InventoryCheckpointRef, ) -> Result<MinimumProof, WorkspaceError> { - authenticate_minimum(connection, input, crypto, binding, current, minimum) + authenticate_minimum(connection, input, crypto, binding, authority, minimum) .await .map_err(|_| WorkspaceError::RecoveryRequired) } @@ -35,6 +35,15 @@ pub(super) async fn check_head( connection: &mut SqliteConnection, checkpoint: InventoryCheckpoint, ) -> Result<(), WorkspaceError> { + if let Some(expected) = checkpoint.orders { + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_orders") + .fetch_one(&mut *connection) + .await + .map_err(|_| WorkspaceError::RecoveryRequired)?; + if count != expected.get() as i64 { + return Err(WorkspaceError::RecoveryRequired); + } + } let row=sqlx::query("SELECT count(*),coalesce(max(revision),0),coalesce(sum(CASE WHEN revision=? AND chain_head=? THEN 1 ELSE 0 END),0) FROM stock_operations") .bind(checkpoint.revision.get() as i64).bind(checkpoint.head.map(|id|id.as_bytes().to_vec())).fetch_one(&mut *connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?; let count: i64 = row @@ -74,13 +83,14 @@ pub(super) async fn check_head( } Ok(()) } -struct Access { - authority: Authority, - record: StockRecord, - root: Vec<u8>, - grant: Vec<u8>, - current: WorkspaceBinding, - minimum_proof: MinimumProof, +pub(super) struct Access { + pub(super) authority: Authority, + pub(super) record: StockRecord, + pub(super) root: Vec<u8>, + pub(super) grant: Vec<u8>, + pub(super) current: WorkspaceBinding, + pub(super) minimum_proof: MinimumProof, + identity_proof: Option<MinimumProof>, projection_proof: Option<MinimumProof>, mapping_read: Option<mapping::MappingRead>, } @@ -92,8 +102,52 @@ pub(in crate::workspace) struct Turn<'a> { pub clock: &'a dyn WorkspaceClock, pub uncertain: &'a mut bool, } +impl Access { + /// Rechecks authenticated store state inside the caller's actual SQL + /// transaction. Family-specific permissions and deadlines remain separate. + pub(super) async fn confirm( + &self, + connection: &mut SqliteConnection, + namespace: &Namespace, + clock: &dyn WorkspaceClock, + proof: &AttachmentProof, + ) -> Result<WorkspaceBinding, OperationError> { + namespace.validate()?; + super::unchanged( + connection, + self.current.input(), + self.authority.catalog, + &self.root, + &self.grant, + ) + .await?; + if let Some(state) = self.authority.authorization { + grants::check_state(connection, state).await?; + } + check_head( + connection, + self.authority + .inventory + .ok_or(OperationError::UnsupportedOperation)?, + ) + .await?; + self.minimum_proof.confirm(connection).await?; + if let Some(identity) = &self.identity_proof { + identity.confirm(connection).await?; + } + let current = self + .record + .authenticate(self.current.input(), proof, clock.now()?)?; + same_binding(&self.current, ¤t)?; + if current.observed_at() < self.current.observed_at() { + return Err(WorkspaceError::Unavailable.into()); + } + namespace.validate()?; + Ok(current) + } +} impl Turn<'_> { - async fn access( + pub(super) async fn access( &mut self, binding: &WorkspaceBinding, minimum: radroots_storage::inventory::InventoryCheckpointRef, @@ -135,9 +189,7 @@ impl Turn<'_> { self.selected, self.crypto, ¤t, - authority - .inventory - .ok_or(OperationError::UnsupportedOperation)?, + &authority, minimum, ) .await?; @@ -149,6 +201,7 @@ impl Turn<'_> { grant, current, minimum_proof, + identity_proof: None, projection_proof: None, mapping_read: None, }) @@ -171,15 +224,29 @@ impl Turn<'_> { let operation = context.operation_id(); let digest = request.command().digest(); // Retained identity precedes every fresh deadline or pool-existence check. - if let Some(retained) = read_operation( + let retained = read_operation( self.connection, self.selected, self.crypto, request.binding(), operation, ) - .await? - { + .await?; + access.identity_proof = Some( + checkpoint::authenticate_identity( + self.connection, + self.selected, + self.crypto, + &access.current, + &access.authority, + checkpoint::IdentityTarget::Operation( + operation, + retained.as_ref().map(Retained::identity).transpose()?, + ), + ) + .await?, + ); + if let Some(retained) = retained { if retained.digest != digest { return Err(OperationError::IdempotencyConflict); } @@ -241,10 +308,7 @@ impl Turn<'_> { self.selected, self.crypto, &access.current, - access - .authority - .inventory - .ok_or(OperationError::UnsupportedOperation)?, + &access.authority, request.command().pool_id(), before, ) @@ -359,40 +423,76 @@ impl Turn<'_> { }; let command: &RawValue = serde_json::from_slice(request.command().protected_wire()) .map_err(|_| OperationError::InvalidCommand)?; - let protected_operation = self - .crypto - .seal_stock_record_for_catalog( - self.selected, - "operation", - operation.as_bytes(), - catalog, - &encode_operation( - &OperationWire { - version: record_version(catalog)?, - before: if catalog >= 3 { Some(before) } else { None }, - selection: request.binding().input(), - scope: request.binding().scope(), - principal: request.binding().principal_id(), - grant_revision: request.binding().grant_revision(), - grant_expires_at: request.binding().expires_at(), - observed_at: request.binding().observed_at(), - minimum_revision: request.minimum_checkpoint().revision(), - minimum_head: request.minimum_checkpoint().head(), + let operation_body = encode_operation( + &OperationWire { + version: record_version(catalog)?, + before: if catalog >= 3 { Some(before) } else { None }, + selection: request.binding().input(), + scope: request.binding().scope(), + principal: request.binding().principal_id(), + grant_revision: request.binding().grant_revision(), + grant_expires_at: request.binding().expires_at(), + observed_at: request.binding().observed_at(), + minimum_revision: request.minimum_checkpoint().revision(), + minimum_head: request.minimum_checkpoint().head(), + transaction, + revision, + previous_head: checkpoint.head, + head, + command, + pool, + movement, + }, + catalog, + access.authority.authorization, + mapping.as_ref().map(|value| value.effect), + )?; + let framed = if catalog == 7 { + Some( + super::ledger::prepare( + self.crypto, + self.selected, + super::ledger::Header { + version: 5, + family: super::ledger::Family::Inventory, + namespace: SellerAuthoritySelection::from_attachment(self.selected), + actor: request.binding().actor(), + operation, + digest, transaction, revision, - previous_head: checkpoint.head, + previous: checkpoint.head, head, - command, - pool, - movement, + pool: Some(pool.id()), + order: None, + related_operation: None, + subject_grant: None, + bytes: 0, + parts: 0, + body_digest: [0; 32], }, - catalog, - access.authority.authorization, - mapping.as_ref().map(|value| value.effect), - )?, + &operation_body, + ) + .await?, ) - .await?; + } else { + None + }; + let protected_operation = if let Some(framed) = &framed { + framed.protected.clone() + } else { + self.crypto + .seal_stock_record_for_catalog( + self.selected, + "operation", + operation.as_bytes(), + catalog, + &operation_body, + ) + .await? + }; access.authority.inventory = Some(InventoryCheckpoint { + orders: checkpoint.orders, mappings: checkpoint .mappings .map(|count| { @@ -443,6 +543,7 @@ impl Turn<'_> { if let Some(state)=access.authority.authorization { grants::check_state(&mut tx,state).await?; } check_head(&mut tx,checkpoint).await?; access.minimum_proof.confirm(&mut tx).await?; + if let Some(identity)=&access.identity_proof {identity.confirm(&mut tx).await?;} if let Some(proof)=&access.projection_proof {proof.confirm(&mut tx).await?;} let current=access.record.authenticate(request.binding().input(),&proof,self.clock.now()?)?; same_binding(request.binding(),¤t)?; @@ -468,6 +569,7 @@ impl Turn<'_> { } sqlx::query("INSERT INTO stock_operations(actor,grant_id,operation_id,command_digest,transaction_id,pool_id,revision,chain_head,protected) VALUES(?,?,?,?,?,?,?,?,?)") .bind(request.binding().actor().participant().as_bytes().as_slice()).bind(request.binding().input().grant_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(digest.as_bytes().as_slice()).bind(transaction.as_bytes().as_slice()).bind(pool.id().as_bytes().as_slice()).bind(revision.get() as i64).bind(head.as_bytes().as_slice()).bind(protected_operation).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + if let Some(framed)=&framed {framed.insert_parts(&mut tx,request.binding().actor(),operation).await?;} if let (Some(id),Some(protected))=(movement,protected_movement) { sqlx::query("INSERT INTO stock_movements(movement_id,actor,grant_id,operation_id,pool_id,protected) VALUES(?,?,?,?,?,?)").bind(id.as_slice()).bind(request.binding().actor().participant().as_bytes().as_slice()).bind(request.binding().input().grant_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(pool.id().as_bytes().as_slice()).bind(protected).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; } @@ -507,6 +609,7 @@ impl Turn<'_> { if let Some(state)=access.authority.authorization { grants::check_state(&mut tx,state).await?; } check_head(&mut tx,access.authority.inventory.ok_or(OperationError::UnsupportedOperation)?).await?; access.minimum_proof.confirm(&mut tx).await?; + if let Some(identity)=&access.identity_proof {identity.confirm(&mut tx).await?;} if let Some(proof)=&access.projection_proof {proof.confirm(&mut tx).await?;} if let Some(mapping)=&access.mapping_read {mapping.confirm(&mut tx).await?;} let current=access.record.authenticate(access.current.input(),proof,self.clock.now()?)?; @@ -517,6 +620,10 @@ impl Turn<'_> { if let Some(retained)=operation { let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_operations WHERE actor=? AND operation_id=? AND protected=?").bind(current.actor().participant().as_bytes().as_slice()).bind(retained.receipt.attempt().operation_id().as_bytes().as_slice()).bind(&retained.protected).fetch_one(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; if count!=1 {return Err(OperationError::RecoveryRequired);} + if let Some((header,parts))=&retained.frame { + super::ledger::confirm_header(&mut tx,header,&retained.protected).await?; + super::ledger::confirm_parts(&mut tx,header.actor,header.operation,*parts,header.parts).await?; + } let movement_count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_movements WHERE actor=? AND operation_id=?").bind(current.actor().participant().as_bytes().as_slice()).bind(retained.receipt.attempt().operation_id().as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; if movement_count!=i64::from(retained.movement.is_some()) {return Err(OperationError::RecoveryRequired);} if let (Some(id),Some(protected))=(retained.movement,retained.movement_protected.as_ref()) { @@ -542,7 +649,7 @@ impl Turn<'_> { digest: Option<CommandDigest>, proof: AttachmentProof, ) -> Result<Option<InventoryReceipt>, OperationError> { - let access = self.access(&binding, minimum, &proof).await?; + let mut access = self.access(&binding, minimum, &proof).await?; let result = read_operation( self.connection, self.selected, @@ -551,6 +658,20 @@ impl Turn<'_> { operation, ) .await?; + access.identity_proof = Some( + checkpoint::authenticate_identity( + self.connection, + self.selected, + self.crypto, + &access.current, + &access.authority, + checkpoint::IdentityTarget::Operation( + operation, + result.as_ref().map(Retained::identity).transpose()?, + ), + ) + .await?, + ); if !access.record.allows_action(StockAction::ReadOperations) { return Err(OperationError::Unauthorized); } @@ -594,10 +715,7 @@ impl Turn<'_> { self.selected, self.crypto, &access.current, - access - .authority - .inventory - .ok_or(OperationError::UnsupportedOperation)?, + &access.authority, key, result, ) @@ -627,10 +745,7 @@ impl Turn<'_> { self.selected, self.crypto, &access.current, - access - .authority - .inventory - .ok_or(OperationError::UnsupportedOperation)?, + &access.authority, id, result.as_ref().map(|v| v.pool), ) @@ -704,16 +819,31 @@ async fn read_pool( protected, })) } -struct Retained { - original_grant: GrantId, - previous_head: Option<CheckpointDigest>, - movement: Option<[u8; 32]>, - movement_protected: Option<Vec<u8>>, - receipt: InventoryReceipt, - digest: CommandDigest, - protected: Vec<u8>, +pub(super) struct Retained { + pub(super) frame: Option<(super::ledger::Header, [u8; 32])>, + pub(super) original_grant: GrantId, + pub(super) previous_head: Option<CheckpointDigest>, + pub(super) movement: Option<[u8; 32]>, + pub(super) movement_protected: Option<Vec<u8>>, + pub(super) receipt: InventoryReceipt, + pub(super) digest: CommandDigest, + pub(super) protected: Vec<u8>, } -async fn read_operation( +impl Retained { + fn identity(&self) -> Result<checkpoint::EntryIdentity, OperationError> { + Ok(checkpoint::EntryIdentity { + operation: self.receipt.attempt().operation_id(), + revision: self.receipt.checkpoint().revision(), + head: self + .receipt + .checkpoint() + .head() + .ok_or(OperationError::RecoveryRequired)?, + protected_digest: Sha256::digest(&self.protected).into(), + }) + } +} +pub(super) async fn read_operation( connection: &mut SqliteConnection, input: &AttachmentInput, crypto: &WorkspaceCrypto, @@ -731,16 +861,40 @@ async fn read_operation( .fetch_one(&mut *connection) .await .map_err(|_| OperationError::RecoveryRequired)?; - let clear = crypto - .open_stock_record_for_catalog( - input, - "operation", - operation.as_bytes(), - catalog, - &protected, + let (frame, request, decoded) = if catalog == 7 { + let retained = super::ledger::read(connection, input, crypto, operation) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if retained.protected != protected { + return Err(OperationError::RecoveryRequired); + } + if retained.header.family != super::ledger::Family::Inventory { + return Err(OperationError::IdempotencyConflict); + } + let (request, decoded) = decode_operation(retained.body.as_slice(), catalog)?; + if retained.header.actor != request.binding().actor() + || retained.header.previous != decoded.previous_head + { + return Err(OperationError::RecoveryRequired); + } + ( + Some((retained.header, retained.parts_witness)), + request, + decoded, ) - .await?; - let (request, decoded) = clear.expose_secret(|bytes| decode_operation(bytes, catalog))?; + } else { + let clear = crypto + .open_stock_record_for_catalog( + input, + "operation", + operation.as_bytes(), + catalog, + &protected, + ) + .await?; + let (request, decoded) = clear.expose_secret(|bytes| decode_operation(bytes, catalog))?; + (None, request, decoded) + }; if !SellerAuthoritySelection::from_attachment(request.binding().input()) .matches_attachment(binding.input()) || request.binding().actor().participant() != binding.actor().participant() @@ -862,6 +1016,7 @@ async fn read_operation( )? }; Ok(Some(Retained { + frame, original_grant: request.binding().input().grant_id(), previous_head: decoded.previous_head, movement: decoded.movement, diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs b/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs @@ -7,24 +7,43 @@ pub(in crate::workspace::stock) struct MinimumProof { lower: u64, upper: u64, digest: [u8; 32], + multipart: bool, } impl MinimumProof { pub(in crate::workspace::stock) async fn confirm( &self, connection: &mut SqliteConnection, ) -> Result<(), OperationError> { - let mut hash = history_hash(); + let mut hash = history_hash(self.multipart); for revision in (self.lower..=self.upper).rev() { let row=sqlx::query("SELECT actor,grant_id,operation_id,command_digest,transaction_id,pool_id,chain_head,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_operations WHERE revision=?") .bind(revision as i64).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; hash.update(revision.to_be_bytes()); + let mut actor = [0_u8; 32]; + let mut operation = [0_u8; 32]; for column in 0..7 { + if column == 5 { + let pool: Option<Vec<u8>> = row + .try_get(column) + .map_err(|_| OperationError::RecoveryRequired)?; + if !self.multipart && pool.is_none() { + return Err(OperationError::RecoveryRequired); + } + hash_optional(&mut hash, pool.as_deref())?; + continue; + } let bytes: Vec<u8> = row .try_get(column) .map_err(|_| OperationError::RecoveryRequired)?; if bytes.len() != 32 { return Err(OperationError::RecoveryRequired); } + if column == 0 { + actor.copy_from_slice(&bytes); + } + if column == 2 { + operation.copy_from_slice(&bytes); + } hash.update(bytes); } let protected: Vec<u8> = row @@ -33,6 +52,34 @@ impl MinimumProof { .ok_or(OperationError::RecoveryRequired)?; hash.update((protected.len() as u64).to_be_bytes()); hash.update(protected); + if self.multipart { + let row=sqlx::query("SELECT family,order_id,related_operation,subject_grant FROM stock_operations WHERE actor=? AND operation_id=?") + .bind(actor.as_slice()).bind(operation.as_slice()).fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let family: i64 = row + .try_get(0) + .map_err(|_| OperationError::RecoveryRequired)?; + let order: Option<Vec<u8>> = row + .try_get(1) + .map_err(|_| OperationError::RecoveryRequired)?; + let related: Option<Vec<u8>> = row + .try_get(2) + .map_err(|_| OperationError::RecoveryRequired)?; + if !(0..=2).contains(&family) { + return Err(OperationError::RecoveryRequired); + } + let subject: Option<Vec<u8>> = row + .try_get(3) + .map_err(|_| OperationError::RecoveryRequired)?; + hash.update(family.to_be_bytes()); + hash_optional(&mut hash, order.as_deref())?; + hash_optional(&mut hash, related.as_deref())?; + hash_optional(&mut hash, subject.as_deref())?; + let (parts, witness) = + super::super::ledger::raw_parts_witness(connection, &actor, &operation).await?; + hash.update([parts]); + hash.update(witness); + } + hash_current_movements(&mut hash, connection, &actor, &operation).await?; } let actual: [u8; 32] = hash.finalize().into(); if actual != self.digest { @@ -41,19 +88,143 @@ impl MinimumProof { Ok(()) } } -fn history_hash() -> Sha256 { +fn history_hash(multipart: bool) -> Sha256 { let mut hash = Sha256::new(); - hash.update(b"radroots.seller_stock.ancestry_snapshot.v1\0"); + hash.update(b"radroots.seller_stock.ancestry_snapshot.v2\0"); + hash.update([u8::from(multipart)]); hash } +#[derive(Clone, Copy, Eq, PartialEq)] +pub(in crate::workspace::stock) struct EntryIdentity { + pub operation: OperationId, + pub revision: Sequence, + pub head: CheckpointDigest, + pub protected_digest: [u8; 32], +} +pub(in crate::workspace::stock) enum IdentityTarget { + Operation(OperationId, Option<EntryIdentity>), + Consent { + operation: OperationId, + subject: GrantId, + expected: Option<EntryIdentity>, + }, +} +pub(in crate::workspace::stock) async fn authenticate_identity( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + binding: &WorkspaceBinding, + authority: &Authority, + target: IdentityTarget, +) -> Result<MinimumProof, OperationError> { + let current = authority + .inventory + .ok_or(OperationError::UnsupportedOperation)?; + let multipart = authority.catalog == 7; + let upper = current.revision.get(); + let mut previous = current.head; + let mut hash = history_hash(multipart); + for revision in (1..=upper).rev() { + let id:Vec<u8>=sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE revision=? AND length(operation_id)=32") + .bind(revision as i64).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; + let operation = OperationId::from_bytes( + id.try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ); + let (identity, predecessor, natural) = if multipart { + let entry = super::super::ledger::history( + connection, input, crypto, binding, authority, operation, + ) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if entry.header.revision.get() != revision || Some(entry.header.head) != previous { + return Err(OperationError::RecoveryRequired); + } + entry.hash(&mut hash)?; + ( + EntryIdentity { + operation, + revision: entry.header.revision, + head: entry.header.head, + protected_digest: Sha256::digest(&entry.protected).into(), + }, + entry.header.previous, + if entry.header.family == super::super::ledger::Family::Consent { + entry + .header + .related_operation + .zip(entry.header.subject_grant) + } else { + None + }, + ) + } else { + let entry = read_operation(connection, input, crypto, binding, operation) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let checkpoint = entry.receipt.checkpoint(); + if checkpoint.revision().get() != revision || checkpoint.head() != previous { + return Err(OperationError::RecoveryRequired); + } + hash_retained(&mut hash, revision, binding, operation, &entry)?; + ( + EntryIdentity { + operation, + revision: checkpoint.revision(), + head: checkpoint.head().ok_or(OperationError::RecoveryRequired)?, + protected_digest: Sha256::digest(&entry.protected).into(), + }, + entry.previous_head, + None, + ) + }; + let (matched, expected) = match &target { + IdentityTarget::Operation(wanted, expected) => (*wanted == operation, *expected), + IdentityTarget::Consent { + operation: wanted, + subject, + expected, + } => (natural == Some((*wanted, *subject)), *expected), + }; + if matched { + if expected != Some(identity) { + return Err(OperationError::RecoveryRequired); + } + return Ok(MinimumProof { + lower: revision, + upper, + digest: hash.finalize().into(), + multipart, + }); + } + previous = predecessor; + } + let expected = match target { + IdentityTarget::Operation(_, expected) | IdentityTarget::Consent { expected, .. } => { + expected + } + }; + if previous.is_some() || expected.is_some() { + return Err(OperationError::RecoveryRequired); + } + Ok(MinimumProof { + lower: 1, + upper, + digest: hash.finalize().into(), + multipart, + }) +} pub(super) async fn authenticate_minimum( connection: &mut SqliteConnection, input: &AttachmentInput, crypto: &WorkspaceCrypto, binding: &WorkspaceBinding, - current: InventoryCheckpoint, + authority: &Authority, minimum: radroots_storage::inventory::InventoryCheckpointRef, ) -> Result<MinimumProof, OperationError> { + let current = authority + .inventory + .ok_or(OperationError::UnsupportedOperation)?; if minimum.authority() != input.authority() { return Err(WorkspaceError::StaleAuthority.into()); } @@ -62,7 +233,8 @@ pub(super) async fn authenticate_minimum( } let lower = minimum.revision().get().max(1); let upper = current.revision.get(); - let mut hash = history_hash(); + let multipart = authority.catalog == 7; + let mut hash = history_hash(multipart); let mut expected = current.head; for revision in (lower..=upper).rev() { let id:Vec<u8>=sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE revision=? AND length(operation_id)=32") @@ -71,6 +243,23 @@ pub(super) async fn authenticate_minimum( id.try_into() .map_err(|_| OperationError::RecoveryRequired)?, ); + if multipart { + let retained = super::super::ledger::history( + connection, input, crypto, binding, authority, operation, + ) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if retained.header.revision.get() != revision || Some(retained.header.head) != expected + { + return Err(WorkspaceError::StaleCheckpoint.into()); + } + if revision == minimum.revision().get() && expected != minimum.head() { + return Err(WorkspaceError::StaleCheckpoint.into()); + } + retained.hash(&mut hash)?; + expected = retained.header.previous; + continue; + } let retained = read_operation(connection, input, crypto, binding, operation) .await? .ok_or(OperationError::RecoveryRequired)?; @@ -93,6 +282,7 @@ pub(super) async fn authenticate_minimum( lower, upper, digest: hash.finalize().into(), + multipart, }) } @@ -115,7 +305,7 @@ fn hash_retained( .ok_or(OperationError::RecoveryRequired)? .as_bytes(), ); - hash.update(receipt.pool().id().as_bytes()); + hash_optional(hash, Some(receipt.pool().id().as_bytes()))?; hash.update( receipt .checkpoint() @@ -125,6 +315,82 @@ fn hash_retained( ); hash.update((retained.protected.len() as u64).to_be_bytes()); hash.update(&retained.protected); + if let Some((header, parts)) = &retained.frame { + hash.update(header.family.code().to_be_bytes()); + hash_optional(hash, header.order.as_ref().map(|v| v.as_bytes().as_slice()))?; + hash_optional( + hash, + header + .related_operation + .as_ref() + .map(|v| v.as_bytes().as_slice()), + )?; + hash_optional( + hash, + header + .subject_grant + .as_ref() + .map(|v| v.as_bytes().as_slice()), + )?; + hash.update([header.parts]); + hash.update(parts); + } + hash.update([u8::from(retained.movement.is_some())]); + if let (Some(id), Some(protected)) = (retained.movement, &retained.movement_protected) { + hash.update(id); + hash.update(receipt.pool().id().as_bytes()); + hash.update(retained.original_grant.as_bytes()); + hash.update((protected.len() as u64).to_be_bytes()); + hash.update(protected); + } + Ok(()) +} +fn hash_optional(hash: &mut Sha256, value: Option<&[u8]>) -> Result<(), OperationError> { + hash.update([u8::from(value.is_some())]); + if let Some(bytes) = value { + if bytes.len() != 32 { + return Err(OperationError::RecoveryRequired); + } + hash.update(bytes); + } + Ok(()) +} +async fn hash_current_movements( + hash: &mut Sha256, + connection: &mut SqliteConnection, + actor: &[u8; 32], + operation: &[u8; 32], +) -> Result<(), OperationError> { + let count: i64 = + sqlx::query_scalar("SELECT count(*) FROM stock_movements WHERE actor=? AND operation_id=?") + .bind(actor.as_slice()) + .bind(operation.as_slice()) + .fetch_one(&mut *connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + if !(0..=64).contains(&count) { + return Err(OperationError::RecoveryRequired); + } + hash.update([count as u8]); + for offset in 0..count { + let row=sqlx::query("SELECT movement_id,pool_id,grant_id,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_movements WHERE actor=? AND operation_id=? ORDER BY movement_id LIMIT 1 OFFSET ?") + .bind(actor.as_slice()).bind(operation.as_slice()).bind(offset).fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + for column in 0..3 { + let bytes: Vec<u8> = row + .try_get(column) + .map_err(|_| OperationError::RecoveryRequired)?; + if bytes.len() != 32 { + return Err(OperationError::RecoveryRequired); + } + hash.update(bytes); + } + let protected: Vec<u8> = row + .try_get::<Option<Vec<u8>>, _>(3) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)?; + hash.update((protected.len() as u64).to_be_bytes()); + hash.update(protected); + } Ok(()) } @@ -136,7 +402,7 @@ pub(super) async fn authenticate_projection( input: &AttachmentInput, crypto: &WorkspaceCrypto, binding: &WorkspaceBinding, - current: InventoryCheckpoint, + authority: &Authority, pool: PoolId, projected: Option<PoolSnapshot>, ) -> Result<MinimumProof, OperationError> { @@ -145,7 +411,7 @@ pub(super) async fn authenticate_projection( input, crypto, binding, - current, + authority, Projection::Pool(pool, projected), ) .await @@ -155,7 +421,7 @@ pub(super) async fn authenticate_mapping_projection( input: &AttachmentInput, crypto: &WorkspaceCrypto, binding: &WorkspaceBinding, - current: InventoryCheckpoint, + authority: &Authority, key: radroots_domain::stock::OptionMappingKey, projected: Option<radroots_domain::stock::OptionPoolMapping>, ) -> Result<MinimumProof, OperationError> { @@ -164,7 +430,7 @@ pub(super) async fn authenticate_mapping_projection( input, crypto, binding, - current, + authority, Projection::Mapping(key, projected), ) .await @@ -207,18 +473,58 @@ async fn authenticate_projected( input: &AttachmentInput, crypto: &WorkspaceCrypto, binding: &WorkspaceBinding, - current: InventoryCheckpoint, + authority: &Authority, projected: Projection, ) -> Result<MinimumProof, OperationError> { + let current = authority + .inventory + .ok_or(OperationError::UnsupportedOperation)?; let upper = current.revision.get(); let mut expected = current.head; - let mut hash = history_hash(); + let multipart = authority.catalog == 7; + let mut hash = history_hash(multipart); for revision in (1..=upper).rev() { let id:Vec<u8>=sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE revision=? AND length(operation_id)=32").bind(revision as i64).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; let operation = OperationId::from_bytes( id.try_into() .map_err(|_| OperationError::RecoveryRequired)?, ); + if multipart { + let retained = super::super::ledger::history( + connection, input, crypto, binding, authority, operation, + ) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if retained.header.revision.get() != revision || Some(retained.header.head) != expected + { + return Err(OperationError::RecoveryRequired); + } + retained.hash(&mut hash)?; + let matched = match &projected { + Projection::Pool(id, observed) => retained + .pools + .iter() + .find(|pool| pool.id() == *id) + .map(|actual| *observed == Some(*actual)), + Projection::Mapping(key, observed) => retained + .mapping + .filter(|actual| actual.key() == *key) + .map(|actual| *observed == Some(actual)), + }; + if let Some(matched) = matched { + if !matched { + return Err(OperationError::RecoveryRequired); + } + return Ok(MinimumProof { + lower: revision, + upper, + digest: hash.finalize().into(), + multipart, + }); + } + expected = retained.header.previous; + continue; + } let retained = read_operation(connection, input, crypto, binding, operation) .await? .ok_or(OperationError::RecoveryRequired)?; @@ -233,6 +539,7 @@ async fn authenticate_projected( lower: revision, upper, digest: hash.finalize().into(), + multipart, }); } expected = retained.previous_head; @@ -244,5 +551,6 @@ async fn authenticate_projected( lower: 1, upper, digest: hash.finalize().into(), + multipart, }) } diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/codec.rs @@ -120,7 +120,7 @@ pub(super) fn encode_operation( String::from_utf8(clear.to_vec()).map_err(|_| OperationError::StorageFailure)?, ) .map_err(|_| OperationError::StorageFailure)?; - if matches!(catalog, 5 | 6) { + if matches!(catalog, 5..=7) { return super::encode(&OperationV4 { version: 4, authorization: authorization.ok_or(OperationError::RecoveryRequired)?, @@ -158,7 +158,7 @@ fn decode_inner( catalog: i64, allow_mapping: bool, ) -> Result<(InventoryRequest, OperationData), OperationError> { - if matches!(catalog, 5 | 6) { + if matches!(catalog, 5..=7) { let decoded: OperationV4<'_> = super::closed_record(bytes).map_err(|_| OperationError::RecoveryRequired)?; if decoded.version != 4 { diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/mapping.rs b/crates/storage_sqlite/src/workspace/stock/inventory/mapping.rs @@ -58,7 +58,7 @@ impl MappingRead { } } pub(super) fn require(access: &Access, key: OptionMappingKey) -> Result<(), OperationError> { - if !(5..=6).contains(&access.authority.catalog) { + if !(5..=7).contains(&access.authority.catalog) { return Err(OperationError::UnsupportedOperation); } if !access.record.administrator() @@ -180,10 +180,7 @@ pub(super) async fn prepare( turn.selected, turn.crypto, &access.current, - access - .authority - .inventory - .ok_or(OperationError::UnsupportedOperation)?, + &access.authority, input.key(), before, ) diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/plan.rs b/crates/storage_sqlite/src/workspace/stock/inventory/plan.rs @@ -3,7 +3,7 @@ use super::*; pub(super) fn record_version(catalog: i64) -> Result<u8, OperationError> { match catalog { 2 => Ok(1), - 3..=6 => Ok(2), + 3..=7 => Ok(2), _ => Err(OperationError::RecoveryRequired), } } diff --git a/crates/storage_sqlite/src/workspace/stock/ledger.rs b/crates/storage_sqlite/src/workspace/stock/ledger.rs @@ -0,0 +1,560 @@ +//! Bounded multipart operation framing for the multi-pool native ledger. +//! Framing authenticates original storage bytes; family-specific admission +//! must independently validate every business or physical effect. +use super::*; +use radroots_domain::{ActorRef, CheckpointDigest, CommandDigest, OperationId, PoolId}; +use radroots_storage::command::OperationError; +use sha2::{Digest, Sha256}; +use sqlx::Row; +use zeroize::Zeroizing; + +pub(super) const BODY_MAX_BYTES: usize = 256 * 1024; +const PART_BYTES: usize = 16 * 1024; +const MAX_PARTS: usize = BODY_MAX_BYTES / PART_BYTES; + +#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(super) enum Family { + Inventory, + Consent, + Acceptance, +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Header { + pub version: u8, + pub family: Family, + #[serde(deserialize_with = "super::object")] + pub namespace: SellerAuthoritySelection, + pub actor: ActorRef, + pub operation: OperationId, + pub digest: CommandDigest, + pub transaction: TransactionId, + pub revision: Sequence, + #[serde(deserialize_with = "super::required_nullable")] + pub previous: Option<CheckpointDigest>, + pub head: CheckpointDigest, + #[serde(deserialize_with = "super::required_nullable")] + pub pool: Option<PoolId>, + #[serde(deserialize_with = "super::required_nullable")] + pub order: Option<radroots_domain::OrderId>, + #[serde(deserialize_with = "super::required_nullable")] + pub related_operation: Option<OperationId>, + #[serde(deserialize_with = "super::required_nullable")] + pub subject_grant: Option<GrantId>, + pub bytes: u32, + pub parts: u8, + pub body_digest: [u8; 32], +} +impl Header { + pub fn validate( + &self, + input: &AttachmentInput, + operation: OperationId, + ) -> Result<(), OperationError> { + if self.version != 5 + || !self.namespace.matches_attachment(input) + || self.actor.participant() != input.participant() + || self.actor.role() != radroots_domain::ActorRole::Seller + || self.actor.organization().is_some() + || self.actor.grant_id().is_none() + || self.operation != operation + || self.revision.get() == 0 + || (self.revision.get() == 1) != self.previous.is_none() + || (self.family == Family::Inventory) != self.pool.is_some() + || (self.family == Family::Inventory) != self.order.is_none() + || (self.family == Family::Consent) != self.related_operation.is_some() + || (self.family == Family::Consent) != self.subject_grant.is_some() + || self.bytes == 0 + || self.bytes as usize > BODY_MAX_BYTES + || usize::from(self.parts) != (self.bytes as usize).div_ceil(PART_BYTES) + { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } +} + +pub(super) struct Prepared { + pub protected: Vec<u8>, + parts: Vec<Vec<u8>>, +} +pub(super) struct Retained { + pub header: Header, + pub body: Zeroizing<Vec<u8>>, + pub protected: Vec<u8>, + pub parts_witness: [u8; 32], +} +fn part_id(actor: ActorRef, operation: OperationId, part: u8) -> [u8; 32] { + let mut hash = Sha256::new(); + hash.update(b"radroots.seller_stock.operation_part_key.v1\0"); + hash.update(actor.participant().as_bytes()); + hash.update(operation.as_bytes()); + hash.update([part]); + hash.finalize().into() +} +fn part_hash() -> Sha256 { + let mut hash = Sha256::new(); + hash.update(b"radroots.seller_stock.operation_parts_snapshot.v1\0"); + hash +} +fn hash_part(hash: &mut Sha256, part: u8, grant: &[u8; 32], protected: &[u8]) { + hash.update([part]); + hash.update(grant); + hash.update((protected.len() as u64).to_be_bytes()); + hash.update(protected); +} + +pub(super) async fn prepare( + crypto: &WorkspaceCrypto, + input: &AttachmentInput, + mut header: Header, + body: &[u8], +) -> Result<Prepared, OperationError> { + if body.is_empty() || body.len() > BODY_MAX_BYTES { + return Err(WorkspaceError::Capacity.into()); + } + header.bytes = body.len() as u32; + header.parts = body.len().div_ceil(PART_BYTES) as u8; + header.body_digest = Sha256::digest(body).into(); + header.validate(input, header.operation)?; + let mut parts = Vec::with_capacity(usize::from(header.parts)); + for (index, clear) in body.chunks(PART_BYTES).enumerate() { + parts.push( + crypto + .seal_stock_record( + input, + "operation_part", + &part_id(header.actor, header.operation, index as u8), + clear, + ) + .await?, + ); + } + let clear = + Zeroizing::new(serde_json::to_vec(&header).map_err(|_| OperationError::StorageFailure)?); + if clear.len() > PART_BYTES { + return Err(WorkspaceError::Capacity.into()); + } + let protected = crypto + .seal_stock_record_for_catalog(input, "operation", header.operation.as_bytes(), 7, &clear) + .await?; + Ok(Prepared { protected, parts }) +} +impl Prepared { + /// Called only within the existing owner's SQL transaction. Protection and + /// provider callbacks have already completed before entering this method. + pub async fn insert_parts( + &self, + connection: &mut SqliteConnection, + actor: ActorRef, + operation: OperationId, + ) -> Result<(), OperationError> { + let grant = actor.grant_id().ok_or(OperationError::RecoveryRequired)?; + for (index, protected) in self.parts.iter().enumerate() { + sqlx::query("INSERT INTO stock_operation_parts(actor,grant_id,operation_id,part,protected) VALUES(?,?,?,?,?)") + .bind(actor.participant().as_bytes().as_slice()) + .bind(grant.as_bytes().as_slice()) + .bind(operation.as_bytes().as_slice()) + .bind(index as i64) + .bind(protected) + .execute(&mut *connection) + .await + .map_err(|_|OperationError::StorageFailure)?; + } + Ok(()) + } +} + +pub(super) async fn read( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + operation: OperationId, +) -> Result<Option<Retained>, OperationError> { + let row=sqlx::query("SELECT grant_id,command_digest,transaction_id,pool_id,revision,chain_head,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END,family,order_id,related_operation,subject_grant FROM stock_operations WHERE actor=? AND operation_id=?") + .bind(input.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()) + .fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let Some(row) = row else { return Ok(None) }; + let protected: Vec<u8> = row + .try_get::<Option<Vec<u8>>, _>(6) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)?; + let clear = crypto + .open_stock_record_for_catalog(input, "operation", operation.as_bytes(), 7, &protected) + .await?; + let header: Header = clear.expose_secret(|bytes| super::closed_record(bytes))?; + header.validate(input, operation)?; + let grant: Vec<u8> = row + .try_get(0) + .map_err(|_| OperationError::RecoveryRequired)?; + let digest: Vec<u8> = row + .try_get(1) + .map_err(|_| OperationError::RecoveryRequired)?; + let transaction: Vec<u8> = row + .try_get(2) + .map_err(|_| OperationError::RecoveryRequired)?; + let pool: Option<Vec<u8>> = row + .try_get(3) + .map_err(|_| OperationError::RecoveryRequired)?; + let revision: i64 = row + .try_get(4) + .map_err(|_| OperationError::RecoveryRequired)?; + let head: Vec<u8> = row + .try_get(5) + .map_err(|_| OperationError::RecoveryRequired)?; + let family: i64 = row + .try_get(7) + .map_err(|_| OperationError::RecoveryRequired)?; + let order: Option<Vec<u8>> = row + .try_get(8) + .map_err(|_| OperationError::RecoveryRequired)?; + let related: Option<Vec<u8>> = row + .try_get(9) + .map_err(|_| OperationError::RecoveryRequired)?; + let subject: Option<Vec<u8>> = row + .try_get(10) + .map_err(|_| OperationError::RecoveryRequired)?; + if header + .actor + .grant_id() + .map(|value| value.as_bytes().to_vec()) + != Some(grant) + || digest != header.digest.as_bytes() + || transaction != header.transaction.as_bytes() + || pool != header.pool.map(|value| value.as_bytes().to_vec()) + || revision <= 0 + || revision as u64 != header.revision.get() + || head != header.head.as_bytes() + || family != header.family.code() + || order != header.order.map(|value| value.as_bytes().to_vec()) + || subject != header.subject_grant.map(|value| value.as_bytes().to_vec()) + || related + != header + .related_operation + .map(|value| value.as_bytes().to_vec()) + { + return Err(OperationError::RecoveryRequired); + } + let mut body = Zeroizing::new(Vec::with_capacity(header.bytes as usize)); + let mut witness = part_hash(); + for index in 0..header.parts { + let protected = read_part(connection, header.actor, operation, index).await?; + hash_part( + &mut witness, + index, + header + .actor + .grant_id() + .ok_or(OperationError::RecoveryRequired)? + .as_bytes(), + &protected, + ); + let clear = crypto + .open_stock_record( + input, + "operation_part", + &part_id(header.actor, operation, index), + &protected, + ) + .await?; + clear.expose_secret(|bytes| { + let expected = if index + 1 == header.parts { + header.bytes as usize - usize::from(index) * PART_BYTES + } else { + PART_BYTES + }; + if bytes.len() != expected { + return Err(OperationError::RecoveryRequired); + } + body.extend_from_slice(bytes); + Ok(()) + })?; + } + if body.len() != header.bytes as usize + || <[u8; 32]>::from(Sha256::digest(body.as_slice())) != header.body_digest + { + return Err(OperationError::RecoveryRequired); + } + let parts_witness = witness.finalize().into(); + confirm_parts( + connection, + header.actor, + operation, + parts_witness, + header.parts, + ) + .await?; + Ok(Some(Retained { + header, + body, + protected, + parts_witness, + })) +} +impl Family { + pub const fn code(self) -> i64 { + match self { + Self::Inventory => 0, + Self::Consent => 1, + Self::Acceptance => 2, + } + } +} +pub(super) async fn confirm_header( + connection: &mut SqliteConnection, + header: &Header, + protected: &[u8], +) -> Result<(), OperationError> { + let matched:i64=sqlx::query_scalar("SELECT count(*) FROM stock_operations WHERE actor=? AND grant_id=? AND operation_id=? AND command_digest=? AND transaction_id=? AND pool_id IS ? AND revision=? AND chain_head=? AND protected=? AND family=? AND order_id IS ? AND related_operation IS ? AND subject_grant IS ?") + .bind(header.actor.participant().as_bytes().as_slice()) + .bind(header.actor.grant_id().ok_or(OperationError::RecoveryRequired)?.as_bytes().as_slice()) + .bind(header.operation.as_bytes().as_slice()).bind(header.digest.as_bytes().as_slice()) + .bind(header.transaction.as_bytes().as_slice()).bind(header.pool.map(|v|v.as_bytes().to_vec())) + .bind(header.revision.get() as i64).bind(header.head.as_bytes().as_slice()).bind(protected) + .bind(header.family.code()).bind(header.order.map(|v|v.as_bytes().to_vec())) + .bind(header.related_operation.map(|v|v.as_bytes().to_vec())).bind(header.subject_grant.map(|v|v.as_bytes().to_vec())).fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if matched != 1 { + return Err(OperationError::RecoveryRequired); + } + Ok(()) +} +async fn read_part( + connection: &mut SqliteConnection, + actor: ActorRef, + operation: OperationId, + part: u8, +) -> Result<Vec<u8>, OperationError> { + let row=sqlx::query("SELECT grant_id,protected FROM stock_operation_parts WHERE actor=? AND operation_id=? AND part=? AND length(protected) BETWEEN 1 AND 262144") + .bind(actor.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(i64::from(part)) + .fetch_optional(connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; + let grant: Vec<u8> = row + .try_get(0) + .map_err(|_| OperationError::RecoveryRequired)?; + if grant + != actor + .grant_id() + .ok_or(OperationError::RecoveryRequired)? + .as_bytes() + { + return Err(OperationError::RecoveryRequired); + } + row.try_get(1).map_err(|_| OperationError::RecoveryRequired) +} +pub(super) async fn confirm_parts( + connection: &mut SqliteConnection, + actor: ActorRef, + operation: OperationId, + expected: [u8; 32], + parts: u8, +) -> Result<(), OperationError> { + if parts == 0 || usize::from(parts) > MAX_PARTS { + return Err(OperationError::RecoveryRequired); + } + let (count, actual) = raw_parts_witness( + connection, + actor.participant().as_bytes(), + operation.as_bytes(), + ) + .await?; + if count != parts || actual != expected { + return Err(OperationError::RecoveryRequired); + } + Ok(()) +} +pub(super) async fn raw_parts_witness( + connection: &mut SqliteConnection, + actor: &[u8; 32], + operation: &[u8; 32], +) -> Result<(u8, [u8; 32]), OperationError> { + let count: i64 = sqlx::query_scalar( + "SELECT count(*) FROM stock_operation_parts WHERE actor=? AND operation_id=?", + ) + .bind(actor.as_slice()) + .bind(operation.as_slice()) + .fetch_one(&mut *connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + if count <= 0 || count > MAX_PARTS as i64 { + return Err(OperationError::RecoveryRequired); + } + let mut hash = part_hash(); + for part in 0..count { + let row=sqlx::query("SELECT grant_id,protected FROM stock_operation_parts WHERE actor=? AND operation_id=? AND part=? AND length(protected) BETWEEN 1 AND 262144") + .bind(actor.as_slice()).bind(operation.as_slice()).bind(part).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; + let grant: Vec<u8> = row + .try_get(0) + .map_err(|_| OperationError::RecoveryRequired)?; + let grant: [u8; 32] = grant + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?; + let protected: Vec<u8> = row + .try_get(1) + .map_err(|_| OperationError::RecoveryRequired)?; + hash_part(&mut hash, part as u8, &grant, &protected); + } + Ok((count as u8, hash.finalize().into())) +} + +pub(super) struct MovementWitness { + pub id: [u8; 32], + pub pool: PoolId, + pub grant: GrantId, + pub protected: Vec<u8>, +} +/// A completely decoded original effect. Only the owning family decoder +/// supplies its pool effects and movement witnesses; SQL indexes do not. +pub(super) struct HistoryEntry { + pub header: Header, + pub protected: Vec<u8>, + pub parts_witness: [u8; 32], + pub pools: Vec<radroots_domain::stock::PoolSnapshot>, + pub mapping: Option<radroots_domain::stock::OptionPoolMapping>, + pub movements: Vec<MovementWitness>, +} +pub(super) async fn history( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + binding: &WorkspaceBinding, + authority: &Authority, + operation: OperationId, +) -> Result<Option<HistoryEntry>, OperationError> { + let family: Option<i64> = + sqlx::query_scalar("SELECT family FROM stock_operations WHERE actor=? AND operation_id=?") + .bind(input.participant().as_bytes().as_slice()) + .bind(operation.as_bytes().as_slice()) + .fetch_optional(&mut *connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + match family { + None => Ok(None), + Some(0) => { + let retained = + super::inventory::read_operation(connection, input, crypto, binding, operation) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let (header, parts_witness) = retained.frame.ok_or(OperationError::RecoveryRequired)?; + let movements = match (retained.movement, retained.movement_protected) { + (Some(id), Some(protected)) => vec![MovementWitness { + id, + pool: retained.receipt.pool().id(), + grant: retained.original_grant, + protected, + }], + (None, None) => vec![], + _ => return Err(OperationError::RecoveryRequired), + }; + Ok(Some(HistoryEntry { + header, + protected: retained.protected, + parts_witness, + pools: vec![retained.receipt.pool()], + mapping: retained.receipt.mapping(), + movements, + })) + } + Some(1) => { + let retained = super::consent::read( + connection, + input, + crypto, + authority.input.grant_id(), + operation, + ) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let count: i64 = sqlx::query_scalar( + "SELECT count(*) FROM stock_movements WHERE actor=? AND operation_id=?", + ) + .bind(input.participant().as_bytes().as_slice()) + .bind(operation.as_bytes().as_slice()) + .fetch_one(connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + if count != 0 { + return Err(OperationError::RecoveryRequired); + } + Ok(Some(HistoryEntry { + header: retained.frame.header, + protected: retained.frame.protected, + parts_witness: retained.frame.parts_witness, + pools: vec![], + mapping: None, + movements: vec![], + })) + } + Some(2) => Err(OperationError::UnsupportedOperation), + Some(_) => Err(OperationError::RecoveryRequired), + } +} +pub(super) fn hash_optional(hash: &mut Sha256, value: Option<&[u8]>) -> Result<(), OperationError> { + hash.update([u8::from(value.is_some())]); + if let Some(bytes) = value { + if bytes.len() != 32 { + return Err(OperationError::RecoveryRequired); + } + hash.update(bytes); + } + Ok(()) +} +impl HistoryEntry { + pub fn hash(&self, hash: &mut Sha256) -> Result<(), OperationError> { + let header = &self.header; + hash.update(header.revision.get().to_be_bytes()); + hash.update(header.actor.participant().as_bytes()); + hash.update( + header + .actor + .grant_id() + .ok_or(OperationError::RecoveryRequired)? + .as_bytes(), + ); + hash.update(header.operation.as_bytes()); + hash.update(header.digest.as_bytes()); + hash.update(header.transaction.as_bytes()); + hash_optional(hash, header.pool.as_ref().map(|v| v.as_bytes().as_slice()))?; + hash.update(header.head.as_bytes()); + hash.update((self.protected.len() as u64).to_be_bytes()); + hash.update(&self.protected); + hash.update(header.family.code().to_be_bytes()); + hash_optional(hash, header.order.as_ref().map(|v| v.as_bytes().as_slice()))?; + hash_optional( + hash, + header + .related_operation + .as_ref() + .map(|v| v.as_bytes().as_slice()), + )?; + hash_optional( + hash, + header + .subject_grant + .as_ref() + .map(|v| v.as_bytes().as_slice()), + )?; + hash.update([header.parts]); + hash.update(self.parts_witness); + if self.movements.len() > 64 + || self + .movements + .windows(2) + .any(|pair| pair[0].id >= pair[1].id) + { + return Err(OperationError::RecoveryRequired); + } + hash.update([self.movements.len() as u8]); + for movement in &self.movements { + hash.update(movement.id); + hash.update(movement.pool.as_bytes()); + hash.update(movement.grant.as_bytes()); + hash.update((movement.protected.len() as u64).to_be_bytes()); + hash.update(&movement.protected); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/storage_sqlite/src/workspace/stock/ledger/tests.rs b/crates/storage_sqlite/src/workspace/stock/ledger/tests.rs @@ -0,0 +1,228 @@ +//! Framing-only tests: these deliberately supply synthetic body data and do +//! not claim business admission or an accepted stock operation. +use super::*; +use crate::workspace::tests::{CryptoFixture, participant}; +use radroots_domain::{ActorRole, OrderId, UnixSeconds}; + +fn selection() -> AttachmentInput { + let (input, _, _) = SellerStockConfig::new( + participant(), + participant(), + "frame-fixture", + UnixSeconds::new(200).unwrap(), + ) + .unwrap() + .enroll( + UnixSeconds::new(100).unwrap(), + WorkspaceId::from_bytes([1; 32]), + ExecutorId::from_bytes([2; 32]), + GrantId::from_bytes([3; 32]), + AttachmentProof::from_protected_input(&[4; 32]).unwrap(), + ) + .unwrap(); + input +} +fn header(input: &AttachmentInput) -> Header { + Header { + version: 5, + family: Family::Acceptance, + namespace: SellerAuthoritySelection::from_attachment(input), + actor: ActorRef::new( + participant(), + ActorRole::Seller, + None, + Some(input.grant_id()), + ), + operation: OperationId::from_bytes([5; 32]), + digest: CommandDigest::from_bytes([6; 32]), + transaction: TransactionId::from_bytes([7; 32]), + revision: Sequence::new(1).unwrap(), + previous: None, + head: CheckpointDigest::from_bytes([8; 32]), + pool: None, + order: Some(OrderId::from_bytes([9; 32])), + related_operation: None, + subject_grant: None, + bytes: 0, + parts: 0, + body_digest: [0; 32], + } +} +async fn database(input: &AttachmentInput) -> SqliteConnection { + let mut connection = SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .in_memory(true) + .foreign_keys(true), + ) + .await + .unwrap(); + for (_, _, _, sql) in super::super::schema::objects(7).unwrap() { + sqlx::raw_sql(sql).execute(&mut connection).await.unwrap(); + } + // Only the foreign-key metadata needed by framing is installed. This is + // not an enrolled NativeWorkspace and supplies no authenticated grant. + sqlx::query("INSERT INTO stock_grants(grant_id,protected) VALUES(?,?)") + .bind(input.grant_id().as_bytes().as_slice()) + .bind([1_u8].as_slice()) + .execute(&mut connection) + .await + .unwrap(); + connection +} +async fn insert(connection: &mut SqliteConnection, input: &AttachmentInput, prepared: &Prepared) { + let value = header(input); + let mut tx = connection.begin_with("BEGIN IMMEDIATE").await.unwrap(); + sqlx::query("INSERT INTO stock_operations(actor,grant_id,operation_id,command_digest,transaction_id,pool_id,revision,chain_head,protected,family,order_id,related_operation) VALUES(?,?,?,?,?,NULL,?,?,?,2,?,NULL)") + .bind(input.participant().as_bytes().as_slice()).bind(input.grant_id().as_bytes().as_slice()) + .bind(value.operation.as_bytes().as_slice()).bind(value.digest.as_bytes().as_slice()).bind(value.transaction.as_bytes().as_slice()) + .bind(value.revision.get() as i64).bind(value.head.as_bytes().as_slice()).bind(&prepared.protected) + .bind(value.order.unwrap().as_bytes().as_slice()).execute(&mut *tx).await.unwrap(); + prepared + .insert_parts(&mut tx, value.actor, value.operation) + .await + .unwrap(); + tx.commit().await.unwrap(); +} + +#[tokio::test] +async fn actual_protected_multipart_body_roundtrips_exact_boundaries_and_sql_witnesses() { + let fixture = CryptoFixture::new(); + let input = selection(); + let crypto = fixture.crypto(); + for length in [1, PART_BYTES, PART_BYTES + 1, BODY_MAX_BYTES] { + let mut connection = database(&input).await; + let body = vec![0x51; length]; + let prepared = prepare(&crypto, &input, header(&input), &body) + .await + .unwrap(); + assert_eq!(prepared.parts.len(), length.div_ceil(PART_BYTES)); + insert(&mut connection, &input, &prepared).await; + let value = read(&mut connection, &input, &crypto, header(&input).operation) + .await + .unwrap() + .unwrap(); + assert_eq!(value.body.as_slice(), body.as_slice()); + assert_eq!(value.protected, prepared.protected); + confirm_parts( + &mut connection, + value.header.actor, + value.header.operation, + value.parts_witness, + value.header.parts, + ) + .await + .unwrap(); + sqlx::query("PRAGMA foreign_keys=OFF") + .execute(&mut connection) + .await + .unwrap(); + sqlx::query("UPDATE stock_operation_parts SET grant_id=zeroblob(32) WHERE part=0") + .execute(&mut connection) + .await + .unwrap(); + assert_eq!( + confirm_parts( + &mut connection, + value.header.actor, + value.header.operation, + value.parts_witness, + value.header.parts + ) + .await, + Err(OperationError::RecoveryRequired) + ); + assert!( + read(&mut connection, &input, &crypto, value.header.operation) + .await + .is_err() + ); + sqlx::query("UPDATE stock_operation_parts SET grant_id=? WHERE part=0") + .bind(input.grant_id().as_bytes().as_slice()) + .execute(&mut connection) + .await + .unwrap(); + sqlx::query("PRAGMA foreign_keys=ON") + .execute(&mut connection) + .await + .unwrap(); + sqlx::query( + "UPDATE stock_operation_parts SET protected=randomblob(length(protected)) WHERE part=0", + ) + .execute(&mut connection) + .await + .unwrap(); + assert_eq!( + confirm_parts( + &mut connection, + value.header.actor, + value.header.operation, + value.parts_witness, + value.header.parts + ) + .await, + Err(OperationError::RecoveryRequired) + ); + assert!( + read(&mut connection, &input, &crypto, header(&input).operation) + .await + .is_err() + ); + connection.close().await.unwrap(); + } + assert!(matches!( + prepare(&crypto, &input, header(&input), &[]).await, + Err(OperationError::Workspace(WorkspaceError::Capacity)) + )); + assert!(matches!( + prepare( + &crypto, + &input, + header(&input), + &vec![0x51; BODY_MAX_BYTES + 1] + ) + .await, + Err(OperationError::Workspace(WorkspaceError::Capacity)) + )); +} + +#[tokio::test] +async fn substituted_family_scope_and_missing_or_reordered_body_parts_refuse() { + let fixture = CryptoFixture::new(); + let input = selection(); + let crypto = fixture.crypto(); + for statement in [ + "DELETE FROM stock_operation_parts WHERE part=1", + "UPDATE stock_operation_parts SET protected=(SELECT protected FROM stock_operation_parts WHERE part=0) WHERE part=1", + "UPDATE stock_operations SET command_digest=zeroblob(32)", + "UPDATE stock_operations SET transaction_id=zeroblob(32)", + "UPDATE stock_operations SET order_id=zeroblob(32)", + ] { + let mut connection = database(&input).await; + let prepared = prepare(&crypto, &input, header(&input), &vec![0x51; PART_BYTES + 1]) + .await + .unwrap(); + insert(&mut connection, &input, &prepared).await; + sqlx::raw_sql(statement) + .execute(&mut connection) + .await + .unwrap(); + assert!( + read(&mut connection, &input, &crypto, header(&input).operation) + .await + .is_err() + ); + connection.close().await.unwrap(); + } + let mut bad = header(&input); + bad.family = Family::Inventory; + assert!(matches!( + prepare(&crypto, &input, bad, b"frame").await, + Err(OperationError::RecoveryRequired) + )); + let mut bad = header(&input); + bad.related_operation = Some(OperationId::from_bytes([0xa1; 32])); + assert!(matches!( + prepare(&crypto, &input, bad, b"frame").await, + Err(OperationError::RecoveryRequired) + )); +} diff --git a/crates/storage_sqlite/src/workspace/stock/schema.rs b/crates/storage_sqlite/src/workspace/stock/schema.rs @@ -1,7 +1,7 @@ //! Exact stock catalogs. Enrollment-only version1 is retained without upgrade. use super::WorkspaceError; use sqlx::SqliteConnection; -pub(super) const CURRENT: i64 = 6; +pub(super) const CURRENT: i64 = 7; const AUTHORITY: &str = "CREATE TABLE stock_authority (singleton INTEGER PRIMARY KEY CHECK(singleton=1), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT"; const GRANTS: &str = "CREATE TABLE stock_grants (grant_id BLOB PRIMARY KEY CHECK(length(grant_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID"; const POOLS: &str = "CREATE TABLE stock_pools (pool_id BLOB PRIMARY KEY CHECK(length(pool_id)=32), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID"; @@ -12,6 +12,7 @@ const REVISION: &str = "CREATE UNIQUE INDEX stock_operation_revision_identity ON stock_operations(revision)"; const HEAD: &str = "CREATE UNIQUE INDEX stock_operation_head_identity ON stock_operations(chain_head)"; +const OPERATIONS_V7: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL REFERENCES stock_grants(grant_id), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), pool_id BLOB REFERENCES stock_pools(pool_id) DEFERRABLE INITIALLY DEFERRED, revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), family INTEGER NOT NULL DEFAULT 0 CHECK(family BETWEEN 0 AND 2), order_id BLOB CHECK(order_id IS NULL OR length(order_id)=32), related_operation BLOB CHECK(related_operation IS NULL OR length(related_operation)=32), subject_grant BLOB REFERENCES stock_grants(grant_id) CHECK(subject_grant IS NULL OR length(subject_grant)=32), PRIMARY KEY(actor,grant_id,operation_id), CHECK((family=0 AND pool_id IS NOT NULL AND order_id IS NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=1 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NOT NULL) OR (family=2 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NULL AND subject_grant IS NULL))) STRICT, WITHOUT ROWID"; const MOVEMENTS: &str = "CREATE TABLE stock_movements (movement_id BLOB PRIMARY KEY CHECK(length(movement_id)=32), actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL CHECK(length(grant_id)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), pool_id BLOB NOT NULL REFERENCES stock_pools(pool_id), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), FOREIGN KEY(actor,grant_id,operation_id) REFERENCES stock_operations(actor,grant_id,operation_id)) STRICT, WITHOUT ROWID"; pub(super) fn objects( version: i64, @@ -22,9 +23,18 @@ pub(super) fn objects( ]; match version { 1 => {} - 2..=6 => objects.extend([ + 2..=7 => objects.extend([ ("table", "stock_pools", "stock_pools", POOLS), - ("table", "stock_operations", "stock_operations", OPERATIONS), + ( + "table", + "stock_operations", + "stock_operations", + if version == 7 { + OPERATIONS_V7 + } else { + OPERATIONS + }, + ), ( "index", "stock_operation_transaction_identity", @@ -60,7 +70,7 @@ pub(super) fn objects( if version >= 5 { objects.push(("table","stock_mappings","stock_mappings","CREATE TABLE stock_mappings (listing_author BLOB NOT NULL CHECK(length(listing_author)=32), listing_d BLOB NOT NULL CHECK(length(listing_d)=16), option_id BLOB NOT NULL CHECK(length(option_id)=32), pool_id BLOB NOT NULL REFERENCES stock_pools(pool_id), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(listing_author,listing_d,option_id)) STRICT, WITHOUT ROWID")); } - if version == 6 { + if matches!(version, 6 | 7) { objects.push(("table","stock_source_records","stock_source_records","CREATE TABLE stock_source_records (record_id BLOB PRIMARY KEY CHECK(length(record_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); objects.push(("table","stock_source_evidence","stock_source_evidence","CREATE TABLE stock_source_evidence (envelope_id BLOB PRIMARY KEY CHECK(length(envelope_id)=32), record_id BLOB REFERENCES stock_source_records(record_id), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); objects.push(("index","stock_source_transaction_identity","stock_source_evidence","CREATE UNIQUE INDEX stock_source_transaction_identity ON stock_source_evidence(transaction_id)")); @@ -78,6 +88,12 @@ pub(super) fn objects( )); objects.push(("table","stock_source_parts","stock_source_parts","CREATE TABLE stock_source_parts (envelope_id BLOB NOT NULL REFERENCES stock_source_evidence(envelope_id), role INTEGER NOT NULL CHECK(role BETWEEN 0 AND 2), part INTEGER NOT NULL CHECK(part BETWEEN 0 AND 3), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(envelope_id,role,part)) STRICT, WITHOUT ROWID")); } + if version == 7 { + objects.push(("table","stock_operation_parts","stock_operation_parts","CREATE TABLE stock_operation_parts (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL CHECK(length(grant_id)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), part INTEGER NOT NULL CHECK(part BETWEEN 0 AND 15), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(actor,operation_id,part), FOREIGN KEY(actor,grant_id,operation_id) REFERENCES stock_operations(actor,grant_id,operation_id)) STRICT, WITHOUT ROWID")); + objects.push(("index","stock_consent_target_identity","stock_operations","CREATE UNIQUE INDEX stock_consent_target_identity ON stock_operations(actor,related_operation,subject_grant) WHERE family=1")); + objects.push(("index","stock_order_operation_position","stock_operations","CREATE INDEX stock_order_operation_position ON stock_operations(order_id,revision) WHERE order_id IS NOT NULL")); + objects.push(("table","stock_orders","stock_orders","CREATE TABLE stock_orders (order_id BLOB PRIMARY KEY CHECK(length(order_id)=32), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); + } Ok(objects) } pub(super) async fn admit(connection: &mut SqliteConnection) -> Result<i64, WorkspaceError> { diff --git a/crates/storage_sqlite/src/workspace/stock/source/transaction.rs b/crates/storage_sqlite/src/workspace/stock/source/transaction.rs @@ -28,7 +28,7 @@ async fn access( } let (authority, record, root, grant) = super::super::read(turn.connection, binding.input(), turn.crypto).await?; - if authority.catalog != 6 { + if !matches!(authority.catalog, 6 | 7) { return Err(OperationError::UnsupportedOperation); } let current = record.authenticate(binding.input(), proof, turn.clock.now()?)?; diff --git a/crates/storage_sqlite/src/workspace/stock/tests.rs b/crates/storage_sqlite/src/workspace/stock/tests.rs @@ -109,7 +109,7 @@ async fn current_grant_set_reopens_with_original_namespace_after_one_grant_chang ) .await .unwrap(); - assert_eq!(schema::admit(&mut connection).await, Ok(6)); + assert_eq!(schema::admit(&mut connection).await, Ok(7)); assert_eq!(schema::integrity(&mut connection).await, Ok(())); let root: Vec<u8> = sqlx::query_scalar("SELECT protected FROM stock_authority") .fetch_one(&mut connection) @@ -117,18 +117,18 @@ async fn current_grant_set_reopens_with_original_namespace_after_one_grant_chang .unwrap(); let clear = fixture .crypto() - .open_stock_root(enrollment.input(), 6, &root) + .open_stock_root(enrollment.input(), 7, &root) .await .unwrap(); let authority = clear - .expose_secret(|bytes| Authority::decode(bytes, 6)) + .expose_secret(|bytes| Authority::decode(bytes, 7)) .unwrap(); clear.expose_secret(|bytes| { let original:serde_json::Value=serde_json::from_slice(bytes).unwrap(); assert_eq!(original["inventory"]["mappings"],"0"); for bad in [serde_json::json!([]),serde_json::json!({"revision":"1","pools":"1","movements":"1","head":original["inventory"]["head"]})] { let mut value=original.clone();value["inventory"]=bad; - assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),6).is_err()); + assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),7).is_err()); } for bad in [ serde_json::json!([]), @@ -139,7 +139,7 @@ async fn current_grant_set_reopens_with_original_namespace_after_one_grant_chang serde_json::json!({"revision":"1","records":"2","parts":"3","head":"01".repeat(32)}), ] { let mut value=original.clone();value["sources"]=bad; - assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),6).is_err()); + assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),7).is_err()); } }); assert_eq!(authority.input, *enrollment.input()); @@ -189,7 +189,7 @@ async fn current_and_retained_roots_bind_the_complete_namespace_with_distinct_ca let caller = namespace.attachment(GrantId::from_bytes([9; 32])).unwrap(); let crypto = fixture.crypto(); let clear = b"synthetic context payload"; - for version in [4, 5, 6] { + for version in [4, 5, 6, 7] { let current = crypto .seal_stock_root(&owner, version, clear) .await @@ -255,10 +255,22 @@ async fn retained_inventory_v4_preserves_scoped_grants_and_original_effects_with async fn retained_inventory_v5_preserves_mappings_and_never_adds_source_tables() { retained_inventory_catalog(5).await; } -async fn retained_inventory_catalog(catalog: i64) { - use radroots_storage::inventory::{InventoryCommandKind, InventoryOutcome}; - let fixture = CryptoFixture::new(); - let path = fixture.root().join("retained-v2"); +#[tokio::test] +async fn retained_inventory_v6_preserves_original_physical_and_source_capabilities() { + retained_inventory_catalog(6).await; +} +#[tokio::test] +async fn current_v7_physical_ledger_uses_protected_parts() { + assert_eq!(schema::CURRENT, 7); + retained_inventory_catalog(7).await; +} +// Exact catalog fixtures exercise retained/successor codecs; they are not +// evidence from a predecessor executable or a factory migration. +pub(super) async fn literal_catalog( + fixture: &CryptoFixture, + path: &std::path::Path, + catalog: i64, +) -> (AttachmentInput, AttachmentProof) { let (input, proof, record) = SellerStockConfig::new( participant(), participant(), @@ -301,16 +313,23 @@ async fn retained_inventory_catalog(catalog: i64) { } else { serde_json::json!({"version":catalog,"input":input,"transaction":TransactionId::from_bytes([9;32]),"revocation":"1","inventory":{"revision":"0","pools":"0","movements":"0","head":null}}) }; - if catalog == 5 { - value["version"] = serde_json::json!(5); + if catalog >= 5 { + value["version"] = serde_json::json!(catalog); value["inventory"]["mappings"] = serde_json::json!("0"); } + if catalog >= 6 { + value["sources"] = + serde_json::json!({"revision":"0","records":"0","parts":"0","head":null}); + } + if catalog == 7 { + value["inventory"]["orders"] = serde_json::json!("0"); + } let clear = zeroize::Zeroizing::new(serde_json::to_vec(&value).unwrap()); let root = crypto .seal_stock_root(&input, catalog, &clear) .await .unwrap(); - let namespace = Namespace::acquire_kind(&path, true, Kind::SellerStock).unwrap(); + let namespace = Namespace::acquire_kind(path, true, Kind::SellerStock).unwrap(); let mut connection = SqliteConnection::connect_with( &sqlx::sqlite::SqliteConnectOptions::new() .filename(namespace.database_path()) @@ -339,6 +358,8 @@ async fn retained_inventory_catalog(catalog: i64) { 3 => "PRAGMA user_version=3", 4 => "PRAGMA user_version=4", 5 => "PRAGMA user_version=5", + 6 => "PRAGMA user_version=6", + 7 => "PRAGMA user_version=7", _ => unreachable!(), }) .execute(&mut *tx) @@ -347,13 +368,21 @@ async fn retained_inventory_catalog(catalog: i64) { tx.commit().await.unwrap(); connection.close().await.unwrap(); drop(namespace); + (input, proof) +} + +async fn retained_inventory_catalog(catalog: i64) { + use radroots_storage::inventory::{InventoryCommandKind, InventoryOutcome}; + let fixture = CryptoFixture::new(); + let path = fixture.root().join("retained-v2"); + let (input, proof) = literal_catalog(&fixture, &path, catalog).await; let store = NativeWorkspace::open_seller_stock(&path, input.clone(), fixture.crypto(), Arc::new(Clock)) .await .unwrap(); let binding = store.authenticate(input.clone(), &proof).await.unwrap(); let authority = store.stock_authority(input.clone(), &proof).await.unwrap(); - assert!(authority.source_checkpoint().is_none()); + assert_eq!(authority.source_checkpoint().is_some(), catalog >= 6); let minimum = authority.inventory_checkpoint().unwrap(); let context = CommandContextData::new( OperationId::from_bytes([7; 32]), @@ -460,6 +489,71 @@ async fn retained_inventory_catalog(catalog: i64) { InventoryOutcome::Unknown(_) => panic!("retained correction must confirm"), } } + if catalog >= 6 { + // The caller's minimum is newer than this original operation. A + // hidden SQL identity must still fail protected absence verification. + let mut raw = SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .filename(path.join("stock_execution_v1.sqlite")) + .foreign_keys(false), + ) + .await + .unwrap(); + sqlx::query("UPDATE stock_operations SET operation_id=? WHERE operation_id=?") + .bind([0x78_u8; 32].as_slice()) + .bind([7_u8; 32].as_slice()) + .execute(&mut raw) + .await + .unwrap(); + assert!(matches!( + store + .inventory_operation( + binding.clone(), + latest, + OperationId::from_bytes([7; 32]), + None, + copy() + ) + .await, + Err(OperationError::RecoveryRequired + | OperationError::Workspace(WorkspaceError::RecoveryRequired)) + )); + assert!(matches!( + store + .execute_inventory( + InventoryRequest::from_protected_wire( + binding.clone(), + latest, + &serde_json::to_vec(&wire).unwrap() + ) + .unwrap(), + copy() + ) + .await, + Err(OperationError::RecoveryRequired + | OperationError::Workspace(WorkspaceError::RecoveryRequired)) + )); + sqlx::query("UPDATE stock_operations SET operation_id=? WHERE operation_id=?") + .bind([7_u8; 32].as_slice()) + .bind([0x78_u8; 32].as_slice()) + .execute(&mut raw) + .await + .unwrap(); + raw.close().await.unwrap(); + assert_eq!( + store + .inventory_operation( + binding.clone(), + latest, + OperationId::from_bytes([7; 32]), + None, + copy() + ) + .await + .unwrap(), + Some(created.clone()) + ); + } if catalog >= 4 { let child = StockGrantEnrollment::prepare( &SellerAuthoritySelection::from_attachment(&input), @@ -507,7 +601,7 @@ async fn retained_inventory_catalog(catalog: i64) { assert_eq!( reopened .inventory_operation( - binding, + binding.clone(), latest, OperationId::from_bytes([7; 32]), None, @@ -530,18 +624,35 @@ async fn retained_inventory_catalog(catalog: i64) { .fetch_one(&mut connection) .await .unwrap(); - let old = fixture - .crypto() - .open_stock_record_for_catalog( + let old = if catalog == 7 { + let retained = ledger::read( + &mut connection, &input, - "operation", - OperationId::from_bytes([7; 32]).as_bytes(), - catalog, - &protected, + &fixture.crypto(), + OperationId::from_bytes([7; 32]), ) .await + .unwrap() .unwrap(); - old.expose_secret(|bytes| { + assert_eq!(retained.header.version, 5); + assert_eq!(retained.header.family.code(), 0); + retained.body + } else { + let old = fixture + .crypto() + .open_stock_record_for_catalog( + &input, + "operation", + OperationId::from_bytes([7; 32]).as_bytes(), + catalog, + &protected, + ) + .await + .unwrap(); + old.expose_secret(|bytes| zeroize::Zeroizing::new(bytes.to_vec())) + }; + { + let bytes = old.as_slice(); let value: serde_json::Value = serde_json::from_slice(bytes).unwrap(); let value = if catalog >= 4 { assert_eq!(value["version"], if catalog == 4 { 3 } else { 4 }); @@ -560,12 +671,82 @@ async fn retained_inventory_catalog(catalog: i64) { } else { assert_eq!(value["before"], serde_json::Value::Null); } - }); + } + if catalog >= 6 { + // Exercise the actual minimum/projection witness after provider IO, + // inside a real SQL transaction. Row counts and the protected header + // stay unchanged while one referenced ciphertext changes. + for part in [false, true] { + if part && catalog != 7 { + continue; + } + let (authority, _, _, _) = read(&mut connection, &input, &fixture.crypto()) + .await + .unwrap(); + let minimum = radroots_storage::inventory::InventoryCheckpointRef::from_host_metadata( + input.authority(), + Sequence::new(0).unwrap(), + None, + ) + .unwrap() + .with_optional_authorization(authority.authorization); + let witness = inventory::grant_minimum( + &mut connection, + &input, + &fixture.crypto(), + &binding, + &authority, + minimum, + ) + .await + .unwrap(); + let (select, mutate, restore) = if part { + ( + "SELECT protected FROM stock_operation_parts WHERE operation_id=? AND part=0", + "UPDATE stock_operation_parts SET protected=randomblob(length(protected)) WHERE operation_id=? AND part=0", + "UPDATE stock_operation_parts SET protected=? WHERE operation_id=? AND part=0", + ) + } else { + ( + "SELECT protected FROM stock_movements WHERE operation_id=?", + "UPDATE stock_movements SET protected=randomblob(length(protected)) WHERE operation_id=?", + "UPDATE stock_movements SET protected=? WHERE operation_id=?", + ) + }; + let original: Vec<u8> = sqlx::query_scalar(select) + .bind(OperationId::from_bytes([7; 32]).as_bytes().as_slice()) + .fetch_one(&mut connection) + .await + .unwrap(); + sqlx::query(mutate) + .bind(OperationId::from_bytes([7; 32]).as_bytes().as_slice()) + .execute(&mut connection) + .await + .unwrap(); + let mut tx = connection.begin_with("BEGIN IMMEDIATE").await.unwrap(); + assert_eq!( + witness.confirm(&mut tx).await, + Err(OperationError::RecoveryRequired) + ); + tx.rollback().await.unwrap(); + sqlx::query(restore) + .bind(original) + .bind(OperationId::from_bytes([7; 32]).as_bytes().as_slice()) + .execute(&mut connection) + .await + .unwrap(); + let mut tx = connection.begin_with("BEGIN IMMEDIATE").await.unwrap(); + assert_eq!(witness.confirm(&mut tx).await, Ok(())); + tx.rollback().await.unwrap(); + } + } sqlx::query(match catalog { 2 => "PRAGMA user_version=3", 3 => "PRAGMA user_version=4", 4 => "PRAGMA user_version=5", 5 => "PRAGMA user_version=6", + 6 => "PRAGMA user_version=7", + 7 => "PRAGMA user_version=6", _ => unreachable!(), }) .execute(&mut connection) diff --git a/crates/storage_sqlite/src/workspace/tests/mod.rs b/crates/storage_sqlite/src/workspace/tests/mod.rs @@ -53,7 +53,7 @@ fn reference(id: &str, backend: BackendKind, version: u32) -> SecretRef { } pub(super) struct CryptoFixture { _temp: tempfile::TempDir, - provider: Arc<FileProvider>, + pub(super) provider: Arc<FileProvider>, } impl CryptoFixture { pub(super) fn root(&self) -> std::path::PathBuf { @@ -87,8 +87,14 @@ impl CryptoFixture { .unwrap(); } pub(super) fn crypto(&self) -> WorkspaceCrypto { + self.crypto_with_provider(self.provider.clone()) + } + pub(super) fn crypto_with_provider( + &self, + provider: Arc<dyn SecretProvider>, + ) -> WorkspaceCrypto { WorkspaceCrypto::new( - self.provider.clone(), + provider, reference("grant-key", BackendKind::File, 1), SecretMaterial::from_slice(&[0x41; 32]).unwrap(), AccessPolicy::standard(), diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -38,6 +38,21 @@ const QUEUE_MAX_BYTES: usize = 4 * 1024 * 1024; const QUEUE_CAPACITY: usize = 32; type Reply<T, E = WorkspaceError> = oneshot::Sender<Result<T, E>>; enum Job { + IssueStockConsent( + Box<WorkspaceBinding>, + radroots_storage::inventory::InventoryCheckpointRef, + Box<stock::StockConsentCapture>, + AttachmentProof, + Reply<stock::StockConsentOutcome, OperationError>, + ), + StockConsent( + Box<WorkspaceBinding>, + radroots_storage::inventory::InventoryCheckpointRef, + OperationId, + radroots_domain::GrantId, + AttachmentProof, + Reply<Option<stock::StockConsentReceipt>, OperationError>, + ), RetainStockSource( Box<WorkspaceBinding>, radroots_storage::workspace::seller_stock::StockSourceCheckpointRef, @@ -189,6 +204,12 @@ enum Job { impl Job { fn reject_recovery(self) { match self { + Self::IssueStockConsent(_, _, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::StockConsent(_, _, _, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } Self::RetainStockSource(_, _, _, _, reply) => { let _ = reply.send(Err(OperationError::RecoveryRequired)); } @@ -403,6 +424,8 @@ impl Handle { && !matches!( &job, Job::Authenticate(..) + | Job::IssueStockConsent(..) + | Job::StockConsent(..) | Job::ChangeStockGrant(..) | Job::ExecuteInventory(..) | Job::InventoryOperation(..) @@ -502,6 +525,58 @@ impl Handle { }; let _ = reply.send(result); } + Job::IssueStockConsent(binding, minimum, capture, proof, reply) => { + let result = if kind == Kind::SellerStock { + stock::consent::issue( + &mut stock::inventory::Turn { + connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + }, + *binding, + minimum, + *capture, + proof, + ) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + } + Job::StockConsent( + binding, + minimum, + operation, + subject, + proof, + reply, + ) => { + let result = if kind == Kind::SellerStock { + stock::consent::query( + &mut stock::inventory::Turn { + connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + }, + *binding, + minimum, + operation, + subject, + proof, + ) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + } Job::RetainStockSource(binding, minimum, capture, proof, reply) => { let result = if kind == Kind::SellerStock { stock::source::retain( @@ -979,6 +1054,48 @@ impl Handle { ))?; result.await.map_err(|_| OperationError::RecoveryRequired)? } + pub(super) async fn issue_stock_consent( + &self, + binding: WorkspaceBinding, + minimum: radroots_storage::inventory::InventoryCheckpointRef, + capture: stock::StockConsentCapture, + proof: AttachmentProof, + ) -> Result<stock::StockConsentOutcome, OperationError> { + let anchor = stock::StockConsentOutcome::Unknown { + control_operation: capture.control_operation_id(), + transaction: capture.transaction_id(), + command_operation: capture.command().context().operation_id(), + subject: capture.subject_grant(), + }; + let (reply, result) = oneshot::channel(); + self.send(Job::IssueStockConsent( + Box::new(binding), + minimum, + Box::new(capture), + proof, + reply, + ))?; + result.await.unwrap_or(Ok(anchor)) + } + pub(super) async fn stock_consent( + &self, + binding: WorkspaceBinding, + minimum: radroots_storage::inventory::InventoryCheckpointRef, + operation: OperationId, + subject: radroots_domain::GrantId, + proof: AttachmentProof, + ) -> Result<Option<stock::StockConsentReceipt>, OperationError> { + let (reply, result) = oneshot::channel(); + self.send(Job::StockConsent( + Box::new(binding), + minimum, + operation, + subject, + proof, + reply, + ))?; + result.await.map_err(|_| OperationError::RecoveryRequired)? + } pub(super) async fn retain_stock_source( &self, binding: WorkspaceBinding, @@ -1047,6 +1164,7 @@ impl Handle { } fn send(&self, job: Job) -> Result<(), WorkspaceError> { let bytes = match &job { + Job::IssueStockConsent(..) => 512 * 1024, Job::RetainStockSource(..) => 256 * 1024, Job::ChangeStockGrant(..) | Job::ExecuteInventory(..) => 64 * 1024, Job::CaptureDeliveryObservation(..) => 96 * 1024, diff --git a/crates/storage_sqlite/tests/support/pool_creation.rs b/crates/storage_sqlite/tests/support/pool_creation.rs @@ -368,7 +368,7 @@ async fn sealed_root_detects_missing_inventory_history_instead_of_fresh_stock() ); let mut connection = database(&f).await; sqlx::raw_sql( - "DELETE FROM stock_movements; DELETE FROM stock_operations; DELETE FROM stock_pools", + "DELETE FROM stock_movements; DELETE FROM stock_operation_parts; DELETE FROM stock_operations; DELETE FROM stock_pools", ) .execute(&mut connection) .await diff --git a/crates/storage_sqlite/tests/support/stock_authority.rs b/crates/storage_sqlite/tests/support/stock_authority.rs @@ -602,7 +602,7 @@ async fn changed_catalog_after_protected_reads_is_refused_before_authenticated_c clock.release(); assert_eq!(operation.await, Err(WorkspaceError::RecoveryRequired)); store.close().await.unwrap(); - sqlx::query("PRAGMA user_version=6") + sqlx::query("PRAGMA user_version=7") .execute(&mut connection) .await .unwrap(); diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -125,6 +125,18 @@ struct NativeSellerStockAuthority { retained_inventory_versions: Vec<u16>, authority_payload_schema: String, inventory_operation_payload_schema: String, + operation_part_payload_schema: String, + operation_body_max_bytes: u32, + operation_part_max_bytes: u32, + operation_part_max_count: u16, + operation_identity_requires_protected_ancestry: bool, + business_consent_payload_version: u16, + business_consent_action: String, + business_consent_modes: Vec<String>, + business_consent_admin_issuance_required: bool, + business_consent_binds_exact_command_and_subject_grant: bool, + business_consent_issuance_has_order_or_stock_effects: bool, + business_consent_worker_charge_bytes: u32, inventory_movement_payload_schema: String, grant_payload_schema: String, grant_change_payload_schema: String, @@ -329,11 +341,23 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && stock.scope == "seller_stock_owner" && stock.database == "stock_execution_v1.sqlite" && stock.lock == ".stock_execution_v1.lock" - && stock.schema_version == 6 + && stock.schema_version == 7 && stock.retained_enrollment_versions == [1] - && stock.retained_inventory_versions == [2, 3, 4, 5] - && stock.authority_payload_schema == "radroots.seller_stock.authority.v6" - && stock.inventory_operation_payload_schema == "radroots.seller_stock.operation.v4" + && stock.retained_inventory_versions == [2, 3, 4, 5, 6] + && stock.authority_payload_schema == "radroots.seller_stock.authority.v7" + && stock.inventory_operation_payload_schema == "radroots.seller_stock.operation.v5" + && stock.operation_part_payload_schema == "radroots.seller_stock.operation_part.v1" + && stock.operation_body_max_bytes == 262144 + && stock.operation_part_max_bytes == 16384 + && stock.operation_part_max_count == 16 + && stock.operation_identity_requires_protected_ancestry + && stock.business_consent_payload_version == 1 + && stock.business_consent_action == "orders.accept" + && stock.business_consent_modes == ["execute_and_recover", "recover_only"] + && stock.business_consent_admin_issuance_required + && stock.business_consent_binds_exact_command_and_subject_grant + && !stock.business_consent_issuance_has_order_or_stock_effects + && stock.business_consent_worker_charge_bytes == 524288 && stock.mapping_payload_schema == "radroots.seller_stock.mapping.v1" && stock.source_payload_schemas == [ @@ -922,6 +946,47 @@ mod tests { } #[test] + fn consent_ledger_requires_bounded_parts_explicit_scopes_and_protected_identity() { + for (field, bad) in [ + ("schema_version", json!(6)), + ("retained_inventory_versions", json!([2, 3, 4, 5])), + ( + "operation_part_payload_schema", + json!("radroots.seller_stock.operation_part.v2"), + ), + ("operation_body_max_bytes", json!(262145)), + ("operation_part_max_bytes", json!(16385)), + ("operation_part_max_count", json!(17)), + ( + "operation_identity_requires_protected_ancestry", + json!(false), + ), + ("business_consent_payload_version", json!(2)), + ("business_consent_action", json!("stock.add")), + ("business_consent_modes", json!(["execute_and_recover"])), + ("business_consent_admin_issuance_required", json!(false)), + ( + "business_consent_binds_exact_command_and_subject_grant", + json!(false), + ), + ( + "business_consent_issuance_has_order_or_stock_effects", + json!(true), + ), + ("business_consent_worker_charge_bytes", json!(16384)), + ] { + assert!( + validate_bytes(&changed( + &format!("/native_seller_stock_authority/{field}"), + bad + )) + .is_err(), + "{field}" + ); + } + } + + #[test] fn source_retention_contract_requires_provenance_bounds_and_separate_authority() { for (field, bad) in [ ("schema_version", json!(5)),