lib

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

commit a4cc1a1cc76c7e313b0304eb321561e0af14ae22
parent 09c5b616052b5158947a123fef8d949849563a82
Author: triesap <tyson@radroots.org>
Date:   Sat, 24 Oct 2026 18:47:35 +0000

storage_sqlite: add explicit fresh seller authority enrollment

- Consume prepared identities once and retain original creation receipts.
- Bind separate protected authority and grants to an exact native namespace.
- Recheck current snapshots and confirm transaction and close completion.
- Verify real native faults, Linux execution and retained browser workflows.

Diffstat:
Mcontracts/api_baselines/radroots_storage.txt | 10++++++++++
Mcontracts/api_baselines/radroots_storage_sqlite.txt | 18++++++++++++++++++
Mcontracts/architecture/decisions/shared_sdk_refactor.v1.json | 13+++++++++++++
Mcrates/storage/README.md | 5++++-
Mcrates/storage/src/workspace.rs | 2++
Mcrates/storage/src/workspace/grant.rs | 4++++
Acrates/storage/src/workspace/seller_stock.rs | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/README.md | 31++++++++++++++++++++++++++++++-
Mcrates/storage_sqlite/src/workspace/crypto.rs | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/fs.rs | 68+++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mcrates/storage_sqlite/src/workspace/mod.rs | 6++++--
Acrates/storage_sqlite/src/workspace/stock.rs | 398+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/worker.rs | 193++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Acrates/storage_sqlite/tests/support/stock_authority.rs | 512+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/tests/workspace_attachment.rs | 3+++
Mtools/xtask/src/architecture/decision_package.rs | 32++++++++++++++++++++++++++++++++
16 files changed, 1426 insertions(+), 48 deletions(-)

diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -2299,6 +2299,7 @@ pub fn radroots_storage::workspace::grant::WorkspaceGrant::decode_outbox(&[u8]) pub fn radroots_storage::workspace::grant::WorkspaceGrant::encode(&self) -> core::result::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>, radroots_storage::workspace::WorkspaceError> pub fn radroots_storage::workspace::grant::WorkspaceGrant::new(radroots_storage::workspace::AttachmentInput, radroots_domain::context::ActorRef, alloc::string::String, radroots_domain::context::UnixSeconds, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> pub fn radroots_storage::workspace::grant::WorkspaceGrant::revoke(&mut self) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> +pub const fn radroots_storage::workspace::grant::WorkspaceGrant::scope(&self) -> radroots_storage::workspace::WorkspaceScope impl core::ops::drop::Drop for radroots_storage::workspace::grant::WorkspaceGrant pub fn radroots_storage::workspace::grant::WorkspaceGrant::drop(&mut self) pub const radroots_storage::workspace::grant::GRANT_BYTES_MAX: usize @@ -2315,6 +2316,15 @@ pub fn radroots_storage::workspace::local_outbox::LocalOutboxConfig::new(radroot pub fn radroots_storage::workspace::local_outbox::LocalOutboxConfig::seller(radroots_identity::key::PublicKey, radroots_identity::key::PublicKey, impl core::convert::AsRef<str>, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> impl core::fmt::Debug for radroots_storage::workspace::local_outbox::LocalOutboxConfig pub fn radroots_storage::workspace::local_outbox::LocalOutboxConfig::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub mod radroots_storage::workspace::seller_stock +pub struct radroots_storage::workspace::seller_stock::SellerStockConfig +impl radroots_storage::workspace::seller_stock::SellerStockConfig +pub fn radroots_storage::workspace::seller_stock::SellerStockConfig::enroll(self, radroots_domain::context::UnixSeconds, radroots_domain::identifier::WorkspaceId, radroots_domain::identifier::ExecutorId, radroots_domain::identifier::GrantId, radroots_storage::workspace::AttachmentProof) -> core::result::Result<(radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof, radroots_storage::workspace::grant::WorkspaceGrant), radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage::workspace::seller_stock::SellerStockConfig::validate_at(&self, radroots_domain::context::UnixSeconds) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> +impl radroots_storage::workspace::seller_stock::SellerStockConfig +pub fn radroots_storage::workspace::seller_stock::SellerStockConfig::new(radroots_identity::key::PublicKey, radroots_identity::key::PublicKey, impl core::convert::AsRef<str>, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> +impl core::fmt::Debug for radroots_storage::workspace::seller_stock::SellerStockConfig +pub fn radroots_storage::workspace::seller_stock::SellerStockConfig::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result #[non_exhaustive] pub enum radroots_storage::workspace::WorkspaceError pub radroots_storage::workspace::WorkspaceError::Capacity pub radroots_storage::workspace::WorkspaceError::Closed diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -363,6 +363,7 @@ pub mod radroots_storage_sqlite::workspace pub use radroots_storage_sqlite::workspace::AttachmentInput pub use radroots_storage_sqlite::workspace::AttachmentProof pub use radroots_storage_sqlite::workspace::LocalOutboxConfig +pub use radroots_storage_sqlite::workspace::SellerStockConfig pub use radroots_storage_sqlite::workspace::WorkspaceBinding pub use radroots_storage_sqlite::workspace::WorkspaceClock pub use radroots_storage_sqlite::workspace::WorkspaceError @@ -374,6 +375,10 @@ pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::close(&self) - pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::initialize_local_outbox(&std::path::Path, radroots_storage::workspace::local_outbox::LocalOutboxConfig, radroots_storage_sqlite::workspace::WorkspaceCrypto, alloc::sync::Arc<dyn radroots_storage::workspace::WorkspaceClock>) -> core::result::Result<(Self, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof), radroots_storage::workspace::WorkspaceError> pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::open_existing(&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::revoke(&self, radroots_storage::workspace::AttachmentInput, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> +impl radroots_storage_sqlite::workspace::NativeWorkspace +pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::initialize_seller_stock(&std::path::Path, &radroots_storage_sqlite::workspace::StockEnrollment, 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::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 core::fmt::Debug for radroots_storage_sqlite::workspace::NativeWorkspace pub fn radroots_storage_sqlite::workspace::NativeWorkspace::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result impl radroots_storage::command::OperationJournal for radroots_storage_sqlite::workspace::NativeWorkspace @@ -395,6 +400,19 @@ pub fn radroots_storage_sqlite::workspace::NativeWorkspace::signing_plan(&self, impl radroots_storage::workspace::WorkspaceStore for radroots_storage_sqlite::workspace::NativeWorkspace pub fn radroots_storage_sqlite::workspace::NativeWorkspace::authenticate(&self, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::WorkspaceError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::close_workspace(&self) -> radroots_transport::source::BoxFuture<'_, core::result::Result<(), radroots_storage::workspace::WorkspaceError>> +pub struct radroots_storage_sqlite::workspace::StockAuthorityReceipt +impl radroots_storage_sqlite::workspace::StockAuthorityReceipt +pub fn radroots_storage_sqlite::workspace::StockAuthorityReceipt::input(&self) -> &radroots_storage::workspace::AttachmentInput +pub const fn radroots_storage_sqlite::workspace::StockAuthorityReceipt::revocation_generation(&self) -> radroots_domain::context::Sequence +pub const fn radroots_storage_sqlite::workspace::StockAuthorityReceipt::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 +pub fn radroots_storage_sqlite::workspace::StockEnrollment::prepare(radroots_storage::workspace::seller_stock::SellerStockConfig, &dyn radroots_storage::workspace::WorkspaceClock) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage_sqlite::workspace::StockEnrollment::proof(&self) -> &radroots_storage::workspace::AttachmentProof +pub const fn radroots_storage_sqlite::workspace::StockEnrollment::transaction_id(&self) -> radroots_domain::identifier::TransactionId +impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockEnrollment +pub fn radroots_storage_sqlite::workspace::StockEnrollment::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage_sqlite::workspace::WorkspaceCrypto impl radroots_storage_sqlite::workspace::WorkspaceCrypto pub fn radroots_storage_sqlite::workspace::WorkspaceCrypto::new(alloc::sync::Arc<dyn radroots_secrets::provider::SecretProvider>, radroots_secrets::id::SecretRef, radroots_secrets::wrapping::SecretMaterial, radroots_secrets::provider::AccessPolicy) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json @@ -68,6 +68,19 @@ "organization_or_delegation_authority": false, "existing_order_or_history_recovery": false }, + "native_seller_stock_authority": { + "scope": "seller_stock_owner", + "database": "stock_execution_v1.sqlite", + "lock": ".stock_execution_v1.lock", + "schema_version": 1, + "enrollment_prepared_before_durable_creation": true, + "prepared_enrollment_single_use": true, + "same_connection_owner_as_outbox": true, + "protected_authority_and_grants_separate": true, + "automatic_outbox_migration": false, + "historical_obligations_recovered": false, + "business_effects_qualified": false + }, "provenance": { "app_behavior_implementation": "independent_reimplementation", "retain_source_provenance": true, diff --git a/crates/storage/README.md b/crates/storage/README.md @@ -79,7 +79,10 @@ install an executor, spawn hidden workers, read a clock, generate identities, or perform implicit retries. The opt-in `protected_outbox` feature supplies pure local buyer/seller-outbox -enrollment and validated protected-grant codec at `workspace::local_outbox`. +enrollment at `workspace::local_outbox` and the validated shared protected-grant +codec at `workspace::grant`. The separate `workspace::seller_stock` policy +selects fresh stock-owner enrollment for a qualified native host; pure policy +values confer no durable authority. `LocalOutboxConfig::new` selects a fresh buyer outbox; `seller` explicitly selects a fresh seller public-authoring/communication outbox. Authenticated bindings retain that exact scope. Neither scope grants firm stock, delegation, diff --git a/crates/storage/src/workspace.rs b/crates/storage/src/workspace.rs @@ -14,6 +14,8 @@ use zeroize::Zeroizing; pub mod grant; #[cfg(feature = "protected_outbox")] pub mod local_outbox; +#[cfg(feature = "protected_outbox")] +pub mod seller_stock; /// A fixed workspace boundary error; no path, credential, SQL or caller prose. #[derive(Clone, Copy, Debug, Eq, PartialEq)] diff --git a/crates/storage/src/workspace/grant.rs b/crates/storage/src/workspace/grant.rs @@ -103,6 +103,10 @@ impl WorkspaceGrant { } Ok(record) } + /// Declared authenticated metadata; the concrete host still qualifies its scope. + pub const fn scope(&self) -> WorkspaceScope { + self.wire.scope + } pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>, WorkspaceError> { self.validate()?; let bytes = Zeroizing::new( diff --git a/crates/storage/src/workspace/seller_stock.rs b/crates/storage/src/workspace/seller_stock.rs @@ -0,0 +1,122 @@ +//! Explicit pure enrollment policy for a fresh seller stock authority. +//! No database, runtime, signer or provider is acquired here. +use super::{ + AttachmentInput, AttachmentProof, WorkspaceError, WorkspaceScope, grant::WorkspaceGrant, +}; +use radroots_domain::{ + ActorRef, AuthorityRef, CheckpointDigest, CheckpointRef, Coverage, ExecutorId, Generation, + GrantId, PublicKey, RouteDigest, Sequence, UnixSeconds, WorkspaceId, +}; +use sha2::{Digest, Sha256}; +/// Explicit local enrollment inputs, supplied by a trusted host interaction. +/// Only a qualified stock host may persist the resulting authority. +pub struct SellerStockConfig { + scope: WorkspaceScope, + participant: PublicKey, + endpoint_identity: PublicKey, + principal: String, + expires_at: UnixSeconds, +} +impl SellerStockConfig { + /// Selects fresh seller stock with participant, local application identity, + /// device audit label and positive expiry. This performs no authentication + /// or filesystem work. It never recovers existing obligations. + pub fn new( + participant: PublicKey, + endpoint_identity: PublicKey, + principal: impl AsRef<str>, + expires_at: UnixSeconds, + ) -> Result<Self, WorkspaceError> { + let principal = principal.as_ref(); + if principal.is_empty() + || principal.len() > 128 + || principal.chars().any(char::is_control) + || expires_at.get() == 0 + { + return Err(WorkspaceError::InvalidInput); + } + Ok(Self { + scope: WorkspaceScope::SellerStockOwner, + participant, + endpoint_identity, + principal: principal.to_owned(), + expires_at, + }) + } +} +impl std::fmt::Debug for SellerStockConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("SellerStockConfig(<redacted>)") + } +} + +impl SellerStockConfig { + /// Checks enrollment time without acquiring entropy or a host resource. + pub fn validate_at(&self, now: UnixSeconds) -> Result<(), WorkspaceError> { + if now.get() == 0 { + return Err(WorkspaceError::Unavailable); + } + if self.expires_at <= now { + return Err(WorkspaceError::GrantExpired); + } + Ok(()) + } + /// Pure trusted-host enrollment. Concrete hosts supply qualified fresh IDs + /// and a protected proof; this does not acquire or persist any authority. + pub fn enroll( + self, + now: UnixSeconds, + workspace: WorkspaceId, + executor: ExecutorId, + grant: GrantId, + proof: AttachmentProof, + ) -> Result<(AttachmentInput, AttachmentProof, WorkspaceGrant), WorkspaceError> { + self.validate_at(now)?; + let authority = AuthorityRef::new( + executor, + Generation::new(1).map_err(|_| WorkspaceError::InvalidInput)?, + ); + let endpoint = format!("local://seller-stock/{workspace}"); + let mut route = Sha256::new(); + route.update(self.scope.route_domain()); + route.update(workspace.as_bytes()); + route.update(executor.as_bytes()); + route.update(self.endpoint_identity.as_bytes()); + route.update(endpoint.as_bytes()); + let route = RouteDigest::from_bytes(route.finalize().into()); + let mut checkpoint = Sha256::new(); + checkpoint.update(self.scope.genesis_domain()); + checkpoint.update(workspace.as_bytes()); + checkpoint.update(executor.as_bytes()); + checkpoint.update(grant.as_bytes()); + // Genesis certifies only a fresh unrelated stock namespace. Partial coverage is + // deliberate: no old order, private history or inventory has been recovered. + let checkpoint = CheckpointRef::new( + CheckpointDigest::from_bytes(checkpoint.finalize().into()), + Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?, + Coverage::Partial, + vec![], + ) + .map_err(|_| WorkspaceError::InvalidInput)?; + let input = AttachmentInput::new( + workspace, + authority, + self.participant, + endpoint, + self.endpoint_identity, + grant, + checkpoint, + route, + )?; + let actor = ActorRef::new(self.participant, self.scope.actor_role(), None, Some(grant)); + let record = WorkspaceGrant::with_scope( + input.clone(), + self.scope, + actor, + self.principal, + self.expires_at, + &proof, + )?; + Ok((input, proof, record)) + } +} diff --git a/crates/storage_sqlite/README.md b/crates/storage_sqlite/README.md @@ -1,6 +1,6 @@ # radroots_storage_sqlite -The separate execution-workspace database creates exact schema generation 10. +The separate execution-workspace database creates exact outbox schema generation 11. Chat and initial `listing.publish` share the operation journal, protected preparation and owned bounded worker. Seller authentication and a retained T0 coordinate decision precede public issuance. A conflicting initial publish @@ -308,3 +308,32 @@ including null, remains immutable. Current-access snapshots fence the complete T0/T1/S/T2/D graph and all target observations before projecting bounded summaries. Reopen performs no publication. Ordinary library-owned inbox orchestration, browser/bindings, consumer adoption and final qualification remain separate work. + +## Fresh native seller stock authority + +`StockEnrollment::prepare` creates a one-shot unrelated fresh seller workspace selection, +protected credential and original creation transaction ID without touching the +namespace. Retain those values through protected host handling before awaiting +`NativeWorkspace::initialize_seller_stock`. This explicit factory uses +`stock_execution_v1.sqlite` and `.stock_execution_v1.lock` in a new owner-only +directory. Its exact version-1 catalog has separate protected authority and +grant records. Grant scope, route, genesis, credential and AEAD context are +separate from ordinary outboxes. The same bounded native worker owns the +connection, admitted work, close completion and persistent writer lock. + +Creation uses WAL, FULL synchronization, foreign keys and `BEGIN IMMEDIATE`. +Provider work completes outside the transaction. Use a local filesystem that +honors SQLite locking and synchronization; network filesystems and copied live +WAL sets are not qualified. Missing or malformed namespaces are never reset or +adopted. A failed or cancelled constructor is not evidence of absence: reopen +with `open_seller_stock` and query `stock_authority` with the original retained +selection and credential. The confirmed receipt preserves the original +transaction ID. Creation consumes the sole prepared grant before IO; that enrollment cannot +create a second authority namespace, including after caller cancellation. + +Authentication rechecks the protected current authority and grant. Revocation +atomically compares and replaces both protected snapshots and advances the +revocation generation. An uncertain commit fences further access on that +worker until close and explicit reopen. This enrollment boundary provides no +pool allocation, old-order recovery, transfer, signing or business confirmation; +ordinary outbox journal jobs are refused on the stock namespace. diff --git a/crates/storage_sqlite/src/workspace/crypto.rs b/crates/storage_sqlite/src/workspace/crypto.rs @@ -143,6 +143,32 @@ impl WorkspaceCrypto { ) .await } + pub(super) async fn seal_stock( + &self, + input: &super::AttachmentInput, + authority: bool, + plaintext: &[u8], + ) -> Result<Vec<u8>, WorkspaceError> { + self.seal_bound( + stock_context(input, authority)?, + PRIVATE_PAYLOAD_MAX_BYTES, + plaintext, + ) + .await + } + pub(super) async fn open_stock( + &self, + input: &super::AttachmentInput, + authority: bool, + protected: &[u8], + ) -> Result<SecretMaterial, WorkspaceError> { + self.open_bound( + stock_context(input, authority)?, + PRIVATE_PAYLOAD_MAX_BYTES, + protected, + ) + .await + } pub(super) async fn seal_operation( &self, workspace: WorkspaceId, @@ -563,3 +589,34 @@ fn listing_context(scope: ListingScope) -> Result<EnvelopeContext, WorkspaceErro PayloadSchemaId::parse(schema).map_err(|_| WorkspaceError::InvalidInput)?, )) } + +fn stock_context( + input: &super::AttachmentInput, + authority: bool, +) -> Result<EnvelopeContext, WorkspaceError> { + let (purpose, schema) = if authority { + ( + "radroots.seller_stock.authority", + "radroots.seller_stock.authority.v1", + ) + } else { + ( + "radroots.seller_stock.grant", + "radroots.seller_stock.grant.v1", + ) + }; + use sha2::{Digest, Sha256}; + let mut subject = Sha256::new(); + subject.update(b"radroots.seller_stock.context.v1\0"); + subject.update(input.workspace_id().as_bytes()); + subject.update(input.authority().executor_id().as_bytes()); + subject.update(input.authority().generation().get().to_be_bytes()); + subject.update(input.grant_id().as_bytes()); + let subject = radroots_domain::CommandDigest::from_bytes(subject.finalize().into()); + Ok(EnvelopeContext::new( + EnvelopePurpose::parse(purpose).map_err(|_| WorkspaceError::InvalidInput)?, + EnvelopeSubject::parse("seller_stock", subject.to_string()) + .map_err(|_| WorkspaceError::InvalidInput)?, + PayloadSchemaId::parse(schema).map_err(|_| WorkspaceError::InvalidInput)?, + )) +} diff --git a/crates/storage_sqlite/src/workspace/fs.rs b/crates/storage_sqlite/src/workspace/fs.rs @@ -9,19 +9,45 @@ use std::{ path::{Component, Path, PathBuf}, }; -const DATABASE: &str = "execution_v1.sqlite"; -const LOCK: &str = ".execution_v1.lock"; +#[derive(Clone, Copy, Eq, PartialEq)] +pub(super) enum Kind { + Outbox, + SellerStock, +} +impl Kind { + fn database(self) -> &'static str { + match self { + Self::Outbox => "execution_v1.sqlite", + Self::SellerStock => "stock_execution_v1.sqlite", + } + } + fn lock(self) -> &'static str { + match self { + Self::Outbox => ".execution_v1.lock", + Self::SellerStock => ".stock_execution_v1.lock", + } + } +} /// Retained identities and writer authority. The persistent lock inode is never /// unlinked on close, so another opener cannot lock a replacement inode. pub(super) struct Namespace { root: PathBuf, + kind: Kind, directory: File, lock: File, database: File, } impl Namespace { + #[cfg(test)] pub(super) fn acquire(root: &Path, create: bool) -> Result<Self, WorkspaceError> { + Self::acquire_kind(root, create, Kind::Outbox) + } + pub(super) fn acquire_kind( + root: &Path, + create: bool, + kind: Kind, + ) -> Result<Self, WorkspaceError> { validate_absolute(root)?; if create { std::fs::DirBuilder::new() @@ -49,7 +75,7 @@ impl Namespace { } else { OFlags::empty() }; - let lock: File = openat(&directory, LOCK, flags, Mode::RUSR | Mode::WUSR) + let lock: File = openat(&directory, kind.lock(), flags, Mode::RUSR | Mode::WUSR) .map_err(|_| WorkspaceError::NamespaceUnavailable)? .into(); validate_file(&lock)?; @@ -68,7 +94,7 @@ impl Namespace { WorkspaceError::NamespaceUnavailable } })?; - let database: File = openat(&directory, DATABASE, flags, Mode::RUSR | Mode::WUSR) + let database: File = openat(&directory, kind.database(), flags, Mode::RUSR | Mode::WUSR) .map_err(|_| WorkspaceError::NamespaceUnavailable)? .into(); validate_file(&database)?; @@ -93,6 +119,7 @@ impl Namespace { } let namespace = Self { root: root.to_path_buf(), + kind, directory, lock, database, @@ -100,8 +127,11 @@ impl Namespace { namespace.validate()?; Ok(namespace) } + pub(super) fn kind(&self) -> Kind { + self.kind + } pub(super) fn database_path(&self) -> PathBuf { - self.root.join(DATABASE) + self.root.join(self.kind.database()) } pub(super) fn validate(&self) -> Result<(), WorkspaceError> { validate_ancestors(&self.root)?; @@ -110,16 +140,15 @@ impl Namespace { for (index, entry) in entries.enumerate() { let entry = entry.map_err(|_| WorkspaceError::NamespaceUnavailable)?; if index >= 5 - || !matches!( - entry.file_name().to_str(), - Some( - "execution_v1.sqlite" - | ".execution_v1.lock" - | "execution_v1.sqlite-wal" - | "execution_v1.sqlite-shm" - | "execution_v1.sqlite-journal" - ) - ) + || ![ + self.kind.database().to_owned(), + self.kind.lock().to_owned(), + format!("{}-wal", self.kind.database()), + format!("{}-shm", self.kind.database()), + format!("{}-journal", self.kind.database()), + ] + .iter() + .any(|name| entry.file_name() == name.as_str()) { return Err(WorkspaceError::RecoveryRequired); } @@ -134,7 +163,10 @@ impl Namespace { if !root.is_dir() || root.file_type().is_symlink() || !same(&root, &retained) { return Err(WorkspaceError::NamespaceUnavailable); } - for (name, file) in [(DATABASE, &self.database), (LOCK, &self.lock)] { + for (name, file) in [ + (self.kind.database(), &self.database), + (self.kind.lock(), &self.lock), + ] { validate_file(file)?; let current = std::fs::symlink_metadata(self.root.join(name)) .map_err(|_| WorkspaceError::NamespaceUnavailable)?; @@ -146,7 +178,9 @@ impl Namespace { } } for suffix in ["-wal", "-shm", "-journal"] { - match std::fs::symlink_metadata(self.root.join(format!("{DATABASE}{suffix}"))) { + match std::fs::symlink_metadata( + self.root.join(format!("{}{suffix}", self.kind.database())), + ) { Ok(metadata) => validate_metadata(&metadata)?, Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(_) => return Err(WorkspaceError::NamespaceUnavailable), diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs @@ -1,6 +1,6 @@ -//! Explicit protected local buyer/seller-outbox attachment. +//! Explicit protected native outbox and fresh seller stock attachment. //! -//! This host cannot acquire seller stock authority, attach a remote endpoint, +//! Fresh stock enrollment is separate from outboxes. Neither can attach a remote endpoint, //! continue an existing order or restore state from a participant key. Its //! single connection and persistent writer lock belong to one bounded worker. //! Losing an observer never drops that lock ahead of the SQLite connection. @@ -21,6 +21,8 @@ mod record; mod recovery; mod schema; mod snapshot; +mod stock; +pub use stock::{SellerStockConfig, StockAuthorityReceipt, StockEnrollment}; mod worker; #[cfg(test)] diff --git a/crates/storage_sqlite/src/workspace/stock.rs b/crates/storage_sqlite/src/workspace/stock.rs @@ -0,0 +1,398 @@ +//! Fresh native stock authority. No allocation or issuance is implied by enrollment. +use super::{ + AttachmentInput, AttachmentProof, NativeWorkspace, WorkspaceBinding, WorkspaceClock, + WorkspaceCrypto, WorkspaceError, WorkspaceScope, fs::Namespace, record::GrantRecord, +}; +use radroots_domain::{ExecutorId, GrantId, Sequence, TransactionId, WorkspaceId}; +pub use radroots_storage::workspace::seller_stock::SellerStockConfig; +use serde::{Deserialize, Serialize}; +use sqlx::{Connection, SqliteConnection}; +use std::{ + path::Path, + sync::{Arc, Mutex}, +}; + +/// One-shot protected enrollment, retained before starting durable creation. A lost +/// observer must reopen its original selection, never silently create a replacement. +pub struct StockEnrollment { + input: AttachmentInput, + proof: AttachmentProof, + record: Mutex<Option<GrantRecord>>, + transaction: TransactionId, +} +impl StockEnrollment { + pub fn prepare( + config: SellerStockConfig, + clock: &dyn WorkspaceClock, + ) -> Result<Self, WorkspaceError> { + let now = clock.now()?; + config.validate_at(now)?; + let secret = zeroize::Zeroizing::new(super::random()?); + let proof = AttachmentProof::from_protected_input(secret.as_ref())?; + let (input, proof, record) = config.enroll( + now, + WorkspaceId::from_bytes(super::random()?), + ExecutorId::from_bytes(super::random()?), + GrantId::from_bytes(super::random()?), + proof, + )?; + Ok(Self { + input, + proof, + record: Mutex::new(Some(record)), + transaction: TransactionId::from_bytes(super::random()?), + }) + } + pub fn input(&self) -> &AttachmentInput { + &self.input + } + pub fn proof(&self) -> &AttachmentProof { + &self.proof + } + pub const fn transaction_id(&self) -> TransactionId { + self.transaction + } +} +impl std::fmt::Debug for StockEnrollment { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("StockEnrollment(<redacted>)") + } +} +/// A confirmed creation identity read from protected durable state. This is +/// enrollment evidence, not proof of any stock quantity or business operation. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct StockAuthorityReceipt { + pub(super) input: AttachmentInput, + pub(super) transaction: TransactionId, + pub(super) revocation: Sequence, +} +impl StockAuthorityReceipt { + pub fn input(&self) -> &AttachmentInput { + &self.input + } + pub const fn transaction_id(&self) -> TransactionId { + self.transaction + } + pub const fn revocation_generation(&self) -> Sequence { + self.revocation + } +} +impl NativeWorkspace { + pub async fn initialize_seller_stock( + path: &Path, + enrollment: &StockEnrollment, + crypto: WorkspaceCrypto, + clock: Arc<dyn WorkspaceClock>, + ) -> Result<Self, WorkspaceError> { + // Taking the sole prepared grant is irreversible, even if this observer + // disappears. Retained selectors/proof permit reopening, never cloning authority. + let record = { + enrollment + .record + .lock() + .map_err(|_| WorkspaceError::Unavailable)? + .take() + .ok_or(WorkspaceError::RecoveryRequired)? + }; + let binding = record.authenticate(&enrollment.input, &enrollment.proof, clock.now()?)?; + let worker = super::worker::Handle::launch_stock( + path.to_path_buf(), + enrollment.input.clone(), + Some((record, enrollment.transaction, binding.expires_at())), + crypto, + clock, + ) + .await?; + Ok(Self { + worker: Arc::new(worker), + }) + } + pub async fn open_seller_stock( + path: &Path, + expected: AttachmentInput, + crypto: WorkspaceCrypto, + clock: Arc<dyn WorkspaceClock>, + ) -> Result<Self, WorkspaceError> { + let worker = + super::worker::Handle::launch_stock(path.to_path_buf(), expected, None, crypto, clock) + .await?; + Ok(Self { + worker: Arc::new(worker), + }) + } + /// Query after an interrupted creation using the retained original selection. + pub async fn stock_authority( + &self, + input: AttachmentInput, + proof: &AttachmentProof, + ) -> Result<StockAuthorityReceipt, WorkspaceError> { + let proof = proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?; + self.worker.stock_authority(input, proof).await + } +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Authority { + version: u8, + input: AttachmentInput, + transaction: TransactionId, + revocation: Sequence, +} +pub(super) struct Initial { + pub grant: GrantRecord, + pub transaction: TransactionId, + pub expires_at: radroots_domain::UnixSeconds, + pub clock: Arc<dyn WorkspaceClock>, +} +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 CATALOG: [&str; 2] = [AUTHORITY, GRANTS]; +async fn catalog(connection: &mut SqliteConnection) -> Result<(), WorkspaceError> { + let valid: i64 = sqlx::query_scalar("SELECT CASE WHEN count(*)=2 AND sum(CASE WHEN type='table' AND name='stock_authority' AND tbl_name='stock_authority' AND sql=? THEN 1 WHEN type='table' AND name='stock_grants' AND tbl_name='stock_grants' AND sql=? THEN 1 ELSE 0 END)=2 THEN 1 ELSE 0 END FROM sqlite_schema").bind(AUTHORITY).bind(GRANTS).fetch_one(&mut *connection).await.map_err(|_| WorkspaceError::RecoveryRequired)?; + let version: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&mut *connection) + .await + .map_err(|_| WorkspaceError::RecoveryRequired)?; + if valid != 1 || version != 1 { + return Err(WorkspaceError::RecoveryRequired); + } + let integrity: String = sqlx::query_scalar("PRAGMA quick_check(1)") + .fetch_one(connection) + .await + .map_err(|_| WorkspaceError::RecoveryRequired)?; + if integrity != "ok" { + return Err(WorkspaceError::RecoveryRequired); + } + Ok(()) +} +pub(super) async fn initialize( + connection: &mut SqliteConnection, + namespace: &Namespace, + input: &AttachmentInput, + initial: Option<Initial>, + crypto: &WorkspaceCrypto, +) -> Result<(), WorkspaceError> { + namespace.validate()?; + if let Some(initial) = initial { + let authority = Authority { + version: 1, + input: input.clone(), + transaction: initial.transaction, + revocation: Sequence::new(1).map_err(|_| WorkspaceError::InvalidInput)?, + }; + let clear = zeroize::Zeroizing::new( + serde_json::to_vec(&authority).map_err(|_| WorkspaceError::StorageFailure)?, + ); + let root = crypto.seal_stock(input, true, &clear).await?; + let grant = crypto + .seal_stock(input, false, &initial.grant.encode()?) + .await?; + let now = initial.clock.now()?; + if now.get() == 0 { + return Err(WorkspaceError::Unavailable); + } + if now >= initial.expires_at { + return Err(WorkspaceError::GrantExpired); + } + let mut tx = connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + let changed: Result<(), WorkspaceError> = async { + namespace.validate()?; + let now = initial.clock.now()?; + if now.get() == 0 { + return Err(WorkspaceError::Unavailable); + } + if now >= initial.expires_at { + return Err(WorkspaceError::GrantExpired); + } + for sql in CATALOG { + sqlx::raw_sql(sql) + .execute(&mut *tx) + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + } + sqlx::query("PRAGMA user_version=1") + .execute(&mut *tx) + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + sqlx::query("INSERT INTO stock_authority(singleton,protected) VALUES(1,?)") + .bind(root) + .execute(&mut *tx) + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + sqlx::query("INSERT INTO stock_grants(grant_id,protected) VALUES(?,?)") + .bind(input.grant_id().as_bytes().as_slice()) + .bind(grant) + .execute(&mut *tx) + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + Ok(()) + } + .await; + if let Err(error) = changed { + tx.rollback() + .await + .map_err(|_| WorkspaceError::CommitUnknown)?; + return Err(error); + } + tx.commit() + .await + .map_err(|_| WorkspaceError::CommitUnknown)?; + } + catalog(connection).await?; + read(connection, input, crypto).await?; + namespace.validate() +} +async fn read( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, +) -> Result<(Authority, GrantRecord, Vec<u8>, Vec<u8>), WorkspaceError> { + // Bound in SQL before materializing attacker-controlled protected payloads. + let root: Vec<u8> = sqlx::query_scalar("SELECT protected FROM stock_authority WHERE singleton=1 AND length(protected) BETWEEN 1 AND 262144").fetch_optional(&mut *connection).await.map_err(|_| WorkspaceError::RecoveryRequired)?.ok_or(WorkspaceError::RecoveryRequired)?; + let grant: Vec<u8> = sqlx::query_scalar("SELECT protected FROM stock_grants WHERE grant_id=? AND length(protected) BETWEEN 1 AND 262144").bind(input.grant_id().as_bytes().as_slice()).fetch_optional(&mut *connection).await.map_err(|_| WorkspaceError::RecoveryRequired)?.ok_or(WorkspaceError::WrongNamespace)?; + let clear = crypto.open_stock(input, true, &root).await?; + let authority: Authority = clear + .expose_secret(|bytes| serde_json::from_slice(bytes)) + .map_err(|_| WorkspaceError::RecoveryRequired)?; + if authority.version != 1 || authority.input != *input || authority.revocation.get() == 0 { + return Err(WorkspaceError::WrongNamespace); + } + let clear = crypto.open_stock(input, false, &grant).await?; + let record = clear.expose_secret(GrantRecord::decode)?; + // Validate the protected scope without inventing possession of its credential. + if record.scope() != WorkspaceScope::SellerStockOwner { + return Err(WorkspaceError::RecoveryRequired); + } + Ok((authority, record, root, grant)) +} +pub(super) async fn authenticate( + connection: &mut SqliteConnection, + namespace: &Namespace, + expected: &AttachmentInput, + crypto: &WorkspaceCrypto, + clock: &dyn WorkspaceClock, + selected: &AttachmentInput, + proof: &AttachmentProof, +) -> Result<(StockAuthorityReceipt, WorkspaceBinding), WorkspaceError> { + namespace.validate()?; + let (authority, record, root, grant) = read(connection, expected, crypto).await?; + record.authenticate(selected, proof, clock.now()?)?; + let mut tx = connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + let checked = async { + namespace.validate()?; + unchanged(&mut tx, expected, &root, &grant).await?; + record.authenticate(selected, proof, clock.now()?) + } + .await; + tx.rollback() + .await + .map_err(|_| WorkspaceError::CommitUnknown)?; + let binding = checked?; + if binding.scope() != WorkspaceScope::SellerStockOwner { + return Err(WorkspaceError::RecoveryRequired); + } + namespace.validate()?; + Ok(( + StockAuthorityReceipt { + input: authority.input, + transaction: authority.transaction, + revocation: authority.revocation, + }, + binding, + )) +} +pub(super) async fn revoke( + connection: &mut SqliteConnection, + namespace: &Namespace, + expected: &AttachmentInput, + crypto: &WorkspaceCrypto, + clock: &dyn WorkspaceClock, + selected: &AttachmentInput, + proof: &AttachmentProof, +) -> Result<(), WorkspaceError> { + namespace.validate()?; + let (mut authority, mut record, old_root, old_grant) = + read(connection, expected, crypto).await?; + let expiry = record + .authenticate(selected, proof, clock.now()?)? + .expires_at(); + record.revoke()?; + authority.revocation = Sequence::new( + authority + .revocation + .get() + .checked_add(1) + .ok_or(WorkspaceError::Capacity)?, + ) + .map_err(|_| WorkspaceError::Capacity)?; + let clear = zeroize::Zeroizing::new( + serde_json::to_vec(&authority).map_err(|_| WorkspaceError::StorageFailure)?, + ); + let root = crypto.seal_stock(expected, true, &clear).await?; + let grant = crypto + .seal_stock(expected, false, &record.encode()?) + .await?; + namespace.validate()?; + let mut tx = connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + let changed: Result<(), WorkspaceError> = async { + // Current clock and both exact protected snapshots fence the write after provider IO. + record.authenticate_retained_capture(selected, proof)?; + let now = clock.now()?; + if now.get() == 0 { + return Err(WorkspaceError::Unavailable); + } + if now >= expiry { + return Err(WorkspaceError::GrantExpired); + } + let a = + sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?") + .bind(root) + .bind(old_root) + .execute(&mut *tx) + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + let g = sqlx::query("UPDATE stock_grants SET protected=? WHERE grant_id=? AND protected=?") + .bind(grant) + .bind(expected.grant_id().as_bytes().as_slice()) + .bind(old_grant) + .execute(&mut *tx) + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + if a.rows_affected() != 1 || g.rows_affected() != 1 { + return Err(WorkspaceError::RecoveryRequired); + } + namespace.validate()?; + Ok(()) + } + .await; + if let Err(error) = changed { + tx.rollback() + .await + .map_err(|_| WorkspaceError::CommitUnknown)?; + return Err(error); + } + tx.commit().await.map_err(|_| WorkspaceError::CommitUnknown) +} + +async fn unchanged( + connection: &mut SqliteConnection, + input: &AttachmentInput, + root: &[u8], + grant: &[u8], +) -> Result<(), WorkspaceError> { + let matched: i64 = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM stock_authority WHERE singleton=1 AND protected=?) AND EXISTS(SELECT 1 FROM stock_grants WHERE grant_id=? AND protected=?)") + .bind(root).bind(input.grant_id().as_bytes().as_slice()).bind(grant).fetch_one(connection).await.map_err(|_| WorkspaceError::StorageFailure)?; + if matched != 1 { + return Err(WorkspaceError::RecoveryRequired); + } + Ok(()) +} diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -1,6 +1,10 @@ use super::{ AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceCrypto, - WorkspaceError, admission::Journal, fs::Namespace, record::GrantRecord, schema, + WorkspaceError, + admission::Journal, + fs::{Kind, Namespace}, + record::GrantRecord, + schema, stock, }; use radroots_domain::{CommandDigest, OperationId}; use radroots_storage::command::{ @@ -34,6 +38,11 @@ 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 { + StockAuthority( + AttachmentInput, + AttachmentProof, + Reply<super::StockAuthorityReceipt>, + ), CaptureDeliveryObservation( Box<WorkspaceBinding>, AttachmentProof, @@ -134,6 +143,9 @@ enum Job { impl Job { fn reject_recovery(self) { match self { + Self::StockAuthority(_, _, reply) => { + let _ = reply.send(Err(WorkspaceError::RecoveryRequired)); + } Self::CaptureDeliveryObservation(_, _, _, reply) => { let _ = reply.send(Err(OperationError::RecoveryRequired)); } @@ -212,6 +224,37 @@ impl Handle { crypto: WorkspaceCrypto, clock: Arc<dyn WorkspaceClock>, ) -> Result<Self, WorkspaceError> { + Self::launch_kind(path, input, initial, None, Kind::Outbox, crypto, clock).await + } + pub(super) async fn launch_stock( + path: PathBuf, + input: AttachmentInput, + initial: Option<( + GrantRecord, + radroots_domain::TransactionId, + radroots_domain::UnixSeconds, + )>, + crypto: WorkspaceCrypto, + clock: Arc<dyn WorkspaceClock>, + ) -> Result<Self, WorkspaceError> { + let initial = initial.map(|(grant, transaction, expires_at)| stock::Initial { + grant, + transaction, + expires_at, + clock: clock.clone(), + }); + Self::launch_kind(path, input, None, initial, Kind::SellerStock, crypto, clock).await + } + async fn launch_kind( + path: PathBuf, + input: AttachmentInput, + initial: Option<GrantRecord>, + stock_initial: Option<stock::Initial>, + kind: Kind, + crypto: WorkspaceCrypto, + clock: Arc<dyn WorkspaceClock>, + ) -> Result<Self, WorkspaceError> { + let creating = initial.is_some() || stock_initial.is_some(); let (sender, requests) = mpsc::sync_channel::<Queued>(QUEUE_CAPACITY); let queued_bytes = Arc::new(AtomicUsize::new(0)); let (ready, started) = oneshot::channel(); @@ -232,7 +275,7 @@ impl Handle { }; // Construction, every request and explicit close complete on this // owner even when an async observer disappears between await points. - let namespace = match Namespace::acquire(&path, initial.is_some()) { + let namespace = match Namespace::acquire_kind(&path, creating, kind) { Ok(namespace) => namespace, Err(error) => { let _ = ready.send(Err(error)); @@ -241,7 +284,7 @@ impl Handle { } }; let result = runtime.block_on(async { - if initial.is_none() { + if !creating { let preflight = preflight_existing(&namespace, &input, &crypto).await; if let Err(error) = preflight { let _ = ready.send(Err(error)); @@ -262,8 +305,21 @@ impl Handle { return Err(WorkspaceError::StorageFailure); } }; - let initialized = - initialize(&mut connection, &namespace, &input, initial, &crypto).await; + let initialized = match kind { + Kind::Outbox => { + initialize(&mut connection, &namespace, &input, initial, &crypto).await + } + Kind::SellerStock => { + stock::initialize( + &mut connection, + &namespace, + &input, + stock_initial, + &crypto, + ) + .await + } + }; if let Err(error) = initialized { let _ = ready.send(Err(error)); // Do not release namespace authority at the first failure; @@ -276,6 +332,17 @@ impl Handle { let mut connection = Some(connection); if ready.send(Ok(())).is_ok() { while let Ok(Queued { job, _budget }) = requests.recv() { + if kind == Kind::SellerStock + && !matches!( + &job, + Job::Authenticate(..) + | Job::Revoke(..) + | Job::StockAuthority(..) + ) + { + job.reject_recovery(); + continue; + } let job = match job { Job::RecoverCapture(selected, proof, evidence, reply) => { let result = super::recovery::RecoveryTurn { @@ -300,6 +367,27 @@ impl Handle { continue; }; match job { + Job::StockAuthority(selected, proof, reply) => { + let result = if kind == Kind::SellerStock && !uncertain { + stock::authenticate( + connection, + &namespace, + &input, + &crypto, + clock.as_ref(), + &selected, + &proof, + ) + .await + .map(|(receipt, _)| receipt) + } else { + Err(WorkspaceError::RecoveryRequired) + }; + if result == Err(WorkspaceError::CommitUnknown) { + uncertain = true; + } + let _ = reply.send(result); + } job @ Job::RecoverCapture(..) => job.reject_recovery(), Job::CaptureDeliveryObservation( binding, @@ -487,30 +575,67 @@ impl Handle { let _ = reply.send(result); } Job::Authenticate(selected, proof, reply) => { - let result = authenticate( - connection, - &namespace, - &input, - &crypto, - clock.as_ref(), - &selected, - &proof, - ) - .await - .map(|(_, binding)| binding); + let result = if uncertain { + Err(WorkspaceError::RecoveryRequired) + } else if kind == Kind::SellerStock { + stock::authenticate( + connection, + &namespace, + &input, + &crypto, + clock.as_ref(), + &selected, + &proof, + ) + .await + .map(|(_, binding)| binding) + } else { + authenticate( + connection, + &namespace, + &input, + &crypto, + clock.as_ref(), + &selected, + &proof, + ) + .await + .map(|(_, binding)| binding) + }; + if result == Err(WorkspaceError::CommitUnknown) { + uncertain = true; + } let _ = reply.send(result); } Job::Revoke(selected, proof, reply) => { - let result = revoke( - connection, - &namespace, - &input, - &crypto, - clock.as_ref(), - &selected, - &proof, - ) - .await; + let result = if uncertain { + Err(WorkspaceError::RecoveryRequired) + } else if kind == Kind::SellerStock { + stock::revoke( + connection, + &namespace, + &input, + &crypto, + clock.as_ref(), + &selected, + &proof, + ) + .await + } else { + revoke( + connection, + &namespace, + &input, + &crypto, + clock.as_ref(), + &selected, + &proof, + ) + .await + }; + if result == Err(WorkspaceError::CommitUnknown) { + uncertain = true; + } let _ = reply.send(result); } Job::Admit(request, proof, reply) => { @@ -581,6 +706,15 @@ impl Handle { } } } + pub(super) async fn stock_authority( + &self, + input: AttachmentInput, + proof: AttachmentProof, + ) -> Result<super::StockAuthorityReceipt, WorkspaceError> { + let (reply, result) = oneshot::channel(); + self.send(Job::StockAuthority(input, proof, reply))?; + result.await.map_err(|_| WorkspaceError::RecoveryRequired)? + } fn send(&self, job: Job) -> Result<(), WorkspaceError> { let bytes = match &job { Job::CaptureDeliveryObservation(..) => 96 * 1024, @@ -944,7 +1078,12 @@ pub(super) async fn preflight_existing( let mut connection = SqliteConnection::connect_with(&options) .await .map_err(|_| WorkspaceError::RecoveryRequired)?; - let inspected = initialize(&mut connection, namespace, expected, None, crypto).await; + let inspected = match namespace.kind() { + Kind::Outbox => initialize(&mut connection, namespace, expected, None, crypto).await, + Kind::SellerStock => { + stock::initialize(&mut connection, namespace, expected, None, crypto).await + } + }; let closed = connection .close() .await diff --git a/crates/storage_sqlite/tests/support/stock_authority.rs b/crates/storage_sqlite/tests/support/stock_authority.rs @@ -0,0 +1,512 @@ +use super::*; +use radroots_storage::workspace::WorkspaceScope; +use radroots_storage_sqlite::workspace::{SellerStockConfig, StockEnrollment}; +use sqlx::Connection; +fn enrollment(f: &Fixture) -> StockEnrollment { + StockEnrollment::prepare( + SellerStockConfig::new( + key(), + key(), + "stock-owner-device", + UnixSeconds::new(200).unwrap(), + ) + .unwrap(), + f.clock.as_ref(), + ) + .unwrap() +} +async fn create(f: &Fixture, e: &StockEnrollment) -> NativeWorkspace { + NativeWorkspace::initialize_seller_stock(&f.path, e, f.crypto(), f.clock.clone()) + .await + .unwrap() +} +async fn reopen(f: &Fixture, e: &StockEnrollment) -> NativeWorkspace { + NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone()) + .await + .unwrap() +} +#[tokio::test] +async fn explicit_stock_creation_has_retained_receipt_and_reopens() { + let f = Fixture::new(); + let e = enrollment(&f); + assert!(!f.path.exists()); + let store = create(&f, &e).await; + let binding = store + .authenticate(e.input().clone(), e.proof()) + .await + .unwrap(); + assert_eq!(binding.scope(), WorkspaceScope::SellerStockOwner); + assert_eq!(binding.actor().role(), radroots_domain::ActorRole::Seller); + let receipt = store + .stock_authority(e.input().clone(), e.proof()) + .await + .unwrap(); + assert_eq!(receipt.input(), e.input()); + assert_eq!(receipt.transaction_id(), e.transaction_id()); + assert_eq!(receipt.revocation_generation().get(), 1); + assert!(f.path.join("stock_execution_v1.sqlite").exists()); + assert!(!f.path.join("execution_v1.sqlite").exists()); + store.close().await.unwrap(); + let store = reopen(&f, &e).await; + assert_eq!( + store + .stock_authority(e.input().clone(), e.proof()) + .await + .unwrap(), + receipt + ); + store.close().await.unwrap(); +} +#[tokio::test] +async fn proof_expiry_revocation_and_wrong_selection_are_current() { + let f = Fixture::new(); + let e = enrollment(&f); + let store = create(&f, &e).await; + let wrong = AttachmentProof::from_protected_input(&[0xAB; 32]).unwrap(); + assert_eq!( + store.authenticate(e.input().clone(), &wrong).await, + Err(WorkspaceError::Unauthorized) + ); + for field in 0..9 { + assert!( + store + .authenticate(altered(e.input(), field), e.proof()) + .await + .is_err() + ); + } + f.clock.0.store(200, Ordering::SeqCst); + assert_eq!( + store.authenticate(e.input().clone(), e.proof()).await, + Err(WorkspaceError::GrantExpired) + ); + f.clock.0.store(100, Ordering::SeqCst); + store.revoke(e.input().clone(), e.proof()).await.unwrap(); + assert_eq!( + store.authenticate(e.input().clone(), e.proof()).await, + Err(WorkspaceError::GrantRevoked) + ); + store.close().await.unwrap(); + let store = reopen(&f, &e).await; + assert_eq!( + store.authenticate(e.input().clone(), e.proof()).await, + Err(WorkspaceError::GrantRevoked) + ); + store.close().await.unwrap(); +} +#[tokio::test] +async fn stock_and_outbox_factories_never_adopt_or_reset_one_another() { + let f = Fixture::new(); + let e = enrollment(&f); + let store = create(&f, &e).await; + assert!(matches!( + NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone()) + .await, + Err(WorkspaceError::WriterActive) + )); + store.close().await.unwrap(); + let database = f.path.join("stock_execution_v1.sqlite"); + let before = std::fs::read(&database).unwrap(); + assert!( + NativeWorkspace::open_existing(&f.path, e.input().clone(), f.crypto(), f.clock.clone()) + .await + .is_err() + ); + assert!( + NativeWorkspace::initialize_local_outbox(&f.path, f.config(), f.crypto(), f.clock.clone()) + .await + .is_err() + ); + assert!( + NativeWorkspace::initialize_seller_stock(&f.path, &e, f.crypto(), f.clock.clone()) + .await + .is_err() + ); + assert_eq!(std::fs::read(&database).unwrap(), before); + let g = Fixture::new(); + let (outbox, input, _) = g.create().await; + outbox.close().await.unwrap(); + let database = g.path.join("execution_v1.sqlite"); + let before = std::fs::read(&database).unwrap(); + assert!( + NativeWorkspace::open_seller_stock(&g.path, input, g.crypto(), g.clock.clone()) + .await + .is_err() + ); + assert_eq!(std::fs::read(&database).unwrap(), before); +} +#[tokio::test] +async fn protected_key_and_every_selection_field_refuse_without_writes() { + let f = Fixture::new(); + let e = enrollment(&f); + let store = create(&f, &e).await; + store.close().await.unwrap(); + let database = f.path.join("stock_execution_v1.sqlite"); + let before = std::fs::read(&database).unwrap(); + assert!( + NativeWorkspace::open_seller_stock( + &f.path, + e.input().clone(), + f.crypto_with([0x99; 32]), + f.clock.clone() + ) + .await + .is_err() + ); + for field in 0..9 { + assert!( + NativeWorkspace::open_seller_stock( + &f.path, + altered(e.input(), field), + f.crypto(), + f.clock.clone() + ) + .await + .is_err() + ); + } + assert_eq!(std::fs::read(&database).unwrap(), before); +} +#[tokio::test] +async fn stock_catalog_and_protected_record_corruption_are_never_repaired() { + for sql in [ + "PRAGMA user_version=2", + "CREATE TABLE unexpected(value INTEGER)", + "CREATE TRIGGER foreign_trigger BEFORE INSERT ON stock_grants BEGIN SELECT RAISE(ABORT,'fault'); END", + "UPDATE stock_authority SET protected=zeroblob(64)", + "UPDATE stock_grants SET protected=zeroblob(64)", + "DELETE FROM stock_grants", + ] { + let f = Fixture::new(); + let e = enrollment(&f); + let store = create(&f, &e).await; + store.close().await.unwrap(); + let database = f.path.join("stock_execution_v1.sqlite"); + let mut connection = sqlx::SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new().filename(&database), + ) + .await + .unwrap(); + sqlx::raw_sql(sql).execute(&mut connection).await.unwrap(); + connection.close().await.unwrap(); + let before = std::fs::read(&database).unwrap(); + assert!( + NativeWorkspace::open_seller_stock( + &f.path, + e.input().clone(), + f.crypto(), + f.clock.clone() + ) + .await + .is_err(), + "{sql}" + ); + assert_eq!(std::fs::read(&database).unwrap(), before); + } +} +#[tokio::test] +async fn cancelled_stock_revocation_drains_then_remains_revoked() { + let f = Fixture::new(); + let e = enrollment(&f); + let clock = Arc::new(PausedClock { + state: std::sync::Mutex::new((false, false, false)), + changed: std::sync::Condvar::new(), + }); + let store = NativeWorkspace::initialize_seller_stock(&f.path, &e, f.crypto(), clock.clone()) + .await + .unwrap(); + clock.arm(); + let mut revoked = Box::pin(store.revoke(e.input().clone(), e.proof())); + assert!(futures::poll!(revoked.as_mut()).is_pending()); + clock.entered(); + drop(revoked); + let mut closing = Box::pin(store.close()); + assert!(futures::poll!(closing.as_mut()).is_pending()); + drop(closing); + assert!(matches!( + NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone()) + .await, + Err(WorkspaceError::WriterActive) + )); + clock.release(); + store.close().await.unwrap(); + let store = reopen(&f, &e).await; + assert_eq!( + store.authenticate(e.input().clone(), e.proof()).await, + Err(WorkspaceError::GrantRevoked) + ); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn actual_commit_error_fences_the_owner_until_original_state_reopens() { + let f = Fixture::new(); + let e = enrollment(&f); + let store = create(&f, &e).await; + let database = f.path.join("stock_execution_v1.sqlite"); + let mut connection = sqlx::SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new().filename(&database), + ) + .await + .unwrap(); + sqlx::raw_sql("CREATE TABLE deferred_fault(value INTEGER REFERENCES stock_authority(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_commit AFTER UPDATE ON stock_grants BEGIN INSERT INTO deferred_fault VALUES(2); END").execute(&mut connection).await.unwrap(); + assert_eq!( + store.revoke(e.input().clone(), e.proof()).await, + Err(WorkspaceError::CommitUnknown) + ); + assert_eq!( + store.authenticate(e.input().clone(), e.proof()).await, + Err(WorkspaceError::RecoveryRequired) + ); + assert_eq!( + store.stock_authority(e.input().clone(), e.proof()).await, + Err(WorkspaceError::RecoveryRequired) + ); + store.close().await.unwrap(); + sqlx::raw_sql("DROP TRIGGER fail_commit; DROP TABLE deferred_fault") + .execute(&mut connection) + .await + .unwrap(); + connection.close().await.unwrap(); + let store = reopen(&f, &e).await; + let receipt = store + .stock_authority(e.input().clone(), e.proof()) + .await + .unwrap(); + assert_eq!(receipt.transaction_id(), e.transaction_id()); + assert_eq!(receipt.revocation_generation().get(), 1); + store + .authenticate(e.input().clone(), e.proof()) + .await + .unwrap(); + store.close().await.unwrap(); +} +struct CreationClock { + calls: AtomicU64, + paused: PausedClock, +} +impl WorkspaceClock for CreationClock { + fn now(&self) -> Result<UnixSeconds, WorkspaceError> { + if self.calls.fetch_add(1, Ordering::SeqCst) == 1 { + self.paused.arm(); + self.paused.now() + } else { + Ok(UnixSeconds::new(100).unwrap()) + } + } +} +#[tokio::test] +async fn lost_creation_observer_recovers_original_prepared_identity() { + let f = Fixture::new(); + let e = enrollment(&f); + let clock = Arc::new(CreationClock { + calls: AtomicU64::new(0), + paused: PausedClock { + state: std::sync::Mutex::new((false, false, false)), + changed: std::sync::Condvar::new(), + }, + }); + let mut creation = Box::pin(NativeWorkspace::initialize_seller_stock( + &f.path, + &e, + f.crypto(), + clock.clone(), + )); + assert!(futures::poll!(creation.as_mut()).is_pending()); + clock.paused.entered(); + drop(creation); + assert!(matches!( + NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone()) + .await, + Err(WorkspaceError::WriterActive) + )); + clock.paused.release(); + // The first observer owns no handle after cancellation. The worker still + // commits and explicitly closes its connection before releasing authority. + // Observe the actual persistent writer-ownership transition. Attempt counts + // cannot establish completion on a slower scheduler or emulated target. + let lock = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(f.path.join(".stock_execution_v1.lock")) + .unwrap(); + fs2::FileExt::lock_exclusive(&lock).unwrap(); + fs2::FileExt::unlock(&lock).unwrap(); + drop(lock); + let store = reopen(&f, &e).await; + let receipt = store + .stock_authority(e.input().clone(), e.proof()) + .await + .unwrap(); + assert_eq!(receipt.transaction_id(), e.transaction_id()); + assert_eq!(receipt.input(), e.input()); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn ordinary_journal_is_not_a_stock_transaction_path() { + use radroots_storage::command::{OperationError, OperationJournal}; + let f = Fixture::new(); + let e = enrollment(&f); + let store = create(&f, &e).await; + let binding = store + .authenticate(e.input().clone(), e.proof()) + .await + .unwrap(); + let proof = e + .proof() + .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) + .unwrap(); + assert!(matches!( + store + .operation( + binding, + radroots_domain::OperationId::from_bytes([1; 32]), + None, + proof + ) + .await, + Err(OperationError::RecoveryRequired) + )); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn changed_protected_grant_after_decryption_is_refused_before_binding() { + let f = Fixture::new(); + let e = enrollment(&f); + let clock = Arc::new(PausedClock { + state: std::sync::Mutex::new((false, false, false)), + changed: std::sync::Condvar::new(), + }); + let store = NativeWorkspace::initialize_seller_stock(&f.path, &e, f.crypto(), clock.clone()) + .await + .unwrap(); + clock.arm(); + let mut auth = Box::pin(store.authenticate(e.input().clone(), e.proof())); + assert!(futures::poll!(auth.as_mut()).is_pending()); + clock.entered(); + let mut connection = sqlx::SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .filename(f.path.join("stock_execution_v1.sqlite")), + ) + .await + .unwrap(); + sqlx::query("UPDATE stock_grants SET protected=zeroblob(64)") + .execute(&mut connection) + .await + .unwrap(); + connection.close().await.unwrap(); + clock.release(); + assert_eq!(auth.await, Err(WorkspaceError::RecoveryRequired)); + store.close().await.unwrap(); +} +#[tokio::test] +async fn statement_failure_rolls_back_both_revocation_records() { + let f = Fixture::new(); + let e = enrollment(&f); + let store = create(&f, &e).await; + let mut connection = sqlx::SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .filename(f.path.join("stock_execution_v1.sqlite")), + ) + .await + .unwrap(); + sqlx::raw_sql("CREATE TRIGGER fail_revocation BEFORE UPDATE ON stock_grants BEGIN SELECT RAISE(ABORT,'fault'); END").execute(&mut connection).await.unwrap(); + assert_eq!( + store.revoke(e.input().clone(), e.proof()).await, + Err(WorkspaceError::StorageFailure) + ); + let receipt = store + .stock_authority(e.input().clone(), e.proof()) + .await + .unwrap(); + assert_eq!(receipt.revocation_generation().get(), 1); + sqlx::raw_sql("DROP TRIGGER fail_revocation") + .execute(&mut connection) + .await + .unwrap(); + connection.close().await.unwrap(); + store.close().await.unwrap(); + let store = reopen(&f, &e).await; + store + .authenticate(e.input().clone(), e.proof()) + .await + .unwrap(); + store.close().await.unwrap(); +} + +struct ExpiringCreationClock(AtomicU64); +impl WorkspaceClock for ExpiringCreationClock { + fn now(&self) -> Result<UnixSeconds, WorkspaceError> { + Ok( + UnixSeconds::new(if self.0.fetch_add(1, Ordering::SeqCst) < 2 { + 100 + } else { + 200 + }) + .unwrap(), + ) + } +} +#[tokio::test] +async fn expiry_is_rechecked_inside_actual_creation_transaction() { + let f = Fixture::new(); + let e = enrollment(&f); + assert!(matches!( + NativeWorkspace::initialize_seller_stock( + &f.path, + &e, + f.crypto(), + Arc::new(ExpiringCreationClock(AtomicU64::new(0))) + ) + .await, + Err(WorkspaceError::GrantExpired) + )); + let mut connection = sqlx::SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .filename(f.path.join("stock_execution_v1.sqlite")) + .read_only(true), + ) + .await + .unwrap(); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM sqlite_schema") + .fetch_one(&mut connection) + .await + .unwrap(); + assert_eq!(count, 0); + connection.close().await.unwrap(); + assert!( + NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone()) + .await + .is_err() + ); +} + +#[tokio::test] +async fn prepared_enrollment_cannot_create_a_second_authority_namespace() { + let f = Fixture::new(); + let e = enrollment(&f); + let store = create(&f, &e).await; + let other = f.path.parent().unwrap().join("second-authority"); + assert!(matches!( + NativeWorkspace::initialize_seller_stock(&other, &e, f.crypto(), f.clock.clone()).await, + Err(WorkspaceError::RecoveryRequired) + )); + assert!(!other.exists()); + store.close().await.unwrap(); + assert!(matches!( + NativeWorkspace::initialize_seller_stock(&other, &e, f.crypto(), f.clock.clone()).await, + Err(WorkspaceError::RecoveryRequired) + )); + let store = reopen(&f, &e).await; + assert_eq!( + store + .stock_authority(e.input().clone(), e.proof()) + .await + .unwrap() + .transaction_id(), + e.transaction_id() + ); + store.close().await.unwrap(); +} diff --git a/crates/storage_sqlite/tests/workspace_attachment.rs b/crates/storage_sqlite/tests/workspace_attachment.rs @@ -539,3 +539,6 @@ async fn unsafe_links_permissions_and_schema_are_refused_without_repair() { Err(WorkspaceError::RecoveryRequired) )); } + +#[path = "support/stock_authority.rs"] +mod stock_authority; diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -26,6 +26,7 @@ struct Policy { retained_capability_families: Vec<String>, independence: Independence, local_outbox_authority: LocalOutboxAuthority, + native_seller_stock_authority: NativeSellerStockAuthority, provenance: Provenance, targets: Targets, portability: Portability, @@ -94,6 +95,22 @@ struct LocalOutboxAuthority { #[derive(Deserialize)] #[serde(deny_unknown_fields)] +struct NativeSellerStockAuthority { + scope: String, + database: String, + lock: String, + schema_version: u16, + enrollment_prepared_before_durable_creation: bool, + prepared_enrollment_single_use: bool, + same_connection_owner_as_outbox: bool, + protected_authority_and_grants_separate: bool, + automatic_outbox_migration: bool, + historical_obligations_recovered: bool, + business_effects_qualified: bool, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] struct Provenance { app_behavior_implementation: String, retain_source_provenance: bool, @@ -260,6 +277,21 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && !local.existing_order_or_history_recovery, "local outbox authority drift", )?; + let stock = &p.native_seller_stock_authority; + require( + stock.scope == "seller_stock_owner" + && stock.database == "stock_execution_v1.sqlite" + && stock.lock == ".stock_execution_v1.lock" + && stock.schema_version == 1 + && stock.enrollment_prepared_before_durable_creation + && stock.prepared_enrollment_single_use + && stock.same_connection_owner_as_outbox + && stock.protected_authority_and_grants_separate + && !stock.automatic_outbox_migration + && !stock.historical_obligations_recovered + && !stock.business_effects_qualified, + "native seller stock enrollment boundary drift", + )?; validate_targets(&p.targets, &p.portability)?; validate_packages(&p.packages)?; validate_values(&p.values, &p.limits)?;