lib

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

commit b8647038b643979ba69b7925a8eb7747e025ae62
parent 9d0574aee11389a5038d61f0bf769884b73e9ddd
Author: triesap <tyson@radroots.org>
Date:   Sat, 17 Oct 2026 21:55:41 +0000

execution: attach protected local buyer workspaces

- Add exact scoped descriptors and opaque captured command contexts.
- Authenticate persisted buyer grants in an owner-only native namespace.
- Retain credentials and writer ownership through cancellation and close.
- Verify native refusals, portable builds, APIs and coverage gates.

Diffstat:
MCargo.lock | 11+++++++++++
Mcontracts/api_baselines/radroots.txt | 8++++++++
Mcontracts/api_baselines/radroots_domain.txt | 223+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcontracts/api_baselines/radroots_execution.txt | 17+++++++++++++++++
Mcontracts/api_baselines/radroots_storage.txt | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcontracts/api_baselines/radroots_storage_sqlite.txt | 28++++++++++++++++++++++++++++
Mcontracts/coverage-profiles.toml | 2+-
Acontracts/execution/workspace.v1.json | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/Cargo.toml | 5+++--
Mcrates/domain/README.md | 8++++++++
Acrates/domain/src/context.rs | 595+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/src/identifier.rs | 28++++++++++++++++++++++++++++
Mcrates/domain/src/lib.rs | 15++++++++++++++-
Acrates/domain/tests/context.rs | 298+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/tests/identifier.rs | 31+++++++++++++++++++++++++++++++
Mcrates/execution/Cargo.toml | 2++
Mcrates/execution/README.md | 18+++++++++++++-----
Mcrates/execution/src/error.rs | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/execution/src/lib.rs | 3+++
Mcrates/execution/src/session/client.rs | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/execution/src/session/mod.rs | 2+-
Acrates/execution/src/workspace.rs | 205+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/execution/tests/workspace.rs | 378+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/radroots/Cargo.toml | 3++-
Mcrates/radroots/README.md | 11++++++++---
Mcrates/radroots/src/client.rs | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mcrates/radroots/src/lib.rs | 2++
Mcrates/radroots/tests/package_boundary.rs | 8+++++++-
Acrates/radroots/tests/workspace.rs | 247+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage/Cargo.toml | 3+++
Mcrates/storage/src/lib.rs | 1+
Acrates/storage/src/workspace.rs | 301+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage/tests/workspace.rs | 188+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/Cargo.toml | 8++++++++
Mcrates/storage_sqlite/README.md | 17+++++++++++++++++
Mcrates/storage_sqlite/src/lib.rs | 2++
Acrates/storage_sqlite/src/workspace/crypto.rs | 135+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/fs.rs | 216+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/mod.rs | 217+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/record.rs | 144+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/tests/mod.rs | 615+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/worker.rs | 400+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/tests/package_boundary.rs | 7+++++++
Acrates/storage_sqlite/tests/workspace_attachment.rs | 504+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
44 files changed, 5236 insertions(+), 21 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock @@ -3049,6 +3049,7 @@ dependencies = [ "radroots_identity", "radroots_nostr", "radroots_sdk", + "radroots_secrets", "radroots_signing", "radroots_storage", "radroots_storage_sqlite", @@ -3096,6 +3097,7 @@ dependencies = [ name = "radroots_domain" version = "0.1.0-alpha" dependencies = [ + "radroots_identity", "serde", "serde_json", ] @@ -3170,6 +3172,7 @@ dependencies = [ "radroots_event_codec", "radroots_identity", "radroots_signing", + "radroots_storage", ] [[package]] @@ -3620,6 +3623,7 @@ name = "radroots_storage" version = "0.1.0-alpha" dependencies = [ "futures-executor", + "radroots_domain", "radroots_event", "radroots_event_codec", "radroots_protocol", @@ -3628,6 +3632,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "zeroize", ] [[package]] @@ -3635,19 +3640,25 @@ name = "radroots_storage_sqlite" version = "0.1.0-alpha" dependencies = [ "fs2", + "futures", + "getrandom 0.2.17", "hex", + "radroots_domain", "radroots_event", "radroots_event_codec", "radroots_secrets", "radroots_storage", "radroots_transport", + "rustix 1.1.4", "serde", "serde_json", "sha2", "sqlx", + "subtle", "tempfile", "tokio", "toml 0.8.23", + "zeroize", ] [[package]] diff --git a/contracts/api_baselines/radroots.txt b/contracts/api_baselines/radroots.txt @@ -1,12 +1,17 @@ pub mod radroots +pub use radroots::AttachmentInput +pub use radroots::AttachmentProof +pub use radroots::CommandContext pub use radroots::Error pub use radroots::OperationId pub use radroots::Result +pub use radroots::WorkspaceSession pub mod radroots::client #[non_exhaustive] pub enum radroots::client::StartMode pub radroots::client::StartMode::LocalOnly pub struct radroots::client::Client impl radroots::client::Client +pub async fn radroots::client::Client::attach(&self, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof) -> radroots_execution::Result<radroots_execution::workspace::WorkspaceSession> pub async fn radroots::client::Client::attach_signer(&self, radroots_signing::provider::SignerHandle) -> radroots_execution::Result<radroots_execution::session::signer::SignerSession> pub async fn radroots::client::Client::close(&self) -> radroots_execution::Result<radroots::client::CloseReceipt> pub async fn radroots::client::Client::open(radroots::client::NativeConfig) -> radroots_execution::Result<Self> @@ -21,6 +26,7 @@ pub const fn radroots::client::CloseReceipt::storage(self) -> radroots_storage:: pub struct radroots::client::NativeConfig impl radroots::client::NativeConfig pub fn radroots::client::NativeConfig::public_read(radroots_storage_sqlite::config::OpenOptions) -> Self +pub fn radroots::client::NativeConfig::with_workspace(self, radroots_storage_sqlite::workspace::NativeWorkspace) -> Self pub struct radroots::client::SessionStatus impl radroots::client::SessionStatus pub const fn radroots::client::SessionStatus::state(self) -> radroots_execution::session::SessionState @@ -168,6 +174,7 @@ pub use radroots::transport::TransportId pub radroots::StartMode::LocalOnly pub struct radroots::Client impl radroots::client::Client +pub async fn radroots::client::Client::attach(&self, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof) -> radroots_execution::Result<radroots_execution::workspace::WorkspaceSession> pub async fn radroots::client::Client::attach_signer(&self, radroots_signing::provider::SignerHandle) -> radroots_execution::Result<radroots_execution::session::signer::SignerSession> pub async fn radroots::client::Client::close(&self) -> radroots_execution::Result<radroots::client::CloseReceipt> pub async fn radroots::client::Client::open(radroots::client::NativeConfig) -> radroots_execution::Result<Self> @@ -182,6 +189,7 @@ pub const fn radroots::client::CloseReceipt::storage(self) -> radroots_storage:: pub struct radroots::NativeConfig impl radroots::client::NativeConfig pub fn radroots::client::NativeConfig::public_read(radroots_storage_sqlite::config::OpenOptions) -> Self +pub fn radroots::client::NativeConfig::with_workspace(self, radroots_storage_sqlite::workspace::NativeWorkspace) -> Self pub struct radroots::SessionStatus impl radroots::client::SessionStatus pub const fn radroots::client::SessionStatus::state(self) -> radroots_execution::session::SessionState diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt @@ -1,4 +1,9 @@ pub mod radroots_domain +pub use radroots_domain::PublicKey +#[non_exhaustive] pub enum radroots_domain::ActorRole +pub radroots_domain::ActorRole::Buyer +pub radroots_domain::ActorRole::Coordinator +pub radroots_domain::ActorRole::Seller #[non_exhaustive] pub enum radroots_domain::AmountError pub radroots_domain::AmountError::CoefficientOutOfRange pub radroots_domain::AmountError::InvalidFormat @@ -9,12 +14,125 @@ pub radroots_domain::AmountError::ScaleOutOfRange impl core::error::Error for radroots_domain::AmountError impl core::fmt::Display for radroots_domain::AmountError pub fn radroots_domain::AmountError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_domain::ContextError +pub radroots_domain::ContextError::InconsistentCoverage +pub radroots_domain::ContextError::InvalidInteger +pub radroots_domain::ContextError::InvalidText +pub radroots_domain::ContextError::OutOfRange +pub radroots_domain::ContextError::TooManyReferences +impl core::error::Error for radroots_domain::ContextError +impl core::fmt::Display for radroots_domain::ContextError +pub fn radroots_domain::ContextError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_domain::Coverage +pub radroots_domain::Coverage::Partial +pub radroots_domain::Coverage::ScopeSatisfied #[non_exhaustive] pub enum radroots_domain::IdentifierError pub radroots_domain::IdentifierError::InvalidEncoding pub radroots_domain::IdentifierError::InvalidLength impl core::error::Error for radroots_domain::IdentifierError impl core::fmt::Display for radroots_domain::IdentifierError pub fn radroots_domain::IdentifierError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::ActorRef +impl radroots_domain::ActorRef +pub const fn radroots_domain::ActorRef::grant_id(self) -> core::option::Option<radroots_domain::GrantId> +pub const fn radroots_domain::ActorRef::new(radroots_identity::key::PublicKey, radroots_domain::ActorRole, core::option::Option<radroots_identity::key::PublicKey>, core::option::Option<radroots_domain::GrantId>) -> Self +pub const fn radroots_domain::ActorRef::organization(self) -> core::option::Option<radroots_identity::key::PublicKey> +pub const fn radroots_domain::ActorRef::participant(self) -> radroots_identity::key::PublicKey +pub const fn radroots_domain::ActorRef::role(self) -> radroots_domain::ActorRole +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::ActorRef +pub fn radroots_domain::ActorRef::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::Approval +impl radroots_domain::Approval +pub const fn radroots_domain::Approval::expires_at(&self) -> radroots_domain::UnixSeconds +pub const fn radroots_domain::Approval::intent_digest(&self) -> radroots_domain::ApprovalIntentDigest +pub fn radroots_domain::Approval::new(radroots_domain::ApprovalIntentDigest, impl core::convert::Into<alloc::string::String>, radroots_domain::UnixSeconds) -> core::result::Result<Self, radroots_domain::ContextError> +pub fn radroots_domain::Approval::scope(&self) -> &str +impl core::fmt::Debug for radroots_domain::Approval +pub fn radroots_domain::Approval::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::Approval +pub fn radroots_domain::Approval::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::ApprovalIntentDigest(_) +impl radroots_domain::ApprovalIntentDigest +pub const fn radroots_domain::ApprovalIntentDigest::as_bytes(&self) -> &[u8; 32] +pub const fn radroots_domain::ApprovalIntentDigest::from_bytes([u8; 32]) -> Self +pub const fn radroots_domain::ApprovalIntentDigest::into_bytes(self) -> [u8; 32] +impl core::fmt::Display for radroots_domain::ApprovalIntentDigest +pub fn radroots_domain::ApprovalIntentDigest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::ApprovalIntentDigest +pub type radroots_domain::ApprovalIntentDigest::Err = radroots_domain::IdentifierError +pub fn radroots_domain::ApprovalIntentDigest::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::ApprovalIntentDigest +pub fn radroots_domain::ApprovalIntentDigest::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::ApprovalIntentDigest +pub fn radroots_domain::ApprovalIntentDigest::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::AuthorityRef +impl radroots_domain::AuthorityRef +pub const fn radroots_domain::AuthorityRef::executor_id(self) -> radroots_domain::ExecutorId +pub const fn radroots_domain::AuthorityRef::generation(self) -> radroots_domain::Generation +pub const fn radroots_domain::AuthorityRef::new(radroots_domain::ExecutorId, radroots_domain::Generation) -> Self +pub struct radroots_domain::CheckpointDigest(_) +impl radroots_domain::CheckpointDigest +pub const fn radroots_domain::CheckpointDigest::as_bytes(&self) -> &[u8; 32] +pub const fn radroots_domain::CheckpointDigest::from_bytes([u8; 32]) -> Self +pub const fn radroots_domain::CheckpointDigest::into_bytes(self) -> [u8; 32] +impl core::fmt::Display for radroots_domain::CheckpointDigest +pub fn radroots_domain::CheckpointDigest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::CheckpointDigest +pub type radroots_domain::CheckpointDigest::Err = radroots_domain::IdentifierError +pub fn radroots_domain::CheckpointDigest::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::CheckpointDigest +pub fn radroots_domain::CheckpointDigest::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::CheckpointDigest +pub fn radroots_domain::CheckpointDigest::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::CheckpointRef +impl radroots_domain::CheckpointRef +pub const fn radroots_domain::CheckpointRef::coverage(&self) -> radroots_domain::Coverage +pub const fn radroots_domain::CheckpointRef::digest(&self) -> radroots_domain::CheckpointDigest +pub fn radroots_domain::CheckpointRef::missing(&self) -> &[radroots_domain::SourceId] +pub fn radroots_domain::CheckpointRef::new(radroots_domain::CheckpointDigest, radroots_domain::Sequence, radroots_domain::Coverage, alloc::vec::Vec<radroots_domain::SourceId>) -> core::result::Result<Self, radroots_domain::ContextError> +pub const fn radroots_domain::CheckpointRef::sequence(&self) -> radroots_domain::Sequence +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::CheckpointRef +pub fn radroots_domain::CheckpointRef::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::CommandContextData +impl radroots_domain::CommandContextData +pub const fn radroots_domain::CommandContextData::actor(&self) -> radroots_domain::ActorRef +pub const fn radroots_domain::CommandContextData::approval(&self) -> core::option::Option<&radroots_domain::Approval> +pub const fn radroots_domain::CommandContextData::authority(&self) -> radroots_domain::AuthorityRef +pub const fn radroots_domain::CommandContextData::correlation_id(&self) -> core::option::Option<&radroots_domain::CorrelationId> +pub const fn radroots_domain::CommandContextData::expected(&self) -> core::option::Option<&radroots_domain::ExpectedOrder> +pub fn radroots_domain::CommandContextData::new(radroots_domain::OperationId, radroots_domain::ActorRef, radroots_domain::WorkspaceId, radroots_domain::AuthorityRef, radroots_domain::RouteDigest, core::option::Option<radroots_domain::Approval>, core::option::Option<radroots_domain::ExpectedOrder>, radroots_domain::UnixSeconds, core::option::Option<radroots_domain::CorrelationId>) -> core::result::Result<Self, radroots_domain::ContextError> +pub const fn radroots_domain::CommandContextData::not_after(&self) -> radroots_domain::UnixSeconds +pub const fn radroots_domain::CommandContextData::operation_id(&self) -> radroots_domain::OperationId +pub const fn radroots_domain::CommandContextData::route_digest(&self) -> radroots_domain::RouteDigest +pub const fn radroots_domain::CommandContextData::workspace_id(&self) -> radroots_domain::WorkspaceId +impl core::fmt::Debug for radroots_domain::CommandContextData +pub fn radroots_domain::CommandContextData::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::CommandContextData +pub fn radroots_domain::CommandContextData::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::CommandDigest(_) +impl radroots_domain::CommandDigest +pub const fn radroots_domain::CommandDigest::as_bytes(&self) -> &[u8; 32] +pub const fn radroots_domain::CommandDigest::from_bytes([u8; 32]) -> Self +pub const fn radroots_domain::CommandDigest::into_bytes(self) -> [u8; 32] +impl core::fmt::Display for radroots_domain::CommandDigest +pub fn radroots_domain::CommandDigest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::CommandDigest +pub type radroots_domain::CommandDigest::Err = radroots_domain::IdentifierError +pub fn radroots_domain::CommandDigest::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::CommandDigest +pub fn radroots_domain::CommandDigest::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::CommandDigest +pub fn radroots_domain::CommandDigest::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::CorrelationId(_) +impl radroots_domain::CorrelationId +pub fn radroots_domain::CorrelationId::as_str(&self) -> &str +pub fn radroots_domain::CorrelationId::new(impl core::convert::Into<alloc::string::String>) -> core::result::Result<Self, radroots_domain::ContextError> +impl core::fmt::Debug for radroots_domain::CorrelationId +pub fn radroots_domain::CorrelationId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl serde_core::ser::Serialize for radroots_domain::CorrelationId +pub fn radroots_domain::CorrelationId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::CorrelationId +pub fn radroots_domain::CorrelationId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub struct radroots_domain::Decimal impl radroots_domain::Decimal pub const radroots_domain::Decimal::MAX: Self @@ -61,6 +179,43 @@ impl serde_core::ser::Serialize for radroots_domain::ExecutorId pub fn radroots_domain::ExecutorId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::ExecutorId pub fn radroots_domain::ExecutorId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::ExpectedOrder +impl radroots_domain::ExpectedOrder +pub const fn radroots_domain::ExpectedOrder::agreement(&self) -> core::option::Option<radroots_domain::RecordId> +pub const fn radroots_domain::ExpectedOrder::buyer_head(&self) -> core::option::Option<radroots_domain::RecordId> +pub const fn radroots_domain::ExpectedOrder::checkpoint(&self) -> &radroots_domain::CheckpointRef +pub const fn radroots_domain::ExpectedOrder::new(radroots_domain::OrderId, core::option::Option<radroots_domain::RecordId>, radroots_domain::Sequence, core::option::Option<radroots_domain::RecordId>, radroots_domain::CheckpointRef) -> Self +pub const fn radroots_domain::ExpectedOrder::order_id(&self) -> radroots_domain::OrderId +pub const fn radroots_domain::ExpectedOrder::seller_sequence(&self) -> radroots_domain::Sequence +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::ExpectedOrder +pub fn radroots_domain::ExpectedOrder::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::Generation(_) +impl radroots_domain::Generation +pub const fn radroots_domain::Generation::get(self) -> u64 +pub const fn radroots_domain::Generation::new(u64) -> core::result::Result<Self, radroots_domain::ContextError> +impl core::fmt::Display for radroots_domain::Generation +pub fn radroots_domain::Generation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::Generation +pub type radroots_domain::Generation::Err = radroots_domain::ContextError +pub fn radroots_domain::Generation::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::Generation +pub fn radroots_domain::Generation::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::Generation +pub fn radroots_domain::Generation::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::GrantId(_) +impl radroots_domain::GrantId +pub const fn radroots_domain::GrantId::as_bytes(&self) -> &[u8; 32] +pub const fn radroots_domain::GrantId::from_bytes([u8; 32]) -> Self +pub const fn radroots_domain::GrantId::into_bytes(self) -> [u8; 32] +impl core::fmt::Display for radroots_domain::GrantId +pub fn radroots_domain::GrantId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::GrantId +pub type radroots_domain::GrantId::Err = radroots_domain::IdentifierError +pub fn radroots_domain::GrantId::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::GrantId +pub fn radroots_domain::GrantId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::GrantId +pub fn radroots_domain::GrantId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub struct radroots_domain::OperationId(_) impl radroots_domain::OperationId pub const fn radroots_domain::OperationId::as_bytes(&self) -> &[u8; 32] @@ -107,6 +262,61 @@ impl serde_core::ser::Serialize for radroots_domain::PositiveDecimal pub fn radroots_domain::PositiveDecimal::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::PositiveDecimal pub fn radroots_domain::PositiveDecimal::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::RecordId(_) +impl radroots_domain::RecordId +pub const fn radroots_domain::RecordId::as_bytes(&self) -> &[u8; 32] +pub const fn radroots_domain::RecordId::from_bytes([u8; 32]) -> Self +pub const fn radroots_domain::RecordId::into_bytes(self) -> [u8; 32] +impl core::fmt::Display for radroots_domain::RecordId +pub fn radroots_domain::RecordId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::RecordId +pub type radroots_domain::RecordId::Err = radroots_domain::IdentifierError +pub fn radroots_domain::RecordId::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::RecordId +pub fn radroots_domain::RecordId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::RecordId +pub fn radroots_domain::RecordId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::RouteDigest(_) +impl radroots_domain::RouteDigest +pub const fn radroots_domain::RouteDigest::as_bytes(&self) -> &[u8; 32] +pub const fn radroots_domain::RouteDigest::from_bytes([u8; 32]) -> Self +pub const fn radroots_domain::RouteDigest::into_bytes(self) -> [u8; 32] +impl core::fmt::Display for radroots_domain::RouteDigest +pub fn radroots_domain::RouteDigest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::RouteDigest +pub type radroots_domain::RouteDigest::Err = radroots_domain::IdentifierError +pub fn radroots_domain::RouteDigest::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::RouteDigest +pub fn radroots_domain::RouteDigest::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::RouteDigest +pub fn radroots_domain::RouteDigest::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::Sequence(_) +impl radroots_domain::Sequence +pub const fn radroots_domain::Sequence::get(self) -> u64 +pub const fn radroots_domain::Sequence::new(u64) -> core::result::Result<Self, radroots_domain::ContextError> +impl core::fmt::Display for radroots_domain::Sequence +pub fn radroots_domain::Sequence::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::Sequence +pub type radroots_domain::Sequence::Err = radroots_domain::ContextError +pub fn radroots_domain::Sequence::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::Sequence +pub fn radroots_domain::Sequence::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::Sequence +pub fn radroots_domain::Sequence::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::SourceId(_) +impl radroots_domain::SourceId +pub const fn radroots_domain::SourceId::as_bytes(&self) -> &[u8; 32] +pub const fn radroots_domain::SourceId::from_bytes([u8; 32]) -> Self +pub const fn radroots_domain::SourceId::into_bytes(self) -> [u8; 32] +impl core::fmt::Display for radroots_domain::SourceId +pub fn radroots_domain::SourceId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::SourceId +pub type radroots_domain::SourceId::Err = radroots_domain::IdentifierError +pub fn radroots_domain::SourceId::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::SourceId +pub fn radroots_domain::SourceId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::SourceId +pub fn radroots_domain::SourceId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub struct radroots_domain::ThreadId(_) impl radroots_domain::ThreadId pub const fn radroots_domain::ThreadId::as_bytes(&self) -> &[u8; 32] @@ -121,6 +331,19 @@ impl serde_core::ser::Serialize for radroots_domain::ThreadId pub fn radroots_domain::ThreadId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::ThreadId pub fn radroots_domain::ThreadId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::UnixSeconds(_) +impl radroots_domain::UnixSeconds +pub const fn radroots_domain::UnixSeconds::get(self) -> u64 +pub const fn radroots_domain::UnixSeconds::new(u64) -> core::result::Result<Self, radroots_domain::ContextError> +impl core::fmt::Display for radroots_domain::UnixSeconds +pub fn radroots_domain::UnixSeconds::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::UnixSeconds +pub type radroots_domain::UnixSeconds::Err = radroots_domain::ContextError +pub fn radroots_domain::UnixSeconds::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::UnixSeconds +pub fn radroots_domain::UnixSeconds::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::UnixSeconds +pub fn radroots_domain::UnixSeconds::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub struct radroots_domain::WorkspaceId(_) impl radroots_domain::WorkspaceId pub const fn radroots_domain::WorkspaceId::as_bytes(&self) -> &[u8; 32] diff --git a/contracts/api_baselines/radroots_execution.txt b/contracts/api_baselines/radroots_execution.txt @@ -9,6 +9,7 @@ pub radroots_execution::session::SessionState::Starting pub struct radroots_execution::session::ClientSession<H: radroots_execution::session::SessionHost> impl<H: radroots_execution::session::SessionHost> radroots_execution::session::ClientSession<H> pub async fn radroots_execution::session::ClientSession<H>::attach_signer(&self, radroots_signing::provider::SignerHandle) -> radroots_execution::Result<radroots_execution::session::SignerSession> +pub async fn radroots_execution::session::ClientSession<H>::attach_workspace(&self, alloc::sync::Arc<dyn radroots_storage::workspace::WorkspaceStore>, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof) -> radroots_execution::Result<radroots_execution::workspace::WorkspaceSession> pub async fn radroots_execution::session::ClientSession<H>::close(&self) -> radroots_execution::Result<()> pub fn radroots_execution::session::ClientSession<H>::new(H, core::num::nonzero::NonZeroU16) -> Self pub fn radroots_execution::session::ClientSession<H>::signer_session(&self) -> core::option::Option<radroots_execution::session::SignerSession> @@ -50,6 +51,22 @@ pub fn radroots_execution::session::SessionHost::dispose_callbacks(&self) -> rad pub fn radroots_execution::session::SessionHost::quiesce(&self) -> radroots_execution::session::HostFuture<'_, radroots_execution::Result<()>> pub fn radroots_execution::session::SessionHost::start(&self) -> radroots_execution::session::HostFuture<'_, radroots_execution::Result<()>> pub type radroots_execution::session::HostFuture<'a, T> = core::pin::Pin<alloc::boxed::Box<(dyn core::future::future::Future<Output = T> + core::marker::Send + 'a)>> +pub mod radroots_execution::workspace +pub struct radroots_execution::workspace::CommandContext +impl radroots_execution::workspace::CommandContext +pub const fn radroots_execution::workspace::CommandContext::data(&self) -> &radroots_domain::context::CommandContextData +pub async fn radroots_execution::workspace::CommandContext::revalidate(&self) -> radroots_execution::Result<radroots_storage::workspace::WorkspaceBinding> +impl core::fmt::Debug for radroots_execution::workspace::CommandContext +pub fn radroots_execution::workspace::CommandContext::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_execution::workspace::WorkspaceSession +impl radroots_execution::workspace::WorkspaceSession +pub async fn radroots_execution::workspace::WorkspaceSession::attach(alloc::sync::Arc<dyn radroots_storage::workspace::WorkspaceStore>, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof) -> radroots_execution::Result<Self> +pub fn radroots_execution::workspace::WorkspaceSession::binding(&self) -> &radroots_storage::workspace::WorkspaceBinding +pub fn radroots_execution::workspace::WorkspaceSession::close(&self) +pub fn radroots_execution::workspace::WorkspaceSession::command_context(&self, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::context::ExpectedOrder>, core::option::Option<radroots_domain::context::Approval>, radroots_domain::context::UnixSeconds) -> radroots_execution::Result<radroots_execution::workspace::CommandContext> +pub fn radroots_execution::workspace::WorkspaceSession::command_context_with_correlation(&self, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::context::ExpectedOrder>, core::option::Option<radroots_domain::context::Approval>, radroots_domain::context::UnixSeconds, core::option::Option<radroots_domain::context::CorrelationId>) -> radroots_execution::Result<radroots_execution::workspace::CommandContext> +impl core::fmt::Debug for radroots_execution::workspace::WorkspaceSession +pub fn radroots_execution::workspace::WorkspaceSession::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result #[non_exhaustive] pub enum radroots_execution::Admission pub radroots_execution::Admission::Confirmed pub radroots_execution::Admission::NotAdmitted diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -1820,6 +1820,64 @@ pub trait radroots_storage::status::StorageStatusProvider: radroots_transport::h pub fn radroots_storage::status::StorageStatusProvider::storage_status(&self) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::status::StorageStatus, radroots_storage::Error>> impl radroots_storage::status::StorageStatusProvider for radroots_storage::memory::MemoryStorage pub fn radroots_storage::memory::MemoryStorage::storage_status(&self) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::status::StorageStatus, radroots_storage::Error>> +pub mod radroots_storage::workspace +#[non_exhaustive] pub enum radroots_storage::workspace::WorkspaceError +pub radroots_storage::workspace::WorkspaceError::Closed +pub radroots_storage::workspace::WorkspaceError::CommitUnknown +pub radroots_storage::workspace::WorkspaceError::GrantExpired +pub radroots_storage::workspace::WorkspaceError::GrantRevoked +pub radroots_storage::workspace::WorkspaceError::InvalidInput +pub radroots_storage::workspace::WorkspaceError::NamespaceUnavailable +pub radroots_storage::workspace::WorkspaceError::RecoveryRequired +pub radroots_storage::workspace::WorkspaceError::StaleAuthority +pub radroots_storage::workspace::WorkspaceError::StaleCheckpoint +pub radroots_storage::workspace::WorkspaceError::StorageFailure +pub radroots_storage::workspace::WorkspaceError::Unauthorized +pub radroots_storage::workspace::WorkspaceError::Unavailable +pub radroots_storage::workspace::WorkspaceError::WriterActive +pub radroots_storage::workspace::WorkspaceError::WrongNamespace +impl radroots_storage::workspace::WorkspaceError +pub const fn radroots_storage::workspace::WorkspaceError::code(self) -> &'static str +impl core::error::Error for radroots_storage::workspace::WorkspaceError +impl core::fmt::Display for radroots_storage::workspace::WorkspaceError +pub fn radroots_storage::workspace::WorkspaceError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::workspace::AttachmentInput +impl radroots_storage::workspace::AttachmentInput +pub const fn radroots_storage::workspace::AttachmentInput::authority(&self) -> radroots_domain::context::AuthorityRef +pub const fn radroots_storage::workspace::AttachmentInput::checkpoint(&self) -> &radroots_domain::context::CheckpointRef +pub fn radroots_storage::workspace::AttachmentInput::endpoint(&self) -> &str +pub const fn radroots_storage::workspace::AttachmentInput::endpoint_identity(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_storage::workspace::AttachmentInput::grant_id(&self) -> radroots_domain::identifier::GrantId +pub fn radroots_storage::workspace::AttachmentInput::new(radroots_domain::identifier::WorkspaceId, radroots_domain::context::AuthorityRef, radroots_identity::key::PublicKey, impl core::convert::Into<alloc::string::String>, radroots_identity::key::PublicKey, radroots_domain::identifier::GrantId, radroots_domain::context::CheckpointRef, radroots_domain::identifier::RouteDigest) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> +pub const fn radroots_storage::workspace::AttachmentInput::participant(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_storage::workspace::AttachmentInput::route_digest(&self) -> radroots_domain::identifier::RouteDigest +pub const fn radroots_storage::workspace::AttachmentInput::workspace_id(&self) -> radroots_domain::identifier::WorkspaceId +impl core::fmt::Debug for radroots_storage::workspace::AttachmentInput +pub fn radroots_storage::workspace::AttachmentInput::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl<'de> serde_core::de::Deserialize<'de> for radroots_storage::workspace::AttachmentInput +pub fn radroots_storage::workspace::AttachmentInput::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_storage::workspace::AttachmentProof(_) +impl radroots_storage::workspace::AttachmentProof +pub fn radroots_storage::workspace::AttachmentProof::from_protected_input(&[u8]) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage::workspace::AttachmentProof::with_secret<T>(&self, impl core::ops::function::FnOnce(&[u8; 32]) -> T) -> T +impl core::fmt::Debug for radroots_storage::workspace::AttachmentProof +pub fn radroots_storage::workspace::AttachmentProof::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::workspace::WorkspaceBinding +impl radroots_storage::workspace::WorkspaceBinding +pub const fn radroots_storage::workspace::WorkspaceBinding::actor(&self) -> radroots_domain::context::ActorRef +pub const fn radroots_storage::workspace::WorkspaceBinding::expires_at(&self) -> radroots_domain::context::UnixSeconds +pub fn radroots_storage::workspace::WorkspaceBinding::from_authenticated_host(radroots_storage::workspace::AttachmentInput, radroots_domain::context::ActorRef, impl core::convert::Into<alloc::string::String>, radroots_domain::context::Sequence, radroots_domain::context::UnixSeconds, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> +pub const fn radroots_storage::workspace::WorkspaceBinding::grant_revision(&self) -> radroots_domain::context::Sequence +pub const fn radroots_storage::workspace::WorkspaceBinding::input(&self) -> &radroots_storage::workspace::AttachmentInput +pub const fn radroots_storage::workspace::WorkspaceBinding::observed_at(&self) -> radroots_domain::context::UnixSeconds +pub fn radroots_storage::workspace::WorkspaceBinding::principal_id(&self) -> &str +impl core::fmt::Debug for radroots_storage::workspace::WorkspaceBinding +pub fn radroots_storage::workspace::WorkspaceBinding::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub trait radroots_storage::workspace::WorkspaceClock: radroots_transport::host::HostBound +pub fn radroots_storage::workspace::WorkspaceClock::now(&self) -> core::result::Result<radroots_domain::context::UnixSeconds, radroots_storage::workspace::WorkspaceError> +pub trait radroots_storage::workspace::WorkspaceStore: radroots_transport::host::HostBound +pub fn radroots_storage::workspace::WorkspaceStore::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::workspace::WorkspaceStore::close_workspace(&self) -> radroots_transport::source::BoxFuture<'_, core::result::Result<(), radroots_storage::workspace::WorkspaceError>> #[non_exhaustive] pub enum radroots_storage::Error pub radroots_storage::Error::AdmissionEventMismatch pub radroots_storage::Error::AdmissionRegression diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -359,6 +359,34 @@ pub fn radroots_storage_sqlite::open::Paths::from_files(impl core::convert::Into pub fn radroots_storage_sqlite::open::Paths::private(&self) -> &std::path::Path pub fn radroots_storage_sqlite::open::Paths::runtime(&self) -> &std::path::Path pub mod radroots_storage_sqlite::status +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::WorkspaceBinding +pub use radroots_storage_sqlite::workspace::WorkspaceClock +pub use radroots_storage_sqlite::workspace::WorkspaceError +pub struct radroots_storage_sqlite::workspace::LocalOutboxConfig +impl radroots_storage_sqlite::workspace::LocalOutboxConfig +pub fn radroots_storage_sqlite::workspace::LocalOutboxConfig::new(radroots_identity::key::PublicKey, radroots_identity::key::PublicKey, impl core::convert::Into<alloc::string::String>, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> +impl core::fmt::Debug for radroots_storage_sqlite::workspace::LocalOutboxConfig +pub fn radroots_storage_sqlite::workspace::LocalOutboxConfig::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_sqlite::workspace::NativeWorkspace +impl radroots_storage_sqlite::workspace::NativeWorkspace +pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::authenticate(&self, radroots_storage::workspace::AttachmentInput, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::WorkspaceError> +pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::close(&self) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> +pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::initialize_local_outbox(&std::path::Path, radroots_storage_sqlite::workspace::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 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::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::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> +impl core::fmt::Debug for radroots_storage_sqlite::workspace::WorkspaceCrypto +pub fn radroots_storage_sqlite::workspace::WorkspaceCrypto::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result #[non_exhaustive] pub enum radroots_storage_sqlite::Error pub radroots_storage_sqlite::Error::AuthoredMigrationBlocked pub radroots_storage_sqlite::Error::AuthoredMigrationBlocked::invalid_or_unsupported: u64 diff --git a/contracts/coverage-profiles.toml b/contracts/coverage-profiles.toml @@ -5,7 +5,7 @@ test_threads = 1 [profiles.crates."radroots_execution"] no_default_features = false -features = ["session", "signer_session", "client_session"] +features = ["session", "signer_session", "client_session", "workspace_session"] test_threads = 1 [profiles.crates."radroots"] diff --git a/contracts/execution/workspace.v1.json b/contracts/execution/workspace.v1.json @@ -0,0 +1,71 @@ +{ + "schema_version": 1, + "contract_id": "radroots.execution.workspace.v1", + "state": "native_buyer_attachment_component_implemented", + "ownership": { + "domain": "Validated actor, authority, checkpoint and captured-context descriptors; descriptors grant no rights", + "execution": "Owned authenticated workspace session and opaque captured command context", + "storage_sqlite": "Concrete protected native namespace and current grant/authority verification", + "facade": "Explicit local attachment and shared execution entry points" + }, + "identity": { + "workspace_executor_operation_grant_bytes": 32, + "integer_wire": "canonical decimal strings bounded by signed 64-bit maximum", + "generation": "positive; distinct from a public cache generation", + "participant": "validated Nostr x-only key; distinct from the authenticated device/principal" + }, + "native_scope": { + "namespace": "explicit new execution namespace; existing opens never create or infer authority", + "authentication": "protected high-entropy credential checked against persisted scoped grant and authority state", + "credential_bytes": 32, + "credential_persistence": "verifier only, under protected handling; no plaintext credential in SQL, diagnostics or arguments", + "private_payload_max_bytes": 16384, + "private_codec": "existing context-bound authenticated envelope v2 with explicit qualified provider, key material and unique nonce", + "transactions": "Grant creation and revocation observe actual SQLite commit completion. Transaction-time business admission/revalidation remains unimplemented.", + "initialization": "explicit fresh local outbox enrollment; no automatic stock ledger or restore from a key/public cache", + "remote_attachment_qualified": false, + "firm_stock_qualified": false + }, + "context": { + "constructor": "pure synchronous authenticated workspace-session method; no clock, storage, signer or network effects; arbitrary JSON yields descriptors, never a trusted context", + "fields": [ + "operation_id", + "actor", + "workspace_id", + "authority", + "route_digest", + "approval", + "expected", + "not_after", + "correlation_id" + ], + "nullable_fields_required": true, + "approval": "descriptor alone is not consent; authoritative admission validates protected origin, exact intent, scope and expiry", + "idempotency": "captured semantic input is immutable; correlation is diagnostic only", + "revocation": "attachment observation does not replace current transaction-time grant checks" + }, + "lifecycle": "attach work and callbacks remain owned across observer loss; close stops admission and drains work before credentials/callbacks and storage are released", + "resource_bounds": { + "native_queued_requests": 32, + "native_in_flight_requests": 1, + "client_workspace_scopes": 16, + "credentials": "zeroizing roots are released at scope/client quiesce; admitted authentication owns its request credential through safe completion" + }, + "qualification_required": [ + "Actual protected native store and correct credential attachment", + "Wrong credential, participant, workspace, executor, generation, route, grant and checkpoint refusal", + "Revoked/expired grant refusal and persisted reopen behavior", + "No context authority from signer observation, public cache or caller-provided descriptors", + "Full captured context fields, exact strings, explicit null, bounded redacted diagnostics and local/native lifetime checks", + "Owning native/portable/API/contract checks and unchanged coverage policy" + ], + "remaining": [ + "Complete operation receipts and actual known-kind T0/T1/S/T2/D execution", + "Owned durable workers, per-target delivery and process-fault recovery", + "Full stock executor, remote pairing/transfer and restore/fencing", + "Actual browser/platform providers, generated bindings, coherent consumers and final acceptance" + ], + "implementation_claimed": true, + "implementation_scope": "Fresh unrelated protected local buyer attachment and pure captured context only; no durable business command, selected seller stock, remote pairing or recovery qualification.", + "package_publication_authorized": false +} diff --git a/crates/domain/Cargo.toml b/crates/domain/Cargo.toml @@ -14,10 +14,11 @@ include = ["src/**", "tests/**", "Cargo.toml", "README.md", "LICENSE-APACHE", "L [features] default = ["std", "serde"] -std = [] -serde = ["dep:serde"] +std = ["radroots_identity/std"] +serde = ["dep:serde", "radroots_identity/serde"] [dependencies] +radroots_identity = { workspace = true, default-features = false } serde = { workspace = true, optional = true } [dev-dependencies] diff --git a/crates/domain/README.md b/crates/domain/README.md @@ -36,4 +36,12 @@ use radroots_domain::OperationId; let _ = OperationId::from_bytes([0; 31]); ``` +Actor, authority, checkpoint, approval, expected-order and complete captured +context descriptors validate their representations without authenticating a +principal. Sequence, generation and wall time use exact canonical decimal +strings. Required nullable fields remain explicit JSON nulls. Checkpoint missing +sources retain full digests independently of structured-record identity. +`CommandContextData` is untrusted data; only an authenticated execution session +can construct the opaque executable context. + Licensed under MIT OR Apache-2.0; see LICENSE-MIT and LICENSE-APACHE. diff --git a/crates/domain/src/context.rs b/crates/domain/src/context.rs @@ -0,0 +1,595 @@ +//! Exact captured-context descriptors. These values authenticate no principal +//! and grant no command permission, approval or stock authority. + +use crate::{ + ApprovalIntentDigest, CheckpointDigest, ExecutorId, GrantId, OperationId, OrderId, RecordId, + RouteDigest, SourceId, WorkspaceId, +}; +use alloc::{boxed::Box, string::String, vec::Vec}; +use core::{fmt, str::FromStr}; +use radroots_identity::PublicKey; + +/// Maximum sequence or authority generation supported by every governed host. +const MAX_SEQUENCE: u64 = i64::MAX as u64; +const MAX_UNIX_SECONDS: u64 = 253_402_300_799; +const MAX_MISSING: usize = 128; + +/// A fixed descriptor failure with no retained caller input. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum ContextError { + /// An integer has a noncanonical decimal representation. + InvalidInteger, + /// A value exceeds the shared bound or requires a positive value. + OutOfRange, + /// Bounded diagnostic or scope text is invalid. + InvalidText, + /// A checkpoint has more missing references than supported. + TooManyReferences, + /// Satisfied coverage cannot retain missing references. + InconsistentCoverage, +} +impl fmt::Display for ContextError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::InvalidInteger => "context integer is not canonical", + Self::OutOfRange => "context value is out of range", + Self::InvalidText => "context text is invalid", + Self::TooManyReferences => "checkpoint reference limit exceeded", + Self::InconsistentCoverage => "checkpoint coverage is inconsistent", + }) + } +} +impl core::error::Error for ContextError {} + +fn integer(value: &str, max: u64, positive: bool) -> Result<u64, ContextError> { + if value.is_empty() + || value.len() > 20 + || (value.len() > 1 && value.starts_with('0')) + || !value.bytes().all(|b| b.is_ascii_digit()) + { + return Err(ContextError::InvalidInteger); + } + let number = value.parse::<u64>().map_err(|_| ContextError::OutOfRange)?; + if number > max || (positive && number == 0) { + return Err(ContextError::OutOfRange); + } + Ok(number) +} +macro_rules! exact_integer { + ($name:ident,$doc:literal,$max:expr,$positive:expr) => { + #[doc=$doc] + #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] + pub struct $name(u64); + impl $name { + /// Checks the cross-host range without coercing or rounding. + pub const fn new(value: u64) -> Result<Self, ContextError> { + if value > $max || ($positive && value == 0) { + Err(ContextError::OutOfRange) + } else { + Ok(Self(value)) + } + } + /// Returns the exact integer for checked host operations. + pub const fn get(self) -> u64 { + self.0 + } + } + impl FromStr for $name { + type Err = ContextError; + fn from_str(value: &str) -> Result<Self, Self::Err> { + integer(value, $max, $positive).map(Self) + } + } + impl fmt::Display for $name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.0) + } + } + #[cfg(feature = "serde")] + impl serde::Serialize for $name { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + s.collect_str(self) + } + } + #[cfg(feature = "serde")] + impl<'de> serde::Deserialize<'de> for $name { + fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> { + struct Visitor; + impl serde::de::Visitor<'_> for Visitor { + type Value = $name; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a bounded canonical decimal string") + } + fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<$name, E> { + value.parse().map_err(E::custom) + } + } + d.deserialize_str(Visitor) + } + } + }; +} +exact_integer!( + Sequence, + "A canonical sequence, including an explicit genesis zero.", + MAX_SEQUENCE, + false +); +exact_integer!( + Generation, + "A positive authority generation, independent of cache cursors.", + MAX_SEQUENCE, + true +); +exact_integer!( + UnixSeconds, + "Exact bounded Unix seconds serialized as a decimal string.", + MAX_UNIX_SECONDS, + false +); + +/// A participant's requested business role; this is not permission evidence. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] +#[non_exhaustive] +pub enum ActorRole { + /// The seller participant. + Seller, + /// The buyer participant. + Buyer, + /// A separately granted logistics coordinator. + Coordinator, +} +/// An untrusted actor descriptor. Grant origin and scope require authentication. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct ActorRef { + participant: PublicKey, + role: ActorRole, + organization: Option<PublicKey>, + grant_id: Option<GrantId>, +} +impl ActorRef { + /// Captures validated values without authenticating their relationship. + pub const fn new( + participant: PublicKey, + role: ActorRole, + organization: Option<PublicKey>, + grant_id: Option<GrantId>, + ) -> Self { + Self { + participant, + role, + organization, + grant_id, + } + } + /// Returns the claimed participant. + pub const fn participant(self) -> PublicKey { + self.participant + } + /// Returns the requested role. + pub const fn role(self) -> ActorRole { + self.role + } + /// Returns the represented organization, if supplied. + pub const fn organization(self) -> Option<PublicKey> { + self.organization + } + /// Returns a grant selector, never its credential. + pub const fn grant_id(self) -> Option<GrantId> { + self.grant_id + } +} +/// Exact selected executor and authority epoch, without an authority certificate. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(deny_unknown_fields))] +pub struct AuthorityRef { + executor_id: ExecutorId, + generation: Generation, +} +impl AuthorityRef { + /// Captures one exact selected executor/generation pair. + pub const fn new(executor_id: ExecutorId, generation: Generation) -> Self { + Self { + executor_id, + generation, + } + } + /// Returns the selected executor. + pub const fn executor_id(self) -> ExecutorId { + self.executor_id + } + /// Returns the authority generation. + pub const fn generation(self) -> Generation { + self.generation + } +} +/// Described checkpoint coverage, independently verified by the execution owner. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] +#[non_exhaustive] +pub enum Coverage { + /// Coverage is incomplete or unknown within its scope. + Partial, + /// The named scope has no reported missing references. + ScopeSatisfied, +} +/// A bounded checkpoint descriptor; it is neither a stock authority nor a proof. +#[derive(Clone, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct CheckpointRef { + digest: CheckpointDigest, + sequence: Sequence, + coverage: Coverage, + missing: Box<[SourceId]>, +} +impl CheckpointRef { + /// Captures bounded, internally consistent coverage claims. + pub fn new( + digest: CheckpointDigest, + sequence: Sequence, + coverage: Coverage, + missing: Vec<SourceId>, + ) -> Result<Self, ContextError> { + if missing.len() > MAX_MISSING { + return Err(ContextError::TooManyReferences); + } + if coverage == Coverage::ScopeSatisfied && !missing.is_empty() { + return Err(ContextError::InconsistentCoverage); + } + Ok(Self { + digest, + sequence, + coverage, + missing: missing.into_boxed_slice(), + }) + } + /// Returns the claimed checkpoint digest. + pub const fn digest(&self) -> CheckpointDigest { + self.digest + } + /// Returns its exact sequence, including explicit genesis. + pub const fn sequence(&self) -> Sequence { + self.sequence + } + /// Returns the described coverage. + pub const fn coverage(&self) -> Coverage { + self.coverage + } + /// Borrows the bounded missing-source list. + pub fn missing(&self) -> &[SourceId] { + &self.missing + } +} +/// A bounded diagnostic reference excluded from semantic idempotency. +#[derive(Clone, Eq, PartialEq)] +pub struct CorrelationId(String); +impl CorrelationId { + /// Retains at most 128 UTF-8 bytes, with no terminal/control characters. + pub fn new(value: impl Into<String>) -> Result<Self, ContextError> { + let value = value.into(); + if value.len() > 128 || value.chars().any(char::is_control) { + return Err(ContextError::InvalidText); + } + Ok(Self(value)) + } + /// Borrows the explicit diagnostic value for an authorized presentation. + pub fn as_str(&self) -> &str { + &self.0 + } +} +impl fmt::Debug for CorrelationId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CorrelationId(<redacted>)") + } +} +/// Untrusted approval data. The descriptor alone proves no consent or grant. +#[derive(Clone, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct Approval { + intent_digest: ApprovalIntentDigest, + scope: String, + expires_at: UnixSeconds, +} +impl Approval { + /// Checks representation only; the host must authenticate origin and scope. + pub fn new( + intent_digest: ApprovalIntentDigest, + scope: impl Into<String>, + expires_at: UnixSeconds, + ) -> Result<Self, ContextError> { + let scope = scope.into(); + if scope.is_empty() || scope.len() > 160 || scope.chars().any(char::is_control) { + return Err(ContextError::InvalidText); + } + if expires_at.get() == 0 { + return Err(ContextError::OutOfRange); + } + Ok(Self { + intent_digest, + scope, + expires_at, + }) + } + /// Returns the exact displayed-intent commitment. + pub const fn intent_digest(&self) -> ApprovalIntentDigest { + self.intent_digest + } + /// Borrows the bounded requested consent scope. + pub fn scope(&self) -> &str { + &self.scope + } + /// Returns the captured consent expiry. + pub const fn expires_at(&self) -> UnixSeconds { + self.expires_at + } +} +impl fmt::Debug for Approval { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Approval(<untrusted descriptor>)") + } +} +/// Captured order preconditions, independent of whether the history is present. +#[derive(Clone, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct ExpectedOrder { + order_id: OrderId, + agreement: Option<RecordId>, + seller_sequence: Sequence, + buyer_head: Option<RecordId>, + checkpoint: CheckpointRef, +} +impl ExpectedOrder { + /// Captures exact expected values without querying or installing an order. + pub const fn new( + order_id: OrderId, + agreement: Option<RecordId>, + seller_sequence: Sequence, + buyer_head: Option<RecordId>, + checkpoint: CheckpointRef, + ) -> Self { + Self { + order_id, + agreement, + seller_sequence, + buyer_head, + checkpoint, + } + } + /// Returns the order identity. + pub const fn order_id(&self) -> OrderId { + self.order_id + } + /// Returns the expected installed agreement. + pub const fn agreement(&self) -> Option<RecordId> { + self.agreement + } + /// Returns the exact expected seller sequence. + pub const fn seller_sequence(&self) -> Sequence { + self.seller_sequence + } + /// Returns the expected buyer head. + pub const fn buyer_head(&self) -> Option<RecordId> { + self.buyer_head + } + /// Borrows the expected evidence checkpoint. + pub const fn checkpoint(&self) -> &CheckpointRef { + &self.checkpoint + } +} +/// Complete wire-shaped captured-context data. Deserializing it never constructs +/// an authenticated execution context or grants any permission. +#[derive(Clone, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct CommandContextData { + operation_id: OperationId, + actor: ActorRef, + workspace_id: WorkspaceId, + authority: AuthorityRef, + route_digest: RouteDigest, + approval: Option<Approval>, + expected: Option<ExpectedOrder>, + not_after: UnixSeconds, + correlation_id: Option<CorrelationId>, +} +impl CommandContextData { + /// Captures every explicit descriptor field, with no ambient effects. + #[allow(clippy::too_many_arguments)] + pub fn new( + operation_id: OperationId, + actor: ActorRef, + workspace_id: WorkspaceId, + authority: AuthorityRef, + route_digest: RouteDigest, + approval: Option<Approval>, + expected: Option<ExpectedOrder>, + not_after: UnixSeconds, + correlation_id: Option<CorrelationId>, + ) -> Result<Self, ContextError> { + if not_after.get() == 0 { + return Err(ContextError::OutOfRange); + } + Ok(Self { + operation_id, + actor, + workspace_id, + authority, + route_digest, + approval, + expected, + not_after, + correlation_id, + }) + } + /// Returns the full caller-retained operation identity. + pub const fn operation_id(&self) -> OperationId { + self.operation_id + } + /// Returns claimed actor/grant data, without authenticating it. + pub const fn actor(&self) -> ActorRef { + self.actor + } + /// Returns the selected workspace. + pub const fn workspace_id(&self) -> WorkspaceId { + self.workspace_id + } + /// Returns the exact executor and epoch. + pub const fn authority(&self) -> AuthorityRef { + self.authority + } + /// Returns the immutable selected route commitment. + pub const fn route_digest(&self) -> RouteDigest { + self.route_digest + } + /// Borrows untrusted approval data. + pub const fn approval(&self) -> Option<&Approval> { + self.approval.as_ref() + } + /// Borrows captured expected order state. + pub const fn expected(&self) -> Option<&ExpectedOrder> { + self.expected.as_ref() + } + /// Returns the original admission deadline. + pub const fn not_after(&self) -> UnixSeconds { + self.not_after + } + /// Borrows the diagnostic reference, which is not idempotency. + pub const fn correlation_id(&self) -> Option<&CorrelationId> { + self.correlation_id.as_ref() + } +} +impl fmt::Debug for CommandContextData { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CommandContextData(<untrusted descriptor>)") + } +} + +#[cfg(feature = "serde")] +mod serialization { + use super::*; + use serde::{Deserialize, Deserializer, Serializer, de::Error}; + fn nullable<'de, D: Deserializer<'de>, T: Deserialize<'de>>( + d: D, + ) -> Result<Option<T>, D::Error> { + Option::<T>::deserialize(d) + } + impl serde::Serialize for CorrelationId { + fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + s.serialize_str(&self.0) + } + } + impl<'de> Deserialize<'de> for CorrelationId { + fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { + Self::new(String::deserialize(d)?).map_err(D::Error::custom) + } + } + impl<'de> Deserialize<'de> for ActorRef { + fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Raw { + participant: PublicKey, + role: ActorRole, + #[serde(deserialize_with = "nullable")] + organization: Option<PublicKey>, + #[serde(deserialize_with = "nullable")] + grant_id: Option<GrantId>, + } + let raw = Raw::deserialize(d)?; + Ok(Self::new( + raw.participant, + raw.role, + raw.organization, + raw.grant_id, + )) + } + } + impl<'de> Deserialize<'de> for CheckpointRef { + fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Raw { + digest: CheckpointDigest, + sequence: Sequence, + coverage: Coverage, + missing: Vec<SourceId>, + } + let raw = Raw::deserialize(d)?; + Self::new(raw.digest, raw.sequence, raw.coverage, raw.missing).map_err(D::Error::custom) + } + } + impl<'de> Deserialize<'de> for Approval { + fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Raw { + intent_digest: ApprovalIntentDigest, + scope: String, + expires_at: UnixSeconds, + } + let raw = Raw::deserialize(d)?; + Self::new(raw.intent_digest, raw.scope, raw.expires_at).map_err(D::Error::custom) + } + } + impl<'de> Deserialize<'de> for ExpectedOrder { + fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Raw { + order_id: OrderId, + #[serde(deserialize_with = "nullable")] + agreement: Option<RecordId>, + seller_sequence: Sequence, + #[serde(deserialize_with = "nullable")] + buyer_head: Option<RecordId>, + checkpoint: CheckpointRef, + } + let raw = Raw::deserialize(d)?; + Ok(Self::new( + raw.order_id, + raw.agreement, + raw.seller_sequence, + raw.buyer_head, + raw.checkpoint, + )) + } + } + impl<'de> Deserialize<'de> for CommandContextData { + fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Raw { + operation_id: OperationId, + actor: ActorRef, + workspace_id: WorkspaceId, + authority: AuthorityRef, + route_digest: RouteDigest, + #[serde(deserialize_with = "nullable")] + approval: Option<Approval>, + #[serde(deserialize_with = "nullable")] + expected: Option<ExpectedOrder>, + not_after: UnixSeconds, + #[serde(deserialize_with = "nullable")] + correlation_id: Option<CorrelationId>, + } + let raw = Raw::deserialize(d)?; + Self::new( + raw.operation_id, + raw.actor, + raw.workspace_id, + raw.authority, + raw.route_digest, + raw.approval, + raw.expected, + raw.not_after, + raw.correlation_id, + ) + .map_err(D::Error::custom) + } + } +} diff --git a/crates/domain/src/identifier.rs b/crates/domain/src/identifier.rs @@ -122,3 +122,31 @@ identifier!( OperationId, "An exact 256-bit retained operation identifier." ); +identifier!( + GrantId, + "An exact 256-bit scoped grant identifier; not a credential." +); +identifier!( + RecordId, + "A structured record content digest, distinct from rumor and envelope identities." +); +identifier!( + SourceId, + "A missing authenticated-source digest; provenance identifies its event or record family." +); +identifier!( + CommandDigest, + "A domain-separated exact command commitment." +); +identifier!( + RouteDigest, + "A commitment to one explicitly selected execution route." +); +identifier!( + CheckpointDigest, + "A checkpoint commitment; its bytes alone establish no coverage." +); +identifier!( + ApprovalIntentDigest, + "A commitment to the exact intent presented for approval." +); diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs @@ -3,8 +3,21 @@ #![forbid(unsafe_code)] #![warn(missing_docs)] +extern crate alloc; + mod amount; +mod context; mod identifier; +/// The identity-owned validated participant key; no second key type is defined. +pub use radroots_identity::PublicKey; + pub use amount::{AmountError, Decimal, PositiveDecimal}; -pub use identifier::{ExecutorId, IdentifierError, OperationId, OrderId, ThreadId, WorkspaceId}; +pub use context::{ + ActorRef, ActorRole, Approval, AuthorityRef, CheckpointRef, CommandContextData, ContextError, + CorrelationId, Coverage, ExpectedOrder, Generation, Sequence, UnixSeconds, +}; +pub use identifier::{ + ApprovalIntentDigest, CheckpointDigest, CommandDigest, ExecutorId, GrantId, IdentifierError, + OperationId, OrderId, RecordId, RouteDigest, SourceId, ThreadId, WorkspaceId, +}; diff --git a/crates/domain/tests/context.rs b/crates/domain/tests/context.rs @@ -0,0 +1,298 @@ +use radroots_domain::*; +use radroots_identity::PublicKey; +use serde_json::{Value, json}; +use std::str::FromStr; + +const KEY: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; +fn actor() -> ActorRef { + ActorRef::new( + PublicKey::from_str(KEY).unwrap(), + ActorRole::Buyer, + None, + Some(GrantId::from_bytes([4; 32])), + ) +} +fn checkpoint() -> CheckpointRef { + CheckpointRef::new( + CheckpointDigest::from_bytes([8; 32]), + Sequence::new(0).unwrap(), + Coverage::Partial, + vec![SourceId::from_bytes([9; 32])], + ) + .unwrap() +} +fn context() -> CommandContextData { + CommandContextData::new( + OperationId::from_bytes([1; 32]), + actor(), + WorkspaceId::from_bytes([2; 32]), + AuthorityRef::new( + ExecutorId::from_bytes([3; 32]), + Generation::new(9_007_199_254_740_993).unwrap(), + ), + RouteDigest::from_bytes([5; 32]), + None, + None, + UnixSeconds::new(1_900_000_000).unwrap(), + None, + ) + .unwrap() +} + +#[test] +fn exact_integers_never_round_or_accept_numeric_json_coercions() { + for value in [0, 1, 9_007_199_254_740_993, i64::MAX as u64] { + let sequence = Sequence::new(value).unwrap(); + assert_eq!(sequence.get(), value); + assert_eq!(sequence.to_string().parse::<Sequence>(), Ok(sequence)); + assert_eq!( + serde_json::to_value(sequence).unwrap(), + json!(value.to_string()) + ); + assert_eq!( + serde_json::from_value::<Sequence>(json!(value.to_string())).unwrap(), + sequence + ); + assert!(serde_json::from_value::<Sequence>(json!(value)).is_err()); + if value > 0 { + let generation = Generation::new(value).unwrap(); + assert_eq!(generation.get(), value); + assert_eq!(generation.to_string().parse::<Generation>(), Ok(generation)); + assert_eq!( + serde_json::from_value::<Generation>(json!(value.to_string())).unwrap(), + generation + ); + } + } + for text in [ + "", + "00", + "01", + "-1", + "+1", + "1.0", + "1e2", + " 1", + "1 ", + "1", + "18446744073709551616", + "9223372036854775808", + ] { + assert!(text.parse::<Sequence>().is_err(), "{text:?}"); + assert!(text.parse::<Generation>().is_err()); + assert!(serde_json::from_value::<Sequence>(json!(text)).is_err()); + } + assert!(Generation::new(0).is_err()); + assert!("0".parse::<Generation>().is_err()); + assert!(Sequence::new(u64::MAX).is_err()); + assert!(Generation::new(u64::MAX).is_err()); + for value in [0, 1, 253_402_300_799] { + let timestamp = UnixSeconds::new(value).unwrap(); + assert_eq!(timestamp.get(), value); + assert_eq!(timestamp.to_string().parse::<UnixSeconds>(), Ok(timestamp)); + assert_eq!( + serde_json::from_value::<UnixSeconds>(json!(value.to_string())).unwrap(), + timestamp + ); + assert_eq!( + serde_json::to_value(timestamp).unwrap(), + json!(value.to_string()) + ); + } + assert!(UnixSeconds::new(253_402_300_800).is_err()); + assert!("253402300800".parse::<UnixSeconds>().is_err()); + assert!(serde_json::from_value::<UnixSeconds>(json!(1)).is_err()); +} + +#[test] +fn captured_descriptors_preserve_every_field_and_explicit_null() { + let data = context(); + let wire = serde_json::to_value(&data).unwrap(); + assert_eq!(wire["operation_id"], json!("01".repeat(32))); + assert_eq!(wire["authority"]["generation"], json!("9007199254740993")); + for name in ["approval", "expected", "correlation_id"] { + assert!(wire[name].is_null()); + } + assert_eq!( + serde_json::from_value::<CommandContextData>(wire.clone()).unwrap(), + data + ); + assert_eq!(data.operation_id(), OperationId::from_bytes([1; 32])); + assert_eq!(data.actor(), actor()); + assert_eq!(data.workspace_id(), WorkspaceId::from_bytes([2; 32])); + assert_eq!( + data.authority().executor_id(), + ExecutorId::from_bytes([3; 32]) + ); + assert_eq!(data.authority().generation().get(), 9_007_199_254_740_993); + assert_eq!(data.route_digest(), RouteDigest::from_bytes([5; 32])); + assert_eq!(data.not_after().get(), 1_900_000_000); + assert!( + data.approval().is_none() && data.expected().is_none() && data.correlation_id().is_none() + ); + assert_eq!( + data.actor().participant(), + PublicKey::from_str(KEY).unwrap() + ); + assert_eq!(data.actor().role(), ActorRole::Buyer); + assert_eq!(data.actor().organization(), None); + assert_eq!(data.actor().grant_id(), Some(GrantId::from_bytes([4; 32]))); + for field in ["approval", "expected", "correlation_id"] { + let mut missing = wire.clone(); + missing.as_object_mut().unwrap().remove(field); + assert!( + serde_json::from_value::<CommandContextData>(missing).is_err(), + "required {field}" + ); + } + for field in ["organization", "grant_id"] { + let mut missing = wire.clone(); + missing["actor"].as_object_mut().unwrap().remove(field); + assert!( + serde_json::from_value::<CommandContextData>(missing).is_err(), + "required actor {field}" + ); + } + let raw = serde_json::to_string(&data).unwrap(); + let duplicate = format!("{{\"operation_id\":\"{}\",{}", "ff".repeat(32), &raw[1..]); + assert!(serde_json::from_str::<CommandContextData>(&duplicate).is_err()); + let mut unknown = wire.clone(); + unknown["authenticated"] = json!(true); + assert!(serde_json::from_value::<CommandContextData>(unknown).is_err()); + let mut unknown = wire; + unknown["actor"]["role"] = json!("operator"); + assert!(serde_json::from_value::<CommandContextData>(unknown).is_err()); + assert!(!format!("{data:?}").contains(KEY)); +} + +#[test] +fn complete_preconditions_and_approval_data_remain_untrusted_bounded_values() { + let approval = Approval::new( + ApprovalIntentDigest::from_bytes([6; 32]), + "orders.accept", + UnixSeconds::new(1_900_000_000).unwrap(), + ) + .unwrap(); + assert_eq!( + approval.intent_digest(), + ApprovalIntentDigest::from_bytes([6; 32]) + ); + assert_eq!(approval.scope(), "orders.accept"); + assert_eq!(approval.expires_at().get(), 1_900_000_000); + let expected = ExpectedOrder::new( + OrderId::from_bytes([7; 32]), + Some(RecordId::from_bytes([10; 32])), + Sequence::new(4).unwrap(), + Some(RecordId::from_bytes([11; 32])), + checkpoint(), + ); + assert_eq!(expected.order_id(), OrderId::from_bytes([7; 32])); + assert_eq!(expected.agreement(), Some(RecordId::from_bytes([10; 32]))); + assert_eq!(expected.seller_sequence().get(), 4); + assert_eq!(expected.buyer_head(), Some(RecordId::from_bytes([11; 32]))); + assert_eq!( + expected.checkpoint().digest(), + CheckpointDigest::from_bytes([8; 32]) + ); + assert_eq!(expected.checkpoint().sequence().get(), 0); + assert_eq!(expected.checkpoint().coverage(), Coverage::Partial); + assert_eq!( + expected.checkpoint().missing(), + &[SourceId::from_bytes([9; 32])] + ); + let mut wire = serde_json::to_value(context()).unwrap(); + wire["approval"] = serde_json::to_value(&approval).unwrap(); + wire["expected"] = serde_json::to_value(&expected).unwrap(); + wire["correlation_id"] = json!("synthetic diagnostic"); + let data: CommandContextData = serde_json::from_value(wire.clone()).unwrap(); + assert_eq!(data.approval(), Some(&approval)); + assert_eq!(data.expected(), Some(&expected)); + assert_eq!( + data.correlation_id().unwrap().as_str(), + "synthetic diagnostic" + ); + assert_eq!(serde_json::to_value(&data).unwrap(), wire); + for field in ["agreement", "buyer_head"] { + let mut missing = wire.clone(); + missing["expected"].as_object_mut().unwrap().remove(field); + assert!(serde_json::from_value::<CommandContextData>(missing).is_err()); + } + for nested in ["authority", "approval", "expected"] { + let mut changed = wire.clone(); + changed[nested]["extra"] = Value::Bool(true); + assert!(serde_json::from_value::<CommandContextData>(changed).is_err()); + } + assert!(!format!("{data:?}").contains("synthetic diagnostic")); + assert!(!format!("{approval:?}").contains("orders.accept")); +} + +#[test] +fn bounds_and_coverage_claims_fail_without_echoing_sensitive_text() { + assert!(CorrelationId::new("é".repeat(64)).is_ok()); + assert!(CorrelationId::new("é".repeat(65)).is_err()); + assert!(CorrelationId::new("diagnostic\nsecret").is_err()); + assert_eq!( + serde_json::from_str::<CorrelationId>("\"hello\"") + .unwrap() + .as_str(), + "hello" + ); + assert!(serde_json::from_value::<CorrelationId>(json!("x".repeat(129))).is_err()); + assert!( + !format!("{:?}", CorrelationId::new("private diagnostic").unwrap()) + .contains("private diagnostic") + ); + for scope in [String::new(), "x".repeat(161), "private\ncontext".into()] { + let error = Approval::new( + ApprovalIntentDigest::from_bytes([1; 32]), + scope.clone(), + UnixSeconds::new(1).unwrap(), + ) + .unwrap_err(); + assert_eq!(error, ContextError::InvalidText); + assert!(!error.to_string().contains(&scope) || scope.is_empty()); + } + assert!( + Approval::new( + ApprovalIntentDigest::from_bytes([1; 32]), + "valid", + UnixSeconds::new(0).unwrap() + ) + .is_err() + ); + let digest = CheckpointDigest::from_bytes([2; 32]); + let sequence = Sequence::new(0).unwrap(); + assert!( + CheckpointRef::new( + digest, + sequence, + Coverage::Partial, + vec![SourceId::from_bytes([1; 32]); 128] + ) + .is_ok() + ); + assert_eq!( + CheckpointRef::new( + digest, + sequence, + Coverage::Partial, + vec![SourceId::from_bytes([1; 32]); 129] + ) + .unwrap_err(), + ContextError::TooManyReferences + ); + assert_eq!( + CheckpointRef::new( + digest, + sequence, + Coverage::ScopeSatisfied, + vec![SourceId::from_bytes([1; 32])] + ) + .unwrap_err(), + ContextError::InconsistentCoverage + ); + assert!(CheckpointRef::new(digest, sequence, Coverage::ScopeSatisfied, vec![]).is_ok()); + let mut invalid = serde_json::to_value(context()).unwrap(); + invalid["not_after"] = json!("0"); + assert!(serde_json::from_value::<CommandContextData>(invalid).is_err()); +} diff --git a/crates/domain/tests/identifier.rs b/crates/domain/tests/identifier.rs @@ -7,6 +7,37 @@ use std::{ const SEQUENTIAL: &str = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"; #[test] +fn captured_context_identities_preserve_full_width_and_canonical_encoding() { + macro_rules! check { + ($t:ty) => {{ + let bytes = core::array::from_fn(|i| i as u8); + let id = <$t>::from_bytes(bytes); + assert_eq!(id.as_bytes(), &bytes); + assert_eq!(id.into_bytes(), bytes); + assert_eq!(id.to_string(), SEQUENTIAL); + assert_eq!(SEQUENTIAL.parse::<$t>().unwrap(), id); + assert!("A".repeat(64).parse::<$t>().is_err()); + assert!("0".repeat(63).parse::<$t>().is_err()); + #[cfg(feature = "serde")] + { + let encoded = format!("\"{SEQUENTIAL}\""); + assert_eq!(serde_json::to_string(&id).unwrap(), encoded); + assert_eq!(serde_json::from_str::<$t>(&encoded).unwrap(), id); + assert!(serde_json::from_str::<$t>("1").is_err()); + assert!(serde_json::from_str::<$t>("\"x\"").is_err()); + } + }}; + } + check!(radroots_domain::GrantId); + check!(radroots_domain::RecordId); + check!(radroots_domain::SourceId); + check!(radroots_domain::CommandDigest); + check!(radroots_domain::RouteDigest); + check!(radroots_domain::CheckpointDigest); + check!(radroots_domain::ApprovalIntentDigest); +} + +#[test] fn all_namespaces_match_independent_byte_and_hex_vectors() { let bytes = core::array::from_fn(|i| i as u8); macro_rules! check { diff --git a/crates/execution/Cargo.toml b/crates/execution/Cargo.toml @@ -17,11 +17,13 @@ default = [] session = ["dep:futures"] signer_session = ["session", "dep:radroots_signing"] client_session = ["signer_session"] +workspace_session = ["client_session", "dep:radroots_storage"] [dependencies] radroots_domain = { workspace = true, default-features = false } futures = { workspace = true, optional = true } radroots_signing = { workspace = true, default-features = false, optional = true } +radroots_storage = { workspace = true, default-features = false, optional = true } [dev-dependencies] futures = { workspace = true } diff --git a/crates/execution/README.md b/crates/execution/README.md @@ -85,8 +85,16 @@ unfinished host hook. Hosts must independently preserve their own partial hook progress and obtained results. Dropping an unpolled close performs no shutdown; dropping handles or permits never claims durable completion. -The package is unpublished while the shared facade is migrated. The session -coordinator is tested with controlled hosts; concrete journal/network/browser -hosts still require qualification. It does not yet implement durable commands, -signing, outbox workers, inventory authority, public listing/private chat -execution, participant attachment or bindings. +With `workspace_session`, explicit attachment authenticates a protected +credential through the selected host. `WorkspaceSession::command_context` +purely freezes the captured attachment and all explicit context fields without +I/O or a clock read. Current grant, revision and expiry require revalidation. +The opaque `CommandContext` has no public field constructor or JSON deserializer. +Closing the attachment invalidates its contexts. A custom adapter is an explicit +host trust boundary and requires its own qualification; its observation cannot +establish native SQL authority. An approval descriptor is not consent proof. + +Package upload is not authorized. Actual durable command transactions, outbox +workers, inventory authority, public listing/private chat execution, browser +attachment and new bindings remain separate requirements. Revalidating a context +is not durable admission; the authoritative transaction must recheck its scope. diff --git a/crates/execution/src/error.rs b/crates/execution/src/error.rs @@ -191,6 +191,108 @@ pub struct Error { } impl Error { + #[cfg(feature = "workspace_session")] + pub(crate) const fn workspace( + error: radroots_storage::workspace::WorkspaceError, + operation: Option<OperationId>, + ) -> Self { + use crate::{Field as F, Reason as R}; + use radroots_storage::workspace::WorkspaceError as W; + let (code, retry, field, reason) = match error { + W::InvalidInput => ( + Code::InvalidInput, + RetryClass::Never, + F::Input, + R::OutOfRange, + ), + W::Unauthorized => ( + Code::Unauthorized, + RetryClass::Never, + F::Authority, + R::Missing, + ), + W::GrantExpired => ( + Code::Unauthorized, + RetryClass::AfterStateRefresh, + F::Authority, + R::OutOfRange, + ), + W::GrantRevoked => ( + Code::GrantRevoked, + RetryClass::AfterStateRefresh, + F::Authority, + R::Conflict, + ), + W::WriterActive => ( + Code::MissingAuthority, + RetryClass::AfterStateRefresh, + F::Authority, + R::Conflict, + ), + W::WrongNamespace => ( + Code::Unauthorized, + RetryClass::Never, + F::Authority, + R::Conflict, + ), + W::StaleAuthority => ( + Code::StaleState, + RetryClass::AfterStateRefresh, + F::Authority, + R::Conflict, + ), + W::StaleCheckpoint => ( + Code::StaleState, + RetryClass::AfterStateRefresh, + F::History, + R::Conflict, + ), + W::Unavailable => ( + Code::CapabilityUnavailable, + RetryClass::Never, + F::Authority, + R::Unavailable, + ), + W::Closed => ( + Code::CapabilityUnavailable, + RetryClass::Never, + F::Operation, + R::Unavailable, + ), + W::StorageFailure => ( + Code::StorageFailure, + RetryClass::Never, + F::Storage, + R::Unavailable, + ), + W::NamespaceUnavailable => ( + Code::RecoveryRequired, + RetryClass::ManualReconciliation, + F::Storage, + R::Unavailable, + ), + // Attachment/context are pre-admission. An adapter's uncertain + // mutation cannot be reported as this command's confirmed admission. + W::RecoveryRequired | W::CommitUnknown => ( + Code::RecoveryRequired, + RetryClass::ManualReconciliation, + F::Storage, + R::Unknown, + ), + _ => ( + Code::RecoveryRequired, + RetryClass::ManualReconciliation, + F::Authority, + R::Unknown, + ), + }; + Self { + code, + context: OperationContext::proposed(operation), + retry, + detail: Some(Detail::new(field, reason)), + } + } #[cfg(feature = "client_session")] pub(crate) const fn identity_changed() -> Self { Self { diff --git a/crates/execution/src/lib.rs b/crates/execution/src/lib.rs @@ -12,6 +12,9 @@ extern crate std; #[cfg(feature = "session")] pub mod session; +#[cfg(feature = "workspace_session")] +pub mod workspace; + pub use diagnostic::{Detail, Field, Reason}; pub use error::{Admission, Code, Error, InvalidErrorContext, OperationContext, RetryClass}; diff --git a/crates/execution/src/session/client.rs b/crates/execution/src/session/client.rs @@ -9,8 +9,14 @@ use std::{ struct Resources<H> { host: H, signer: Shared<Mutex<Option<SignerSession>>>, + #[cfg(feature = "workspace_session")] + workspaces: WorkspaceScopes, host_quiesced: Mutex<bool>, } +#[cfg(feature = "workspace_session")] +type WorkspaceScopes = Shared<Mutex<std::vec::Vec<crate::workspace::WorkspaceSession>>>; +#[cfg(feature = "workspace_session")] +const MAX_WORKSPACE_SCOPES: usize = 16; fn signer_lock(value: &Mutex<Option<SignerSession>>) -> MutexGuard<'_, Option<SignerSession>> { value .lock() @@ -22,6 +28,16 @@ impl<H: SessionHost> SessionHost for Resources<H> { } fn quiesce(&self) -> HostFuture<'_, crate::Result<()>> { Box::pin(async move { + #[cfg(feature = "workspace_session")] + { + let scopes = self + .workspaces + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + for scope in scopes.iter() { + scope.close(); + } + } let quiesced = *self .host_quiesced .lock() @@ -64,12 +80,16 @@ impl<H: SessionHost> SessionHost for Resources<H> { pub struct ClientSession<H: SessionHost> { session: Session<Resources<H>>, signer: Shared<Mutex<Option<SignerSession>>>, + #[cfg(feature = "workspace_session")] + workspaces: WorkspaceScopes, } impl<H: SessionHost> Clone for ClientSession<H> { fn clone(&self) -> Self { Self { session: self.session.clone(), signer: self.signer.clone(), + #[cfg(feature = "workspace_session")] + workspaces: self.workspaces.clone(), } } } @@ -77,16 +97,22 @@ impl<H: SessionHost> ClientSession<H> { /// Owns resources without starting workers, observing a signer or networking. pub fn new(host: H, maximum_in_flight: NonZeroU16) -> Self { let signer = Shared::new(Mutex::new(None)); + #[cfg(feature = "workspace_session")] + let workspaces = Shared::new(Mutex::new(std::vec::Vec::new())); Self { session: Session::new( Resources { host, signer: signer.clone(), + #[cfg(feature = "workspace_session")] + workspaces: workspaces.clone(), host_quiesced: Mutex::new(false), }, maximum_in_flight, ), signer, + #[cfg(feature = "workspace_session")] + workspaces, } } /// Reports resource lifecycle independently of business authority. @@ -134,6 +160,41 @@ impl<H: SessionHost> ClientSession<H> { pub fn signer_session(&self) -> Option<SignerSession> { signer_lock(&self.signer).clone() } + /// Authenticates attachment while sharing the client's permanent resource + /// admission gate. The concrete client owns the store through actual close. + #[cfg(feature = "workspace_session")] + pub async fn attach_workspace( + &self, + store: Shared<dyn radroots_storage::workspace::WorkspaceStore>, + input: radroots_storage::workspace::AttachmentInput, + proof: radroots_storage::workspace::AttachmentProof, + ) -> crate::Result<crate::workspace::WorkspaceSession> { + let _permit = self.session.retain_resource()?; + let scope = crate::workspace::WorkspaceSession::attach(store, input, proof).await?; + // Retired adapter roots may run host Drop code. Keep them alive until + // after the registry guard is released, including every error return. + let mut retired = std::vec::Vec::new(); + let mut scopes = self + .workspaces + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + retired.extend(scopes.extract_if(.., |scope| scope.is_closed())); + if matches!(self.state(), SessionState::Closing | SessionState::Closed) { + scope.close(); + return Err(crate::Error::workspace( + radroots_storage::workspace::WorkspaceError::Closed, + None, + )); + } + if scopes.len() >= MAX_WORKSPACE_SCOPES { + scope.close(); + return Err(crate::Error::session_unavailable(crate::Reason::OutOfRange)); + } + scopes.push(scope.clone()); + drop(scopes); + drop(retired); + Ok(scope) + } /// Stops admission, quiesces callbacks, drains work, disconnects transports, /// disposes callbacks and closes storage last. Cancellation is resumable. pub async fn close(&self) -> crate::Result<()> { diff --git a/crates/execution/src/session/mod.rs b/crates/execution/src/session/mod.rs @@ -4,7 +4,7 @@ //! caller's observation future, retains each work permit until its safe boundary. //! A permit is resource ownership, never proof of durable command admission. -mod host; +pub(crate) mod host; #[cfg(feature = "client_session")] mod client; diff --git a/crates/execution/src/workspace.rs b/crates/execution/src/workspace.rs @@ -0,0 +1,205 @@ +//! Authenticated attachment and immutable captured command context. +//! +//! Descriptors and observed signer keys cannot construct these capabilities. +//! Current grant verification remains mandatory at authoritative admission; +//! attachment and context construction are not durable command submission. + +use crate::session::host::Shared; +use radroots_domain::{ + Approval, CommandContextData, CorrelationId, ExpectedOrder, OperationId, UnixSeconds, +}; +use radroots_storage::workspace::{ + AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceError, WorkspaceStore, +}; +use std::{ + fmt, + sync::{ + Mutex, + atomic::{AtomicBool, Ordering}, + }, +}; + +struct Attached { + store: Shared<dyn WorkspaceStore>, + proof: Mutex<Option<AttachmentProof>>, + binding: WorkspaceBinding, + closed: AtomicBool, +} +impl Attached { + async fn current(&self) -> Result<WorkspaceBinding, WorkspaceError> { + if self.closed.load(Ordering::Acquire) { + return Err(WorkspaceError::Closed); + } + let proof = self + .proof + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_ref() + .ok_or(WorkspaceError::Closed)? + .with_secret(|secret| AttachmentProof::from_protected_input(secret))?; + if self.closed.load(Ordering::Acquire) { + return Err(WorkspaceError::Closed); + } + let current = self + .store + .authenticate(self.binding.input().clone(), proof) + .await?; + if self.closed.load(Ordering::Acquire) { + return Err(WorkspaceError::Closed); + } + if current.input() != self.binding.input() + || current.actor() != self.binding.actor() + || current.principal_id() != self.binding.principal_id() + || current.grant_revision() != self.binding.grant_revision() + || current.expires_at() != self.binding.expires_at() + { + return Err(WorkspaceError::GrantRevoked); + } + Ok(current) + } +} + +/// An owned authenticated attachment to the explicitly configured workspace. +/// Clones retain one captured grant and permanently shared close gate. +#[derive(Clone)] +pub struct WorkspaceSession { + attached: Shared<Attached>, +} +impl WorkspaceSession { + /// Authenticates the protected credential through a qualified host adapter. + /// Supplying a custom adapter is an explicit host trust boundary; metadata + /// returned by an unqualified adapter cannot qualify native SQL authority. + pub async fn attach( + store: Shared<dyn WorkspaceStore>, + input: AttachmentInput, + proof: AttachmentProof, + ) -> crate::Result<Self> { + let request_proof = proof + .with_secret(|secret| AttachmentProof::from_protected_input(secret)) + .map_err(|error| crate::Error::workspace(error, None))?; + let binding = store + .authenticate(input.clone(), request_proof) + .await + .map_err(|error| crate::Error::workspace(error, None))?; + if binding.input() != &input { + return Err(crate::Error::workspace(WorkspaceError::Unauthorized, None)); + } + Ok(Self { + attached: Shared::new(Attached { + store, + proof: Mutex::new(Some(proof)), + binding, + closed: AtomicBool::new(false), + }), + }) + } + /// Borrows the captured grant observation, without claiming it is current. + pub fn binding(&self) -> &WorkspaceBinding { + &self.attached.binding + } + /// Purely captures the complete context from the authenticated attachment. + /// This performs no clock, storage, signer or network operation. Current + /// rights and deadline must be revalidated at authoritative admission. + /// Approval remains a descriptor; authoritative commands must additionally + /// verify its protected consent origin and exact command intent. + pub fn command_context( + &self, + operation_id: OperationId, + expected: Option<ExpectedOrder>, + approval: Option<Approval>, + not_after: UnixSeconds, + ) -> crate::Result<CommandContext> { + self.command_context_with_correlation(operation_id, expected, approval, not_after, None) + } + /// Captures an optional bounded diagnostic correlation value. Correlation + /// supplies neither authorization nor semantic idempotency. + pub fn command_context_with_correlation( + &self, + operation_id: OperationId, + expected: Option<ExpectedOrder>, + approval: Option<Approval>, + not_after: UnixSeconds, + correlation: Option<CorrelationId>, + ) -> crate::Result<CommandContext> { + let failure = |error| crate::Error::workspace(error, Some(operation_id)); + if self.attached.closed.load(Ordering::Acquire) { + return Err(failure(WorkspaceError::Closed)); + } + let current = &self.attached.binding; + let input = current.input(); + let data = CommandContextData::new( + operation_id, + current.actor(), + input.workspace_id(), + input.authority(), + input.route_digest(), + approval, + expected, + not_after, + correlation, + ) + .map_err(|_| failure(WorkspaceError::InvalidInput))?; + if not_after <= current.observed_at() || not_after > current.expires_at() { + return Err(failure(WorkspaceError::GrantExpired)); + } + Ok(CommandContext { + data, + attached: self.attached.clone(), + }) + } + /// Permanently closes this attachment and every context it has issued. + /// Releases its credential root; owned in-flight requests retain only their + /// own zeroizing input until the adapter's safe completion boundary. + /// It does not revoke the persisted grant or close other workspace sessions. + pub fn close(&self) { + self.attached.closed.store(true, Ordering::Release); + self.attached + .proof + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); + } + pub(crate) fn is_closed(&self) -> bool { + self.attached.closed.load(Ordering::Acquire) + } +} +impl fmt::Debug for WorkspaceSession { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("WorkspaceSession(<redacted>)") + } +} + +/// Authenticated captured context. There is no public field constructor or +/// deserializer from the corresponding untrusted Domain DTO. +/// +/// ```compile_fail +/// use radroots_domain::CommandContextData; +/// use radroots_execution::workspace::CommandContext; +/// fn trust_unchecked(data: CommandContextData) -> CommandContext { data } +/// ``` +pub struct CommandContext { + data: CommandContextData, + attached: Shared<Attached>, +} +impl CommandContext { + /// Borrows the exact captured descriptor without transferring authority. + pub const fn data(&self) -> &CommandContextData { + &self.data + } + /// Revalidates current grant and deadline before an executor prepares its + /// authoritative transaction. The transaction itself must check them again; + /// this observation is not T0, a retained operation or stock admission. + pub async fn revalidate(&self) -> crate::Result<WorkspaceBinding> { + let failure = |error| crate::Error::workspace(error, Some(self.data.operation_id())); + let current = self.attached.current().await.map_err(failure)?; + if self.data.not_after() <= current.observed_at() { + return Err(failure(WorkspaceError::GrantExpired)); + } + Ok(current) + } +} +impl fmt::Debug for CommandContext { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CommandContext(<redacted>)") + } +} diff --git a/crates/execution/tests/workspace.rs b/crates/execution/tests/workspace.rs @@ -0,0 +1,378 @@ +#![cfg(feature = "workspace_session")] +// Port-model tests for captured context invariants. Concrete native credential, +// persistence and cancellation qualification belongs to its actual backend. +use futures::{executor::block_on, task::AtomicWaker}; +use radroots_domain::*; +use radroots_execution::session::{ClientSession, HostFuture, SessionHost}; +use radroots_execution::workspace::WorkspaceSession; +use radroots_storage::workspace::{ + AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceError, WorkspaceStore, +}; +#[cfg(target_arch = "wasm32")] +use std::rc::Rc as Shared; +#[cfg(not(target_arch = "wasm32"))] +use std::sync::Arc as Shared; +use std::{ + future::poll_fn, + sync::{ + Mutex, + atomic::{AtomicBool, Ordering}, + }, + task::Poll, +}; + +struct Model { + binding: Mutex<WorkspaceBinding>, + error: Mutex<Option<WorkspaceError>>, + pending: AtomicBool, + waker: AtomicWaker, +} +impl WorkspaceStore for Model { + fn authenticate( + &self, + _input: AttachmentInput, + _proof: AttachmentProof, + ) -> radroots_storage::event::BoxFuture<'_, Result<WorkspaceBinding, WorkspaceError>> { + Box::pin(async move { + poll_fn(|cx| { + self.waker.register(cx.waker()); + if self.pending.load(Ordering::Acquire) { + Poll::Pending + } else { + Poll::Ready(()) + } + }) + .await; + if let Some(error) = *self.error.lock().unwrap() { + return Err(error); + } + Ok(self.binding.lock().unwrap().clone()) + }) + } + fn close_workspace( + &self, + ) -> radroots_storage::event::BoxFuture<'_, Result<(), WorkspaceError>> { + Box::pin(async { Ok(()) }) + } +} +fn key() -> PublicKey { + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() +} +fn input(route: u8) -> AttachmentInput { + AttachmentInput::new( + WorkspaceId::from_bytes([1; 32]), + AuthorityRef::new(ExecutorId::from_bytes([2; 32]), Generation::new(1).unwrap()), + key(), + "local://model", + key(), + GrantId::from_bytes([3; 32]), + CheckpointRef::new( + CheckpointDigest::from_bytes([4; 32]), + Sequence::new(0).unwrap(), + Coverage::Partial, + vec![], + ) + .unwrap(), + RouteDigest::from_bytes([route; 32]), + ) + .unwrap() +} +fn binding(change: u8, observed: u64) -> WorkspaceBinding { + let input = input(if change == 1 { 9 } else { 5 }); + WorkspaceBinding::from_authenticated_host( + input.clone(), + ActorRef::new( + key(), + if change == 2 { + ActorRole::Seller + } else { + ActorRole::Buyer + }, + None, + Some(input.grant_id()), + ), + if change == 3 { + "other-device" + } else { + "device" + }, + Sequence::new(if change == 4 { 2 } else { 1 }).unwrap(), + UnixSeconds::new(if change == 5 { 201 } else { 200 }).unwrap(), + UnixSeconds::new(observed).unwrap(), + ) + .unwrap() +} +fn new_model() -> Shared<Model> { + Shared::new(Model { + binding: Mutex::new(binding(0, 100)), + error: Mutex::new(None), + pending: AtomicBool::new(false), + waker: AtomicWaker::new(), + }) +} +fn proof() -> AttachmentProof { + AttachmentProof::from_protected_input(&[7; 32]).unwrap() +} + +struct Host; +impl SessionHost for Host { + fn start(&self) -> HostFuture<'_, radroots_execution::Result<()>> { + Box::pin(async { Ok(()) }) + } + fn quiesce(&self) -> HostFuture<'_, radroots_execution::Result<()>> { + Box::pin(async { Ok(()) }) + } + fn disconnect(&self) -> HostFuture<'_, radroots_execution::Result<()>> { + Box::pin(async { Ok(()) }) + } + fn dispose_callbacks(&self) -> HostFuture<'_, radroots_execution::Result<()>> { + Box::pin(async { Ok(()) }) + } + fn close_storage(&self) -> HostFuture<'_, radroots_execution::Result<()>> { + Box::pin(async { Ok(()) }) + } +} +#[test] +fn client_bounds_and_retires_scopes_and_refuses_attachment_finishing_after_quiesce() { + block_on(async { + let model = new_model(); + let client = ClientSession::new(Host, core::num::NonZeroU16::MIN); + let mut scopes = Vec::new(); + for _ in 0..16 { + scopes.push( + client + .attach_workspace(model.clone(), input(5), proof()) + .await + .unwrap(), + ); + } + assert_eq!( + client + .attach_workspace(model.clone(), input(5), proof()) + .await + .unwrap_err() + .code(), + radroots_execution::Code::CapabilityUnavailable + ); + scopes[0].close(); + scopes.push( + client + .attach_workspace(model.clone(), input(5), proof()) + .await + .unwrap(), + ); + model.pending.store(true, Ordering::Release); + let mut attachment = Box::pin(client.attach_workspace(model.clone(), input(5), proof())); + assert!(futures::poll!(attachment.as_mut()).is_pending()); + let mut closing = Box::pin(client.close()); + assert!(futures::poll!(closing.as_mut()).is_pending()); + for scope in &scopes { + assert!( + scope + .command_context( + OperationId::from_bytes([10; 32]), + None, + None, + UnixSeconds::new(150).unwrap() + ) + .is_err() + ); + } + model.pending.store(false, Ordering::Release); + model.waker.wake(); + assert_eq!( + attachment.await.unwrap_err().code(), + radroots_execution::Code::CapabilityUnavailable + ); + closing.await.unwrap(); + assert!( + client + .attach_workspace(model, input(5), proof()) + .await + .is_err() + ); + }) +} +#[test] +fn captured_context_retains_all_fields_and_refuses_each_semantic_grant_change() { + block_on(async { + let model = new_model(); + let session = WorkspaceSession::attach(model.clone(), input(5), proof()) + .await + .unwrap(); + let expected = ExpectedOrder::new( + OrderId::from_bytes([8; 32]), + None, + Sequence::new(0).unwrap(), + None, + input(5).checkpoint().clone(), + ); + let approval = Approval::new( + ApprovalIntentDigest::from_bytes([9; 32]), + "scope", + UnixSeconds::new(160).unwrap(), + ) + .unwrap(); + let context = session + .command_context_with_correlation( + OperationId::from_bytes([10; 32]), + Some(expected.clone()), + Some(approval.clone()), + UnixSeconds::new(150).unwrap(), + Some(CorrelationId::new("diagnostic").unwrap()), + ) + .unwrap(); + assert_eq!(context.data().expected(), Some(&expected)); + assert_eq!(context.data().approval(), Some(&approval)); + assert_eq!(context.data().actor(), session.binding().actor()); + assert_eq!(format!("{session:?}"), "WorkspaceSession(<redacted>)"); + assert_eq!(format!("{context:?}"), "CommandContext(<redacted>)"); + context.revalidate().await.unwrap(); + for change in 1..=5 { + *model.binding.lock().unwrap() = binding(change, 100); + assert_eq!( + context.revalidate().await.unwrap_err().code(), + radroots_execution::Code::GrantRevoked + ); + } + *model.binding.lock().unwrap() = binding(0, 150); + assert_eq!( + context.revalidate().await.unwrap_err().code(), + radroots_execution::Code::Unauthorized + ); + *model.binding.lock().unwrap() = binding(0, 100); + for deadline in [0, 100, 201] { + assert!( + session + .command_context( + OperationId::from_bytes([10; 32]), + None, + None, + UnixSeconds::new(deadline).unwrap() + ) + .is_err() + ); + } + *model.error.lock().unwrap() = Some(WorkspaceError::Unavailable); + // Construction is pure even while the host is unavailable; admission must + // perform the separate current-rights check and refuse this unavailable host. + session + .command_context( + OperationId::from_bytes([10; 32]), + None, + None, + UnixSeconds::new(150).unwrap(), + ) + .unwrap(); + assert_eq!( + context.revalidate().await.unwrap_err().code(), + radroots_execution::Code::CapabilityUnavailable + ); + }) +} + +#[test] +fn pre_admission_workspace_errors_retain_proposed_identity_and_typed_uncertainty() { + block_on(async { + use WorkspaceError as W; + use radroots_execution::{Admission, Code as C, RetryClass}; + let model = new_model(); + let session = WorkspaceSession::attach(model.clone(), input(5), proof()) + .await + .unwrap(); + let operation = OperationId::from_bytes([10; 32]); + let context = session + .command_context(operation, None, None, UnixSeconds::new(150).unwrap()) + .unwrap(); + for (source, code) in [ + (W::InvalidInput, C::InvalidInput), + (W::Unauthorized, C::Unauthorized), + (W::GrantExpired, C::Unauthorized), + (W::GrantRevoked, C::GrantRevoked), + (W::WriterActive, C::MissingAuthority), + (W::WrongNamespace, C::Unauthorized), + (W::StaleAuthority, C::StaleState), + (W::StaleCheckpoint, C::StaleState), + (W::Unavailable, C::CapabilityUnavailable), + (W::Closed, C::CapabilityUnavailable), + (W::StorageFailure, C::StorageFailure), + (W::NamespaceUnavailable, C::RecoveryRequired), + (W::RecoveryRequired, C::RecoveryRequired), + (W::CommitUnknown, C::RecoveryRequired), + ] { + *model.error.lock().unwrap() = Some(source); + let error = context.revalidate().await.unwrap_err(); + assert_eq!(error.code(), code); + assert_eq!(error.context().operation_id(), Some(operation)); + assert_eq!(error.context().admission(), Admission::NotAdmitted); + assert!(error.detail().is_some()); + if source == W::CommitUnknown { + assert_eq!(error.retry(), RetryClass::ManualReconciliation); + } + } + }) +} +#[test] +fn attachment_never_trusts_an_adapter_result_for_another_selection() { + block_on(async { + let model = new_model(); + *model.binding.lock().unwrap() = binding(1, 100); + assert_eq!( + WorkspaceSession::attach(model, input(5), proof()) + .await + .unwrap_err() + .code(), + radroots_execution::Code::Unauthorized + ); + let model = new_model(); + *model.error.lock().unwrap() = Some(WorkspaceError::Unauthorized); + assert_eq!( + WorkspaceSession::attach(model, input(5), proof()) + .await + .unwrap_err() + .code(), + radroots_execution::Code::Unauthorized + ); + }) +} +#[test] +fn close_invalidates_clones_and_an_already_pending_context_revalidation() { + block_on(async { + let model = new_model(); + let session = WorkspaceSession::attach(model.clone(), input(5), proof()) + .await + .unwrap(); + let context = session + .command_context( + OperationId::from_bytes([10; 32]), + None, + None, + UnixSeconds::new(150).unwrap(), + ) + .unwrap(); + model.pending.store(true, Ordering::Release); + let mut pending = Box::pin(context.revalidate()); + assert!(futures::poll!(pending.as_mut()).is_pending()); + session.clone().close(); + model.pending.store(false, Ordering::Release); + model.waker.wake(); + assert_eq!( + pending.await.unwrap_err().code(), + radroots_execution::Code::CapabilityUnavailable + ); + assert_eq!( + context.revalidate().await.unwrap_err().code(), + radroots_execution::Code::CapabilityUnavailable + ); + assert!( + session + .command_context( + OperationId::from_bytes([10; 32]), + None, + None, + UnixSeconds::new(150).unwrap() + ) + .is_err() + ); + }) +} diff --git a/crates/radroots/Cargo.toml b/crates/radroots/Cargo.toml @@ -38,7 +38,7 @@ path = "src/lib.rs" [dependencies] radroots_core = { workspace = true } radroots_domain = { workspace = true, features = ["std", "serde"] } -radroots_execution = { workspace = true, features = ["client_session"] } +radroots_execution = { workspace = true, features = ["client_session", "workspace_session"] } radroots_event = { workspace = true } radroots_identity = { workspace = true, features = ["std"] } radroots_sdk = { workspace = true } @@ -61,6 +61,7 @@ knowledge = ["client", "radroots_sdk/knowledge"] full = ["native", "radroots_sdk/full"] [dev-dependencies] +radroots_secrets = { workspace = true, features = ["file"] } futures = { workspace = true } radroots_event_codec = { workspace = true, default-features = false } radroots_nostr = { workspace = true, features = ["signing"] } diff --git a/crates/radroots/README.md b/crates/radroots/README.md @@ -25,9 +25,14 @@ With `native`, `Client::open(NativeConfig::public_read(options)).await` opens the actual SQLite cache from explicit validated host paths, mode and source generation. It performs no networking or automatic command replay. This public cache scope does not open an authenticated participant workspace or create -seller stock authority. Protected workspace/authority opening, network workers, -complete command receipts and durable listing/chat operations remain separate -unfinished implementation requirements. +seller stock authority. On Unix, explicitly adding an opened protected +`NativeWorkspace` with `NativeConfig::with_workspace` enables `Client::attach`. +Attachment verifies its persisted credential and exact selection before returning +`WorkspaceSession`. That session constructs opaque, immutable command contexts +without I/O or a clock read; admission must recheck current rights and expiry. +A context does not submit a command or prove +user consent; network pairing, seller authority, complete command receipts and +durable listing/chat operations remain separate implementation requirements. `attach_signer` observes the concrete provider only after retaining its callback scope. The first successful key freezes and later drift invalidates that scope. diff --git a/crates/radroots/src/client.rs b/crates/radroots/src/client.rs @@ -21,6 +21,15 @@ const STORAGE_FAILURE: Error = match Error::new( Ok(error) => error, Err(_) => panic!("invalid constant pre-admission storage error"), }; +const MISSING_WORKSPACE: Error = match Error::new( + Code::MissingAuthority, + OperationContext::proposed(None), + RetryClass::AfterStateRefresh, + None, +) { + Ok(error) => error, + Err(_) => panic!("invalid constant pre-admission workspace error"), +}; /// Explicit task admission for a local resource session. No network is selected. #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -65,18 +74,33 @@ impl CloseReceipt { #[cfg(feature = "native")] pub struct NativeConfig { options: radroots_storage_sqlite::OpenOptions, + workspace: Option<Shared<dyn radroots_storage::workspace::WorkspaceStore>>, } #[cfg(feature = "native")] impl NativeConfig { /// Uses the host's validated paths/mode and explicit source generation for /// a public cache. Construction opens no file and starts no worker/network. pub fn public_read(options: radroots_storage_sqlite::OpenOptions) -> Self { - Self { options } + Self { + options, + workspace: None, + } + } + /// Adds an explicitly opened protected local outbox. A public cache alone + /// cannot create this resource or establish a workspace grant. + #[cfg(unix)] + pub fn with_workspace( + mut self, + workspace: radroots_storage_sqlite::workspace::NativeWorkspace, + ) -> Self { + self.workspace = Some(Shared::new(workspace)); + self } } struct StoreHost { store: Shared<dyn Storage>, + workspace: Option<Shared<dyn radroots_storage::workspace::WorkspaceStore>>, closed: Shared<Mutex<Option<CloseReceipt>>>, } impl SessionHost for StoreHost { @@ -94,6 +118,12 @@ impl SessionHost for StoreHost { } fn close_storage(&self) -> HostFuture<'_, crate::Result<()>> { Box::pin(async move { + if let Some(workspace) = &self.workspace { + workspace + .close_workspace() + .await + .map_err(|_| STORAGE_FAILURE)?; + } let status = self.store.close().await.map_err(|_| STORAGE_FAILURE)?; let receipt = CloseReceipt::confirmed(status)?; *self @@ -113,15 +143,20 @@ impl SessionHost for StoreHost { pub struct Client { session: ClientSession<StoreHost>, store: Shared<dyn Storage>, + workspace: Option<Shared<dyn radroots_storage::workspace::WorkspaceStore>>, closed: Shared<Mutex<Option<CloseReceipt>>>, } impl Client { #[cfg(any(feature = "client", feature = "native"))] - fn from_store(store: Shared<dyn Storage>) -> Self { + fn from_store( + store: Shared<dyn Storage>, + workspace: Option<Shared<dyn radroots_storage::workspace::WorkspaceStore>>, + ) -> Self { let closed = Shared::new(Mutex::new(None)); let session = ClientSession::new( StoreHost { store: store.clone(), + workspace: workspace.clone(), closed: closed.clone(), }, NonZeroU16::MIN, @@ -129,6 +164,7 @@ impl Client { Self { session, store, + workspace, closed, } } @@ -141,9 +177,10 @@ impl Client { Ok(generation) => generation, Err(_) => panic!("invalid constant preview generation"), }; - Self::from_store(Shared::new(radroots_storage::memory::MemoryStorage::new( - GENERATION, - ))) + Self::from_store( + Shared::new(radroots_storage::memory::MemoryStorage::new(GENERATION)), + None, + ) } /// Opens the actual native SQLite cache using explicit host options. This /// reads no participant key and performs no network or automatic replay. @@ -152,7 +189,7 @@ impl Client { let store = radroots_storage_sqlite::SqliteStorage::open(config.options) .await .map_err(|_| STORAGE_FAILURE)?; - Ok(Self::from_store(Shared::new(store))) + Ok(Self::from_store(Shared::new(store), config.workspace)) } /// Observes resource lifecycle without probing signer, store or network. pub fn state(&self) -> SessionState { @@ -184,6 +221,16 @@ impl Client { pub fn signer_session(&self) -> Option<SignerSession> { self.session.signer_session() } + /// Authenticates a protected grant in the explicitly configured workspace. + /// Signer observations and arbitrary descriptors cannot supply this grant. + pub async fn attach( + &self, + input: radroots_storage::workspace::AttachmentInput, + proof: radroots_storage::workspace::AttachmentProof, + ) -> crate::Result<radroots_execution::workspace::WorkspaceSession> { + let workspace = self.workspace.clone().ok_or(MISSING_WORKSPACE)?; + self.session.attach_workspace(workspace, input, proof).await + } /// Permanently stops admission, drains resources and scoped callbacks, then /// closes the actual store last. Failed/cancelled closure must be resumed. pub async fn close(&self) -> crate::Result<CloseReceipt> { diff --git a/crates/radroots/src/lib.rs b/crates/radroots/src/lib.rs @@ -20,4 +20,6 @@ pub mod transport; pub use client::NativeConfig; pub use client::{Client, CloseReceipt, SessionStatus, StartMode}; pub use radroots_domain::OperationId; +pub use radroots_execution::workspace::{CommandContext, WorkspaceSession}; pub use radroots_execution::{Error, Result}; +pub use radroots_storage::workspace::{AttachmentInput, AttachmentProof}; diff --git a/crates/radroots/tests/package_boundary.rs b/crates/radroots/tests/package_boundary.rs @@ -57,7 +57,13 @@ fn root_has_exact_exports_and_no_sdk_namespace() { assert!(!ROOT.contains("pub mod sdk")); assert!(!ROOT.contains("pub use radroots_sdk::*")); assert!(ROOT.contains("pub use radroots_domain::OperationId;")); - assert_eq!(ROOT.matches("pub use ").count(), 4); + assert!( + ROOT.contains("pub use radroots_execution::workspace::{CommandContext, WorkspaceSession};") + ); + assert!( + ROOT.contains("pub use radroots_storage::workspace::{AttachmentInput, AttachmentProof};") + ); + assert_eq!(ROOT.matches("pub use ").count(), 6); assert!(README.contains("```compile_fail\nuse radroots::sdk;\n```")); } diff --git a/crates/radroots/tests/workspace.rs b/crates/radroots/tests/workspace.rs @@ -0,0 +1,247 @@ +#![cfg(all(feature = "native", unix))] +use radroots::{Client, NativeConfig, OperationId, StartMode}; +use radroots_domain::{ + Approval, ApprovalIntentDigest, CorrelationId, ExpectedOrder, OrderId, PublicKey, RecordId, + Sequence, UnixSeconds, +}; +use radroots_secrets::{ + SecretId, SecretRef, + envelope::Nonce, + file::{FileOpenMode, FileProvider}, + id::{BackendKind, KeyVersion}, + provider::AccessPolicy, + wrapping::SecretMaterial, +}; +use radroots_storage::{ + event::SourceGeneration, + workspace::{AttachmentProof, WorkspaceClock, WorkspaceError}, +}; +use radroots_storage_sqlite::{ + OpenMode, OpenOptions, Paths, + workspace::{LocalOutboxConfig, NativeWorkspace, WorkspaceCrypto}, +}; +use std::sync::{ + Arc, + atomic::{AtomicU64, Ordering}, +}; +struct Clock(AtomicU64); +impl WorkspaceClock for Clock { + fn now(&self) -> Result<UnixSeconds, WorkspaceError> { + UnixSeconds::new(self.0.load(Ordering::SeqCst)).map_err(|_| WorkspaceError::Unavailable) + } +} +fn key() -> PublicKey { + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() +} +#[tokio::test] +async fn ordinary_client_authenticates_context_and_closes_actual_workspace() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let provider = Arc::new( + FileProvider::open( + root.join("vault"), + FileOpenMode::CreateNew, + SecretMaterial::from_slice(&[0xA5; 32]).unwrap(), + ) + .unwrap(), + ); + let reference = || { + SecretRef::new( + SecretId::parse("workspace-key").unwrap(), + BackendKind::File, + KeyVersion::new(1).unwrap(), + ) + }; + provider + .provision( + &reference(), + &SecretMaterial::from_slice(&[0x41; 32]).unwrap(), + Nonce::new([0x11; 24]), + ) + .unwrap(); + let crypto = || { + WorkspaceCrypto::new( + provider.clone(), + reference(), + SecretMaterial::from_slice(&[0x41; 32]).unwrap(), + AccessPolicy::standard(), + ) + .unwrap() + }; + let clock = Arc::new(Clock(AtomicU64::new(100))); + let config = LocalOutboxConfig::new( + key(), + key(), + "synthetic-device", + UnixSeconds::new(200).unwrap(), + ) + .unwrap(); + let (workspace, input, proof) = NativeWorkspace::initialize_local_outbox( + &root.join("outbox"), + config, + crypto(), + clock.clone(), + ) + .await + .unwrap(); + let workspace_copy = workspace.clone(); + let options = OpenOptions::new( + Paths::from_directory(root.join("cache")).unwrap(), + OpenMode::Create, + ) + .with_source_generation(SourceGeneration::new([17; 32]).unwrap(), 1) + .unwrap(); + // The existing public cache adapter requires its explicit directory to exist. + std::fs::create_dir(root.join("cache")).unwrap(); + let client = Client::open(NativeConfig::public_read(options).with_workspace(workspace)) + .await + .unwrap(); + let wrong = AttachmentProof::from_protected_input(&[0; 32]).unwrap(); + assert_eq!( + client + .attach(input.clone(), wrong) + .await + .unwrap_err() + .code(), + radroots_execution::Code::Unauthorized + ); + let duplicate = proof + .with_secret(|secret| AttachmentProof::from_protected_input(secret)) + .unwrap(); + let other_proof = proof + .with_secret(|secret| AttachmentProof::from_protected_input(secret)) + .unwrap(); + let session = client.attach(input.clone(), proof).await.unwrap(); + assert_eq!(session.binding().actor().participant(), key()); + let op = OperationId::from_bytes([7; 32]); + let approval = Approval::new( + ApprovalIntentDigest::from_bytes([8; 32]), + "known-kind", + UnixSeconds::new(160).unwrap(), + ) + .unwrap(); + let expected = ExpectedOrder::new( + OrderId::from_bytes([9; 32]), + Some(RecordId::from_bytes([10; 32])), + Sequence::new(11).unwrap(), + Some(RecordId::from_bytes([12; 32])), + input.checkpoint().clone(), + ); + let context = session + .command_context_with_correlation( + op, + Some(expected.clone()), + Some(approval.clone()), + UnixSeconds::new(150).unwrap(), + Some(CorrelationId::new("diagnostic").unwrap()), + ) + .unwrap(); + let data = context.data(); + assert_eq!(data.operation_id(), op); + assert_eq!(data.actor(), session.binding().actor()); + assert_eq!(data.workspace_id(), input.workspace_id()); + assert_eq!(data.authority(), input.authority()); + assert_eq!(data.route_digest(), input.route_digest()); + assert_eq!(data.approval(), Some(&approval)); + assert_eq!(data.expected(), Some(&expected)); + assert_eq!(data.not_after().get(), 150); + assert_eq!(data.correlation_id().unwrap().as_str(), "diagnostic"); + context.revalidate().await.unwrap(); + assert_eq!(format!("{context:?}"), "CommandContext(<redacted>)"); + assert_eq!(format!("{session:?}"), "WorkspaceSession(<redacted>)"); + assert!( + session + .command_context(op, None, None, UnixSeconds::new(100).unwrap()) + .is_err() + ); + assert!( + session + .command_context(op, None, None, UnixSeconds::new(201).unwrap()) + .is_err() + ); + clock.0.store(150, Ordering::SeqCst); + assert_eq!( + context.revalidate().await.unwrap_err().code(), + radroots_execution::Code::Unauthorized + ); + clock.0.store(101, Ordering::SeqCst); + let other = client.attach(input.clone(), other_proof).await.unwrap(); + let other_context = other + .command_context(op, None, None, UnixSeconds::new(150).unwrap()) + .unwrap(); + other.close(); + assert_eq!( + other_context.revalidate().await.unwrap_err().code(), + radroots_execution::Code::CapabilityUnavailable + ); + assert!( + other + .command_context(op, None, None, UnixSeconds::new(150).unwrap()) + .is_err() + ); + context.revalidate().await.unwrap(); + workspace_copy + .revoke(input.clone(), &duplicate) + .await + .unwrap(); + assert_eq!( + context.revalidate().await.unwrap_err().code(), + radroots_execution::Code::GrantRevoked + ); + client.start(StartMode::LocalOnly).await.unwrap(); + client.close().await.unwrap(); + assert!( + session + .command_context(op, None, None, UnixSeconds::new(150).unwrap()) + .is_err() + ); + assert_eq!( + context.revalidate().await.unwrap_err().code(), + radroots_execution::Code::CapabilityUnavailable + ); + assert!( + client + .attach( + input.clone(), + AttachmentProof::from_protected_input(&[0; 32]).unwrap() + ) + .await + .is_err() + ); + workspace_copy.close().await.unwrap(); + let reopened = NativeWorkspace::open_existing(&root.join("outbox"), input, crypto(), clock) + .await + .unwrap(); + reopened.close().await.unwrap(); +} + +#[tokio::test] +async fn preview_cannot_authenticate_a_caller_supplied_workspace_descriptor() { + let client = Client::preview(); + let input = radroots_storage::workspace::AttachmentInput::new( + radroots_domain::WorkspaceId::from_bytes([1; 32]), + radroots_domain::AuthorityRef::new( + radroots_domain::ExecutorId::from_bytes([2; 32]), + radroots_domain::Generation::new(1).unwrap(), + ), + key(), + "local://workspace/untrusted", + key(), + radroots_domain::GrantId::from_bytes([3; 32]), + radroots_domain::CheckpointRef::new( + radroots_domain::CheckpointDigest::from_bytes([4; 32]), + Sequence::new(0).unwrap(), + radroots_domain::Coverage::Partial, + vec![], + ) + .unwrap(), + radroots_domain::RouteDigest::from_bytes([5; 32]), + ) + .unwrap(); + let proof = AttachmentProof::from_protected_input(&[0; 32]).unwrap(); + assert_eq!( + client.attach(input, proof).await.unwrap_err().code(), + radroots_execution::Code::MissingAuthority + ); + client.close().await.unwrap(); +} diff --git a/crates/storage/Cargo.toml b/crates/storage/Cargo.toml @@ -37,6 +37,7 @@ default = ["memory", "serde"] memory = [] serde = [ "dep:serde", + "radroots_domain/serde", "radroots_event/serde", "radroots_protocol/serde", "radroots_trade/serde", @@ -44,6 +45,7 @@ serde = [ ] [dependencies] +radroots_domain = { workspace = true, default-features = false } radroots_event = { workspace = true, default-features = false } radroots_event_codec = { workspace = true, default-features = false, features = [ "json", @@ -56,6 +58,7 @@ serde = { workspace = true, default-features = false, features = [ "derive", ], optional = true } sha2 = { workspace = true, default-features = false } +zeroize = { workspace = true, default-features = false } [dev-dependencies] futures-executor = { workspace = true } diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs @@ -19,6 +19,7 @@ pub mod outbox; pub mod private_artifact; pub mod projection; pub mod status; +pub mod workspace; pub use backup::StorageReliability as BackupSource; pub use error::Error; diff --git a/crates/storage/src/workspace.rs b/crates/storage/src/workspace.rs @@ -0,0 +1,301 @@ +//! Scoped workspace authentication primitives. These are storage operations, +//! not an application-owned command, stock or recovery engine. + +use core::fmt; +use radroots_domain::{ + ActorRef, AuthorityRef, CheckpointRef, GrantId, PublicKey, RouteDigest, Sequence, UnixSeconds, + WorkspaceId, +}; +use radroots_transport::{BoxFuture, host::HostBound}; +use zeroize::Zeroizing; + +/// A fixed workspace boundary error; no path, credential, SQL or caller prose. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum WorkspaceError { + /// Descriptor representation is invalid. + InvalidInput, + /// The selected protected provider or host is unavailable. + Unavailable, + /// The explicit private namespace cannot be safely opened. + NamespaceUnavailable, + /// Another writer retains this exact namespace. + WriterActive, + /// Namespace identity does not match the selected workspace. + WrongNamespace, + /// Protected state or creation evidence requires explicit recovery. + RecoveryRequired, + /// The presented protected credential does not authenticate its grant. + Unauthorized, + /// The current grant has expired. + GrantExpired, + /// The current grant has been revoked. + GrantRevoked, + /// The selected authority no longer matches. + StaleAuthority, + /// The required checkpoint does not match retained state. + StaleCheckpoint, + /// Admission is permanently closed. + Closed, + /// Storage reports a known failure before confirmed completion. + StorageFailure, + /// Transaction completion is uncertain and must be reconciled. + CommitUnknown, +} +impl WorkspaceError { + /// Returns the stable source-redacted diagnostic code. + pub const fn code(self) -> &'static str { + match self { + Self::InvalidInput => "invalid_input", + Self::Unavailable => "workspace_unavailable", + Self::NamespaceUnavailable => "namespace_unavailable", + Self::WriterActive => "writer_active", + Self::WrongNamespace => "wrong_workspace", + Self::RecoveryRequired => "recovery_required", + Self::Unauthorized => "unauthorized", + Self::GrantExpired => "grant_expired", + Self::GrantRevoked => "grant_revoked", + Self::StaleAuthority => "stale_authority", + Self::StaleCheckpoint => "stale_checkpoint", + Self::Closed => "closed", + Self::StorageFailure => "storage_failure", + Self::CommitUnknown => "commit_unknown", + } + } +} +impl fmt::Display for WorkspaceError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.code()) + } +} +impl core::error::Error for WorkspaceError {} + +/// An opaque protected bearer credential, independent of signer keys and grant +/// selectors. No automatic serialization, cloning or secret diagnostics exist. +pub struct AttachmentProof(Zeroizing<[u8; 32]>); +impl AttachmentProof { + /// Copies one qualified protected-channel value into a zeroizing owner. + /// This checks only width; the persisted grant must authenticate it. + pub fn from_protected_input(value: &[u8]) -> Result<Self, WorkspaceError> { + let bytes = <[u8; 32]>::try_from(value).map_err(|_| WorkspaceError::InvalidInput)?; + Ok(Self(Zeroizing::new(bytes))) + } + /// Exposes the fixed secret only for explicit backend authentication. + pub fn with_secret<T>(&self, use_secret: impl FnOnce(&[u8; 32]) -> T) -> T { + use_secret(&self.0) + } +} +impl fmt::Debug for AttachmentProof { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("AttachmentProof(<redacted>)") + } +} + +/// Explicit selected endpoint, participant, grant and checkpoint data. This is +/// never itself proof that the actor or endpoint is trusted. +#[derive(Clone, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct AttachmentInput { + workspace_id: WorkspaceId, + authority: AuthorityRef, + participant: PublicKey, + endpoint: Box<str>, + endpoint_identity: PublicKey, + grant_id: GrantId, + checkpoint: CheckpointRef, + route_digest: RouteDigest, +} +impl AttachmentInput { + /// Captures explicit selected input; it performs no authentication or I/O. + #[allow(clippy::too_many_arguments)] + pub fn new( + workspace_id: WorkspaceId, + authority: AuthorityRef, + participant: PublicKey, + endpoint: impl Into<String>, + endpoint_identity: PublicKey, + grant_id: GrantId, + checkpoint: CheckpointRef, + route_digest: RouteDigest, + ) -> Result<Self, WorkspaceError> { + let endpoint = endpoint.into(); + if endpoint.is_empty() || endpoint.len() > 2048 || endpoint.chars().any(char::is_control) { + return Err(WorkspaceError::InvalidInput); + } + Ok(Self { + workspace_id, + authority, + participant, + endpoint: endpoint.into_boxed_str(), + endpoint_identity, + grant_id, + checkpoint, + route_digest, + }) + } + /// Returns the selected workspace, independent of a cache generation. + pub const fn workspace_id(&self) -> WorkspaceId { + self.workspace_id + } + /// Returns the selected executor/epoch. + pub const fn authority(&self) -> AuthorityRef { + self.authority + } + /// Returns the claimed participant. + pub const fn participant(&self) -> PublicKey { + self.participant + } + /// Borrows the explicit selected endpoint. + pub fn endpoint(&self) -> &str { + &self.endpoint + } + /// Returns its pinned application identity. + pub const fn endpoint_identity(&self) -> PublicKey { + self.endpoint_identity + } + /// Returns the requested grant selector, never its credential. + pub const fn grant_id(&self) -> GrantId { + self.grant_id + } + /// Borrows the required checkpoint. + pub const fn checkpoint(&self) -> &CheckpointRef { + &self.checkpoint + } + /// Returns the exact selected route commitment. + pub const fn route_digest(&self) -> RouteDigest { + self.route_digest + } +} +impl fmt::Debug for AttachmentInput { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("AttachmentInput(<untrusted descriptor>)") + } +} + +#[cfg(feature = "serde")] +impl<'de> serde::Deserialize<'de> for AttachmentInput { + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + #[derive(serde::Deserialize)] + #[serde(deny_unknown_fields)] + struct Raw { + workspace_id: WorkspaceId, + authority: AuthorityRef, + participant: PublicKey, + endpoint: String, + endpoint_identity: PublicKey, + grant_id: GrantId, + checkpoint: CheckpointRef, + route_digest: RouteDigest, + } + let raw = Raw::deserialize(deserializer)?; + Self::new( + raw.workspace_id, + raw.authority, + raw.participant, + raw.endpoint, + raw.endpoint_identity, + raw.grant_id, + raw.checkpoint, + raw.route_digest, + ) + .map_err(serde::de::Error::custom) + } +} + +/// A native/remote adapter's authenticated grant observation. It does not +/// replace transaction-time checks and contains no bearer credential. +#[derive(Clone, Eq, PartialEq)] +pub struct WorkspaceBinding { + input: AttachmentInput, + actor: ActorRef, + principal_id: String, + grant_revision: Sequence, + expires_at: UnixSeconds, + observed_at: UnixSeconds, +} +impl WorkspaceBinding { + /// Checks the internal binding of a trusted storage adapter's observation. + /// Host implementations require actual authentication qualification; this + /// constructor does not turn public metadata into an authenticated context. + pub fn from_authenticated_host( + input: AttachmentInput, + actor: ActorRef, + principal_id: impl Into<String>, + grant_revision: Sequence, + expires_at: UnixSeconds, + observed_at: UnixSeconds, + ) -> Result<Self, WorkspaceError> { + let principal_id = principal_id.into(); + if actor.participant() != input.participant() + || actor.grant_id() != Some(input.grant_id()) + || principal_id.is_empty() + || principal_id.len() > 128 + || principal_id.chars().any(char::is_control) + || grant_revision.get() == 0 + || expires_at.get() == 0 + || observed_at.get() == 0 + || expires_at <= observed_at + { + return Err(WorkspaceError::InvalidInput); + } + Ok(Self { + input, + actor, + principal_id, + grant_revision, + expires_at, + observed_at, + }) + } + /// Borrows the exact authenticated selection. + pub const fn input(&self) -> &AttachmentInput { + &self.input + } + /// Returns actor data from the persisted authenticated grant. + pub const fn actor(&self) -> ActorRef { + self.actor + } + /// Borrows the authenticated local device/principal audit identity. + pub fn principal_id(&self) -> &str { + &self.principal_id + } + /// Returns the observed revocation-sensitive grant revision. + pub const fn grant_revision(&self) -> Sequence { + self.grant_revision + } + /// Returns the observed grant expiry, without reading an ambient clock. + pub const fn expires_at(&self) -> UnixSeconds { + self.expires_at + } + /// Returns the actual adapter clock observation used to validate expiry. + pub const fn observed_at(&self) -> UnixSeconds { + self.observed_at + } +} +impl fmt::Debug for WorkspaceBinding { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("WorkspaceBinding(<redacted>)") + } +} + +/// Backend-neutral current workspace authentication. Applications consume the +/// concrete shared implementation; they do not supply command/stock semantics. +pub trait WorkspaceStore: HostBound { + /// Authenticates protected input against current persisted scope. The + /// returned observation is rechecked at each authoritative transaction. + /// The adapter owns its request credential through its safe completion; + /// observers must not retain an attachment's credential root across await. + fn authenticate( + &self, + input: AttachmentInput, + proof: AttachmentProof, + ) -> BoxFuture<'_, Result<WorkspaceBinding, WorkspaceError>>; + /// Stops storage admission and observes actual backend closure. + fn close_workspace(&self) -> BoxFuture<'_, Result<(), WorkspaceError>>; +} + +/// The backend's explicit time source. Failure cannot become a valid timestamp. +pub trait WorkspaceClock: HostBound { + /// Returns a checked, positive current wall time or an unavailable result. + fn now(&self) -> Result<UnixSeconds, WorkspaceError>; +} diff --git a/crates/storage/tests/workspace.rs b/crates/storage/tests/workspace.rs @@ -0,0 +1,188 @@ +use radroots_domain::{ + ActorRef, ActorRole, AuthorityRef, CheckpointDigest, CheckpointRef, Coverage, ExecutorId, + Generation, GrantId, PublicKey, RouteDigest, Sequence, UnixSeconds, WorkspaceId, +}; +use radroots_storage::workspace::{ + AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceError, +}; +fn key() -> PublicKey { + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() +} +fn input() -> AttachmentInput { + AttachmentInput::new( + WorkspaceId::from_bytes([1; 32]), + AuthorityRef::new(ExecutorId::from_bytes([2; 32]), Generation::new(1).unwrap()), + key(), + "local://workspace/selector", + key(), + GrantId::from_bytes([3; 32]), + CheckpointRef::new( + CheckpointDigest::from_bytes([4; 32]), + Sequence::new(0).unwrap(), + Coverage::Partial, + vec![], + ) + .unwrap(), + RouteDigest::from_bytes([5; 32]), + ) + .unwrap() +} +fn actor() -> ActorRef { + ActorRef::new(key(), ActorRole::Buyer, None, Some(input().grant_id())) +} + +#[test] +fn proof_has_exact_width_explicit_exposure_and_redacted_diagnostics() { + for bytes in [&[][..], &[7; 31][..], &[7; 33][..]] { + assert_eq!( + AttachmentProof::from_protected_input(bytes).unwrap_err(), + WorkspaceError::InvalidInput + ); + } + let proof = AttachmentProof::from_protected_input(&[7; 32]).unwrap(); + proof.with_secret(|bytes| assert_eq!(bytes, &[7; 32])); + assert_eq!(format!("{proof:?}"), "AttachmentProof(<redacted>)"); +} +#[test] +fn selections_are_bounded_untrusted_data_with_complete_getters() { + let input = input(); + assert_eq!(input.workspace_id(), WorkspaceId::from_bytes([1; 32])); + assert_eq!( + input.authority().executor_id(), + ExecutorId::from_bytes([2; 32]) + ); + assert_eq!(input.participant(), key()); + assert_eq!(input.endpoint_identity(), key()); + assert_eq!(input.endpoint(), "local://workspace/selector"); + assert_eq!(input.grant_id(), GrantId::from_bytes([3; 32])); + assert_eq!(input.checkpoint().sequence().get(), 0); + assert_eq!(input.route_digest(), RouteDigest::from_bytes([5; 32])); + for endpoint in [String::new(), "x".repeat(2049), "local://bad\n".into()] { + assert_eq!( + AttachmentInput::new( + input.workspace_id(), + input.authority(), + input.participant(), + endpoint, + input.endpoint_identity(), + input.grant_id(), + input.checkpoint().clone(), + input.route_digest() + ) + .unwrap_err(), + WorkspaceError::InvalidInput + ); + } + assert_eq!( + format!("{input:?}"), + "AttachmentInput(<untrusted descriptor>)" + ); +} +#[test] +fn host_observations_validate_internal_binding_without_authenticating_metadata() { + let binding = |actor, principal: &str, revision, expiry, observed| { + WorkspaceBinding::from_authenticated_host( + input(), + actor, + principal, + Sequence::new(revision).unwrap(), + UnixSeconds::new(expiry).unwrap(), + UnixSeconds::new(observed).unwrap(), + ) + }; + let observed = binding(actor(), "device", 1, 200, 100).unwrap(); + assert_eq!(observed.input(), &input()); + assert_eq!(observed.actor(), actor()); + assert_eq!(observed.principal_id(), "device"); + assert_eq!(observed.grant_revision().get(), 1); + assert_eq!(observed.expires_at().get(), 200); + assert_eq!(observed.observed_at().get(), 100); + assert_eq!(format!("{observed:?}"), "WorkspaceBinding(<redacted>)"); + for principal in [String::new(), "x".repeat(129), "device\n".into()] { + assert_eq!( + binding(actor(), principal.as_str(), 1, 200, 100).unwrap_err(), + WorkspaceError::InvalidInput + ); + } + for (revision, expiry, observed) in [ + (0, 200, 100), + (1, 0, 100), + (1, 100, 0), + (1, 100, 100), + (1, 99, 100), + ] { + assert_eq!( + binding(actor(), "device", revision, expiry, observed).unwrap_err(), + WorkspaceError::InvalidInput + ); + } + let other_key = + PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5") + .unwrap(); + for invalid in [ + ActorRef::new(other_key, ActorRole::Buyer, None, Some(input().grant_id())), + ActorRef::new(key(), ActorRole::Buyer, None, None), + ActorRef::new( + key(), + ActorRole::Buyer, + None, + Some(GrantId::from_bytes([9; 32])), + ), + ] { + assert_eq!( + binding(invalid, "device", 1, 200, 100).unwrap_err(), + WorkspaceError::InvalidInput + ); + } +} +#[cfg(feature = "serde")] +#[test] +fn selection_json_rejects_missing_duplicate_unknown_and_invalid_data() { + let input = input(); + let encoded = serde_json::to_string(&input).unwrap(); + assert_eq!( + serde_json::from_str::<AttachmentInput>(&encoded).unwrap(), + input + ); + let value = serde_json::to_value(&input).unwrap(); + for field in value.as_object().unwrap().keys() { + let mut missing = value.clone(); + missing.as_object_mut().unwrap().remove(field); + assert!(serde_json::from_value::<AttachmentInput>(missing).is_err()); + let duplicate = format!("{{\"{field}\":{},{}", value[field], &encoded[1..]); + assert!(serde_json::from_str::<AttachmentInput>(&duplicate).is_err()); + } + let mut unknown = value.clone(); + unknown["unexpected"] = serde_json::json!(true); + assert!(serde_json::from_value::<AttachmentInput>(unknown).is_err()); + for invalid in ["", "bad\n"] { + let mut data = value.clone(); + data["endpoint"] = serde_json::json!(invalid); + assert!(serde_json::from_value::<AttachmentInput>(data).is_err()); + } +} +#[test] +fn workspace_failures_have_fixed_bounded_codes_and_no_sources() { + use WorkspaceError::*; + for error in [ + InvalidInput, + Unavailable, + NamespaceUnavailable, + WriterActive, + WrongNamespace, + RecoveryRequired, + Unauthorized, + GrantExpired, + GrantRevoked, + StaleAuthority, + StaleCheckpoint, + Closed, + StorageFailure, + CommitUnknown, + ] { + assert_eq!(error.to_string(), error.code()); + assert!(error.code().len() <= 32); + let source: &dyn core::error::Error = &error; + assert!(source.source().is_none()); + } +} diff --git a/crates/storage_sqlite/Cargo.toml b/crates/storage_sqlite/Cargo.toml @@ -31,6 +31,8 @@ name = "radroots_storage_sqlite" [dependencies] fs2 = { workspace = true } +getrandom = { workspace = true } +radroots_domain = { workspace = true, features = ["std", "serde"] } radroots_event = { workspace = true, default-features = false, features = [ "serde", "std", @@ -50,10 +52,16 @@ radroots_transport = { workspace = true, default-features = false, features = [ serde = { workspace = true, features = ["derive", "std"] } serde_json = { workspace = true, features = ["std"] } sha2 = { workspace = true, features = ["std"] } +rustix = { workspace = true } +subtle = { workspace = true } +tokio = { workspace = true, features = ["rt", "sync"] } +zeroize = { workspace = true, features = ["alloc"] } sqlx = { workspace = true, features = ["runtime-tokio", "sqlite-bundled"] } [dev-dependencies] +futures = { workspace = true } hex = { workspace = true } +radroots_secrets = { workspace = true, features = ["file", "memory"] } radroots_storage = { workspace = true, default-features = false, features = ["memory", "serde"] } tempfile = { workspace = true } tokio = { workspace = true, features = ["macros", "rt"] } diff --git a/crates/storage_sqlite/README.md b/crates/storage_sqlite/README.md @@ -188,3 +188,20 @@ incompatible source generation therefore leaves both original files intact. Each rechecks metadata and applies its pending suffix atomically in its own database; this does not claim a cross-database atomic commit. An interrupted compatible upgrade resumes from its committed version on the next open. + +On Unix, `workspace::NativeWorkspace` owns an explicit separate local buyer +outbox namespace. Initialization generates random workspace/executor/grant +identities and a protected 32-byte credential; it cannot restore an existing +order or create seller stock authority. Existing open requires the independently +retained selection and never enrolls a new grant. The grant and credential +verifier use the existing context-bound authenticated envelope and an explicitly +selected persistent secret provider. Plaintext credentials are not stored. + +One bounded native worker owns the SQLite connection and persistent namespace +lock. Dropped authentication observers cannot cancel its work or release writer +authority. Close permanently stops admission, drains admitted requests, checks +the WAL checkpoint and awaits connection closure before releasing the lock. +Cancelled close can be awaited again. Dropping the handle is not close evidence. +Revocation commits a protected grant revision and survives reopening. This +attachment boundary supplies no command journal, network pairing, firm stock, +transfer, restore or browser qualification. diff --git a/crates/storage_sqlite/src/lib.rs b/crates/storage_sqlite/src/lib.rs @@ -24,3 +24,5 @@ mod projection; pub use config::OpenOptions; pub use event::SqliteStorage; pub use open::{Error, OpenMode, Paths}; +#[cfg(unix)] +pub mod workspace; diff --git a/crates/storage_sqlite/src/workspace/crypto.rs b/crates/storage_sqlite/src/workspace/crypto.rs @@ -0,0 +1,135 @@ +use super::WorkspaceError; +use radroots_domain::{GrantId, WorkspaceId}; +use radroots_secrets::{ + EncryptedEnvelope, SecretRef, + context::{EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId}, + envelope::{ENVELOPE_MAX_BYTES, Nonce, SealMaterial, SealRequest}, + provider::{AccessPolicy, ResidencySupport, SecretProvider, SelectionPolicy}, + wrapping::SecretMaterial, +}; +use std::{fmt, sync::Arc}; + +pub(super) const PRIVATE_PAYLOAD_MAX_BYTES: usize = 16 * 1024; +pub(super) const PROTECTED_MAX_BYTES: usize = ENVELOPE_MAX_BYTES; + +/// Explicit host-owned encryption material. This is a data-encryption key, +/// independent of the participant signer and the scoped bearer credential. +/// The host chooses its qualified provider and access policy; no fallback or +/// credential installation occurs here. +pub struct WorkspaceCrypto { + provider: Arc<dyn SecretProvider>, + reference: SecretRef, + key: SecretMaterial, +} +impl WorkspaceCrypto { + /// Binds protected host input to one exact persistent provider/ref. Actual + /// provider access and context authentication still execute at seal/open. + pub fn new( + provider: Arc<dyn SecretProvider>, + reference: SecretRef, + key: SecretMaterial, + policy: AccessPolicy, + ) -> Result<Self, WorkspaceError> { + if key.len() != 32 || provider.capabilities().residency() == ResidencySupport::Volatile { + return Err(WorkspaceError::Unavailable); + } + SelectionPolicy::new(reference.backend(), policy) + .select(&[provider.as_ref()]) + .map_err(|_| WorkspaceError::Unavailable)?; + Ok(Self { + provider, + reference, + key, + }) + } + pub(super) async fn seal( + &self, + workspace: WorkspaceId, + grant: GrantId, + plaintext: &[u8], + ) -> Result<Vec<u8>, WorkspaceError> { + if plaintext.len() > PRIVATE_PAYLOAD_MAX_BYTES { + return Err(WorkspaceError::InvalidInput); + } + let plaintext = + SecretMaterial::from_slice(plaintext).map_err(|_| WorkspaceError::InvalidInput)?; + let key = self + .key + .expose_secret(SecretMaterial::from_slice) + .map_err(|_| WorkspaceError::Unavailable)?; + let mut nonce = [0; 24]; + getrandom::getrandom(&mut nonce).map_err(|_| WorkspaceError::Unavailable)?; + let envelope = EncryptedEnvelope::seal( + self.provider.as_ref(), + SealRequest::new( + SecretRef::new( + self.reference.id().clone(), + self.reference.backend(), + self.reference.key_version(), + ), + context(workspace, grant)?, + &plaintext, + SealMaterial::new(key, Nonce::new(nonce)), + ), + ) + .await + .map_err(|_| WorkspaceError::Unavailable)?; + envelope + .encode() + .map_err(|_| WorkspaceError::StorageFailure) + } + pub(super) async fn open( + &self, + workspace: WorkspaceId, + grant: GrantId, + protected: &[u8], + ) -> Result<SecretMaterial, WorkspaceError> { + if protected.len() > PROTECTED_MAX_BYTES { + return Err(WorkspaceError::RecoveryRequired); + } + // A wrong explicitly supplied key cannot silently fall back to a + // different provider-held key, including on a read-only observation. + self.provider + .wrap(radroots_secrets::wrapping::WrapRequest::new( + &self.reference, + &context(workspace, grant)?, + &self.key, + )) + .await + .map_err(|_| WorkspaceError::Unavailable)?; + let envelope = + EncryptedEnvelope::decode(protected).map_err(|_| WorkspaceError::RecoveryRequired)?; + if envelope.reference().id() != self.reference.id() + || envelope.reference().backend() != self.reference.backend() + || envelope.reference().key_version() != self.reference.key_version() + { + return Err(WorkspaceError::RecoveryRequired); + } + let plaintext = envelope + .open(self.provider.as_ref(), &context(workspace, grant)?) + .await + .map_err(|_| WorkspaceError::RecoveryRequired)?; + if plaintext.len() > PRIVATE_PAYLOAD_MAX_BYTES { + return Err(WorkspaceError::RecoveryRequired); + } + Ok(plaintext) + } +} +impl fmt::Debug for WorkspaceCrypto { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("WorkspaceCrypto(<redacted>)") + } +} + +fn context(workspace: WorkspaceId, grant: GrantId) -> Result<EnvelopeContext, WorkspaceError> { + // Both values are fixed-width lowercase hex; their 128-byte concatenation + // is unambiguous and binds the complete IDs without truncation. + Ok(EnvelopeContext::new( + EnvelopePurpose::parse("radroots.workspace.grant") + .map_err(|_| WorkspaceError::InvalidInput)?, + EnvelopeSubject::parse("workspace_grant", format!("{workspace}{grant}")) + .map_err(|_| WorkspaceError::InvalidInput)?, + PayloadSchemaId::parse("radroots.workspace.grant.v1") + .map_err(|_| WorkspaceError::InvalidInput)?, + )) +} diff --git a/crates/storage_sqlite/src/workspace/fs.rs b/crates/storage_sqlite/src/workspace/fs.rs @@ -0,0 +1,216 @@ +//! Owner-only files for the separate native execution namespace. + +use super::WorkspaceError; +use fs2::FileExt; +use rustix::fs::{Mode, OFlags, open, openat}; +use std::{ + fs::{File, Metadata}, + os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt}, + path::{Component, Path, PathBuf}, +}; + +const DATABASE: &str = "execution_v1.sqlite"; +const LOCK: &str = ".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, + directory: File, + lock: File, + database: File, +} +impl Namespace { + pub(super) fn acquire(root: &Path, create: bool) -> Result<Self, WorkspaceError> { + validate_absolute(root)?; + if create { + std::fs::DirBuilder::new() + .mode(0o700) + .create(root) + .map_err(|_| WorkspaceError::NamespaceUnavailable)?; + } + validate_ancestors(root)?; + let directory: File = open( + root, + OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC, + Mode::empty(), + ) + .map_err(|_| WorkspaceError::NamespaceUnavailable)? + .into(); + let metadata = directory + .metadata() + .map_err(|_| WorkspaceError::NamespaceUnavailable)?; + validate_directory(&metadata)?; + let flags = OFlags::RDWR + | OFlags::NOFOLLOW + | OFlags::CLOEXEC + | if create { + OFlags::CREATE | OFlags::EXCL + } else { + OFlags::empty() + }; + let lock: File = openat(&directory, LOCK, flags, Mode::RUSR | Mode::WUSR) + .map_err(|_| WorkspaceError::NamespaceUnavailable)? + .into(); + validate_file(&lock)?; + if lock + .metadata() + .map_err(|_| WorkspaceError::NamespaceUnavailable)? + .len() + != 0 + { + return Err(WorkspaceError::RecoveryRequired); + } + FileExt::try_lock_exclusive(&lock).map_err(|error| { + if error.kind() == std::io::ErrorKind::WouldBlock { + WorkspaceError::WriterActive + } else { + WorkspaceError::NamespaceUnavailable + } + })?; + let database: File = openat(&directory, DATABASE, flags, Mode::RUSR | Mode::WUSR) + .map_err(|_| WorkspaceError::NamespaceUnavailable)? + .into(); + validate_file(&database)?; + if !create + && database + .metadata() + .map_err(|_| WorkspaceError::NamespaceUnavailable)? + .len() + == 0 + { + return Err(WorkspaceError::RecoveryRequired); + } + if create { + database + .sync_all() + .map_err(|_| WorkspaceError::NamespaceUnavailable)?; + lock.sync_all() + .map_err(|_| WorkspaceError::NamespaceUnavailable)?; + directory + .sync_all() + .map_err(|_| WorkspaceError::NamespaceUnavailable)?; + } + let namespace = Self { + root: root.to_path_buf(), + directory, + lock, + database, + }; + namespace.validate()?; + Ok(namespace) + } + pub(super) fn database_path(&self) -> PathBuf { + self.root.join(DATABASE) + } + pub(super) fn validate(&self) -> Result<(), WorkspaceError> { + validate_ancestors(&self.root)?; + let entries = + std::fs::read_dir(&self.root).map_err(|_| WorkspaceError::NamespaceUnavailable)?; + 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" + ) + ) + { + return Err(WorkspaceError::RecoveryRequired); + } + } + let root = std::fs::symlink_metadata(&self.root) + .map_err(|_| WorkspaceError::NamespaceUnavailable)?; + let retained = self + .directory + .metadata() + .map_err(|_| WorkspaceError::NamespaceUnavailable)?; + validate_directory(&root)?; + 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)] { + validate_file(file)?; + let current = std::fs::symlink_metadata(self.root.join(name)) + .map_err(|_| WorkspaceError::NamespaceUnavailable)?; + let retained = file + .metadata() + .map_err(|_| WorkspaceError::NamespaceUnavailable)?; + if current.file_type().is_symlink() || !same(&current, &retained) { + return Err(WorkspaceError::NamespaceUnavailable); + } + } + for suffix in ["-wal", "-shm", "-journal"] { + match std::fs::symlink_metadata(self.root.join(format!("{DATABASE}{suffix}"))) { + Ok(metadata) => validate_metadata(&metadata)?, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return Err(WorkspaceError::NamespaceUnavailable), + } + } + Ok(()) + } +} +fn validate_absolute(root: &Path) -> Result<(), WorkspaceError> { + if !root.is_absolute() + || root + .components() + .any(|part| matches!(part, Component::CurDir | Component::ParentDir)) + { + return Err(WorkspaceError::NamespaceUnavailable); + } + Ok(()) +} +fn validate_ancestors(root: &Path) -> Result<(), WorkspaceError> { + let mut current = PathBuf::new(); + for part in root.components() { + current.push(part.as_os_str()); + let metadata = std::fs::symlink_metadata(&current) + .map_err(|_| WorkspaceError::NamespaceUnavailable)?; + if !metadata.is_dir() || metadata.file_type().is_symlink() { + return Err(WorkspaceError::NamespaceUnavailable); + } + // A root-owned sticky ancestor is an ordinary system temporary root; + // all other mutable ancestors could allow another user to replace it. + let mode = metadata.permissions().mode(); + let sticky_system = metadata.uid() == 0 && mode & 0o1000 != 0; + if mode & 0o022 != 0 && !sticky_system { + return Err(WorkspaceError::NamespaceUnavailable); + } + } + Ok(()) +} +fn same(a: &Metadata, b: &Metadata) -> bool { + a.dev() == b.dev() && a.ino() == b.ino() && a.uid() == b.uid() +} +fn validate_file(file: &File) -> Result<(), WorkspaceError> { + validate_metadata( + &file + .metadata() + .map_err(|_| WorkspaceError::NamespaceUnavailable)?, + ) +} +fn validate_directory(metadata: &Metadata) -> Result<(), WorkspaceError> { + if !metadata.is_dir() + || metadata.uid() != rustix::process::geteuid().as_raw() + || metadata.permissions().mode() & 0o077 != 0 + { + return Err(WorkspaceError::NamespaceUnavailable); + } + Ok(()) +} +fn validate_metadata(metadata: &Metadata) -> Result<(), WorkspaceError> { + if !metadata.is_file() + || metadata.file_type().is_symlink() + || metadata.nlink() != 1 + || metadata.uid() != rustix::process::geteuid().as_raw() + || metadata.permissions().mode() & 0o7777 != 0o600 + { + return Err(WorkspaceError::NamespaceUnavailable); + } + Ok(()) +} diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs @@ -0,0 +1,217 @@ +//! Explicit protected local buyer-outbox attachment. +//! +//! This host cannot acquire seller stock authority, 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. + +mod crypto; +mod fs; +mod record; +mod worker; + +#[cfg(test)] +mod tests; + +pub use crypto::WorkspaceCrypto; +pub use radroots_storage::workspace::{ + AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceError, +}; + +use radroots_domain::{ + ActorRef, ActorRole, AuthorityRef, CheckpointDigest, CheckpointRef, Coverage, ExecutorId, + Generation, GrantId, PublicKey, RouteDigest, Sequence, UnixSeconds, WorkspaceId, +}; +use radroots_storage::workspace::WorkspaceStore; +use radroots_transport::BoxFuture; +use sha2::{Digest, Sha256}; +use std::{path::Path, sync::Arc}; + +/// Explicit local enrollment inputs, supplied by a trusted host interaction. +/// Creation is limited to an unrelated new buyer outbox, never seller stock. +pub struct LocalOutboxConfig { + participant: PublicKey, + endpoint_identity: PublicKey, + principal: String, + expires_at: UnixSeconds, +} +impl LocalOutboxConfig { + /// Captures the participant, local application identity, device audit label + /// and positive expiry. This performs no authentication or filesystem work. + pub fn new( + participant: PublicKey, + endpoint_identity: PublicKey, + principal: impl Into<String>, + expires_at: UnixSeconds, + ) -> Result<Self, WorkspaceError> { + let principal = principal.into(); + if principal.is_empty() + || principal.len() > 128 + || principal.chars().any(char::is_control) + || expires_at.get() == 0 + { + return Err(WorkspaceError::InvalidInput); + } + Ok(Self { + participant, + endpoint_identity, + principal, + expires_at, + }) + } +} +impl std::fmt::Debug for LocalOutboxConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("LocalOutboxConfig(<redacted>)") + } +} + +/// One native local-outbox connection, with an owned bounded request worker. +/// Clones refer to the same admission, writer authority and close completion. +#[derive(Clone)] +pub struct NativeWorkspace { + worker: Arc<worker::Handle>, +} +impl NativeWorkspace { + /// Creates a new owner-only namespace and persisted protected grant. All + /// workspace/executor/grant IDs and the returned credential use OS entropy. + /// The caller must retain both returned values through protected handling. + pub async fn initialize_local_outbox( + path: &Path, + config: LocalOutboxConfig, + crypto: WorkspaceCrypto, + clock: Arc<dyn WorkspaceClock>, + ) -> Result<(Self, AttachmentInput, AttachmentProof), WorkspaceError> { + let now = clock.now()?; + if now.get() == 0 { + return Err(WorkspaceError::Unavailable); + } + if config.expires_at <= now { + return Err(WorkspaceError::GrantExpired); + } + let workspace = WorkspaceId::from_bytes(random()?); + let executor = ExecutorId::from_bytes(random()?); + let grant = GrantId::from_bytes(random()?); + let authority = AuthorityRef::new( + executor, + Generation::new(1).map_err(|_| WorkspaceError::InvalidInput)?, + ); + let endpoint = format!("local://workspace/{workspace}"); + let mut route = Sha256::new(); + route.update(b"radroots.local_buyer_outbox.route.v1\0"); + route.update(workspace.as_bytes()); + route.update(executor.as_bytes()); + route.update(config.endpoint_identity.as_bytes()); + route.update(endpoint.as_bytes()); + let route = RouteDigest::from_bytes(route.finalize().into()); + let mut checkpoint = Sha256::new(); + checkpoint.update(b"radroots.local_buyer_outbox.genesis.v1\0"); + checkpoint.update(workspace.as_bytes()); + checkpoint.update(executor.as_bytes()); + checkpoint.update(grant.as_bytes()); + // Genesis certifies only a fresh unrelated outbox. Partial coverage is + // deliberate: no old order, private history or stock 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, + config.participant, + endpoint, + config.endpoint_identity, + grant, + checkpoint, + route, + )?; + let secret = zeroize::Zeroizing::new(random()?); + let proof = AttachmentProof::from_protected_input(secret.as_ref())?; + let actor = ActorRef::new(config.participant, ActorRole::Buyer, None, Some(grant)); + let record = record::GrantRecord::new( + input.clone(), + actor, + config.principal, + config.expires_at, + &proof, + )?; + let worker = worker::Handle::launch( + path.to_path_buf(), + input.clone(), + Some(record), + crypto, + clock, + ) + .await?; + Ok(( + Self { + worker: Arc::new(worker), + }, + input, + proof, + )) + } + /// Opens only an existing exact namespace. The independently retained + /// selection supplies the expected envelope context; no grant is created. + pub async fn open_existing( + path: &Path, + expected: AttachmentInput, + crypto: WorkspaceCrypto, + clock: Arc<dyn WorkspaceClock>, + ) -> Result<Self, WorkspaceError> { + let worker = + worker::Handle::launch(path.to_path_buf(), expected, None, crypto, clock).await?; + Ok(Self { + worker: Arc::new(worker), + }) + } + /// Authenticates and revokes this exact local grant. A cancelled observer + /// must query its retained identity; it cannot presume the write aborted. + pub async fn revoke( + &self, + input: AttachmentInput, + proof: &AttachmentProof, + ) -> Result<(), WorkspaceError> { + self.worker.revoke(input, proof).await + } + /// Copies an explicitly borrowed protected credential into one owned + /// bounded authentication request. The caller retains its original input. + pub async fn authenticate( + &self, + input: AttachmentInput, + proof: &AttachmentProof, + ) -> Result<WorkspaceBinding, WorkspaceError> { + let proof = proof.with_secret(|secret| AttachmentProof::from_protected_input(secret))?; + self.worker.authenticate(input, proof).await + } + /// Permanently closes admission, drains admitted requests and explicitly + /// closes SQLite before releasing the persistent writer authority. + pub async fn close(&self) -> Result<(), WorkspaceError> { + self.worker.close().await + } +} +impl std::fmt::Debug for NativeWorkspace { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("NativeWorkspace(<redacted>)") + } +} +impl WorkspaceStore for NativeWorkspace { + fn authenticate( + &self, + input: AttachmentInput, + proof: AttachmentProof, + ) -> BoxFuture<'_, Result<WorkspaceBinding, WorkspaceError>> { + Box::pin(self.worker.authenticate(input, proof)) + } + fn close_workspace(&self) -> BoxFuture<'_, Result<(), WorkspaceError>> { + Box::pin(self.close()) + } +} +fn random() -> Result<[u8; 32], WorkspaceError> { + let mut value = [0; 32]; + getrandom::getrandom(&mut value).map_err(|_| WorkspaceError::Unavailable)?; + Ok(value) +} diff --git a/crates/storage_sqlite/src/workspace/record.rs b/crates/storage_sqlite/src/workspace/record.rs @@ -0,0 +1,144 @@ +use super::{AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceError}; +use radroots_domain::{ActorRef, ActorRole, Sequence, UnixSeconds}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use subtle::ConstantTimeEq; +use zeroize::{Zeroize, Zeroizing}; + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct GrantRecord { + version: u8, + scope: Scope, + input: AttachmentInput, + actor: ActorRef, + principal: String, + revision: Sequence, + expires_at: UnixSeconds, + revoked: bool, + verifier: [u8; 32], +} +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +enum Scope { + NewBuyerOutbox, +} +impl Drop for GrantRecord { + fn drop(&mut self) { + self.verifier.zeroize(); + } +} +impl GrantRecord { + pub(super) fn new( + input: AttachmentInput, + actor: ActorRef, + principal: String, + expires_at: UnixSeconds, + proof: &AttachmentProof, + ) -> Result<Self, WorkspaceError> { + let verifier = verifier(&input, proof); + let record = Self { + version: 1, + scope: Scope::NewBuyerOutbox, + input, + actor, + principal, + revision: Sequence::new(1).map_err(|_| WorkspaceError::InvalidInput)?, + expires_at, + revoked: false, + verifier, + }; + record.validate()?; + Ok(record) + } + pub(super) fn decode(bytes: &[u8]) -> Result<Self, WorkspaceError> { + let record: Self = + serde_json::from_slice(bytes).map_err(|_| WorkspaceError::RecoveryRequired)?; + record + .validate() + .map_err(|_| WorkspaceError::RecoveryRequired)?; + Ok(record) + } + pub(super) fn encode(&self) -> Result<Zeroizing<Vec<u8>>, WorkspaceError> { + serde_json::to_vec(self) + .map(Zeroizing::new) + .map_err(|_| WorkspaceError::StorageFailure) + } + fn validate(&self) -> Result<(), WorkspaceError> { + if self.version != 1 + || self.actor.role() != ActorRole::Buyer + || self.actor.organization().is_some() + || self.actor.participant() != self.input.participant() + || self.actor.grant_id() != Some(self.input.grant_id()) + || self.principal.is_empty() + || self.principal.len() > 128 + || self.principal.chars().any(char::is_control) + || self.revision.get() == 0 + || self.expires_at.get() == 0 + { + return Err(WorkspaceError::InvalidInput); + } + Ok(()) + } + pub(super) fn authenticate( + &self, + input: &AttachmentInput, + proof: &AttachmentProof, + now: UnixSeconds, + ) -> Result<WorkspaceBinding, WorkspaceError> { + // Check the complete secret commitment before projecting detailed state. + let observed = Zeroizing::new(verifier(&self.input, proof)); + if !bool::from(observed.as_ref().ct_eq(&self.verifier)) { + return Err(WorkspaceError::Unauthorized); + } + if self.input.workspace_id() != input.workspace_id() { + return Err(WorkspaceError::WrongNamespace); + } + if self.input.authority() != input.authority() { + return Err(WorkspaceError::StaleAuthority); + } + if self.input.checkpoint() != input.checkpoint() { + return Err(WorkspaceError::StaleCheckpoint); + } + if &self.input != input { + return Err(WorkspaceError::Unauthorized); + } + if self.revoked { + return Err(WorkspaceError::GrantRevoked); + } + if now.get() == 0 { + return Err(WorkspaceError::Unavailable); + } + if self.expires_at <= now { + return Err(WorkspaceError::GrantExpired); + } + self.validate()?; + WorkspaceBinding::from_authenticated_host( + self.input.clone(), + self.actor, + self.principal.clone(), + self.revision, + self.expires_at, + now, + ) + } + pub(super) fn revoke(&mut self) -> Result<(), WorkspaceError> { + self.revoked = true; + self.revision = Sequence::new( + self.revision + .get() + .checked_add(1) + .ok_or(WorkspaceError::RecoveryRequired)?, + ) + .map_err(|_| WorkspaceError::RecoveryRequired)?; + Ok(()) + } +} +fn verifier(input: &AttachmentInput, proof: &AttachmentProof) -> [u8; 32] { + let mut digest = Sha256::new(); + digest.update(b"radroots.local_buyer_outbox.credential.v1\0"); + digest.update(input.workspace_id().as_bytes()); + digest.update(input.grant_id().as_bytes()); + proof.with_secret(|secret| digest.update(secret)); + digest.finalize().into() +} diff --git a/crates/storage_sqlite/src/workspace/tests/mod.rs b/crates/storage_sqlite/src/workspace/tests/mod.rs @@ -0,0 +1,615 @@ +use super::*; +use radroots_domain::{ActorRef, SourceId}; +use radroots_secrets::{ + EncryptedEnvelope, SecretId, SecretRef, + context::{EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId}, + envelope::{Nonce, SealMaterial, SealRequest}, + file::{FileOpenMode, FileProvider}, + id::{BackendKind, KeyVersion}, + memory::MemoryProvider, + provider::{AccessPolicy, SecretProvider}, + wrapping::SecretMaterial, +}; +use std::{ + fs as host_fs, + os::unix::fs::{DirBuilderExt, PermissionsExt, symlink}, +}; + +fn participant() -> PublicKey { + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() +} +fn selection() -> AttachmentInput { + AttachmentInput::new( + WorkspaceId::from_bytes([1; 32]), + AuthorityRef::new(ExecutorId::from_bytes([2; 32]), Generation::new(1).unwrap()), + participant(), + "local://synthetic", + participant(), + GrantId::from_bytes([3; 32]), + CheckpointRef::new( + CheckpointDigest::from_bytes([4; 32]), + Sequence::new(0).unwrap(), + Coverage::Partial, + vec![SourceId::from_bytes([5; 32])], + ) + .unwrap(), + RouteDigest::from_bytes([6; 32]), + ) + .unwrap() +} +fn reference(id: &str, backend: BackendKind, version: u32) -> SecretRef { + SecretRef::new( + SecretId::parse(id).unwrap(), + backend, + KeyVersion::new(version).unwrap(), + ) +} +struct CryptoFixture { + _temp: tempfile::TempDir, + provider: Arc<FileProvider>, +} +impl CryptoFixture { + fn new() -> Self { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let provider = Arc::new( + FileProvider::open( + root.join("vault"), + FileOpenMode::CreateNew, + SecretMaterial::from_slice(&[0xA5; 32]).unwrap(), + ) + .unwrap(), + ); + let fixture = Self { + _temp: temp, + provider, + }; + fixture.provision(&reference("grant-key", BackendKind::File, 1), 0x11); + fixture + } + fn provision(&self, reference: &SecretRef, nonce: u8) { + self.provider + .provision( + reference, + &SecretMaterial::from_slice(&[0x41; 32]).unwrap(), + Nonce::new([nonce; 24]), + ) + .unwrap(); + } + fn crypto(&self) -> WorkspaceCrypto { + WorkspaceCrypto::new( + self.provider.clone(), + reference("grant-key", BackendKind::File, 1), + SecretMaterial::from_slice(&[0x41; 32]).unwrap(), + AccessPolicy::standard(), + ) + .unwrap() + } +} +async fn envelope( + provider: &dyn SecretProvider, + reference: SecretRef, + plaintext: &[u8], + nonce: u8, +) -> Vec<u8> { + let input = selection(); + let context = EnvelopeContext::new( + EnvelopePurpose::parse("radroots.workspace.grant").unwrap(), + EnvelopeSubject::parse( + "workspace_grant", + format!("{}{}", input.workspace_id(), input.grant_id()), + ) + .unwrap(), + PayloadSchemaId::parse("radroots.workspace.grant.v1").unwrap(), + ); + let plaintext = SecretMaterial::from_slice(plaintext).unwrap(); + EncryptedEnvelope::seal( + provider, + SealRequest::new( + reference, + context, + &plaintext, + SealMaterial::new( + SecretMaterial::from_slice(&[0x41; 32]).unwrap(), + Nonce::new([nonce; 24]), + ), + ), + ) + .await + .unwrap() + .encode() + .unwrap() +} + +#[tokio::test] +async fn protected_payload_enforces_native_limits_reference_and_context_after_real_crypto() { + let fixture = CryptoFixture::new(); + let input = selection(); + assert!(matches!( + WorkspaceCrypto::new( + fixture.provider.clone(), + reference("grant-key", BackendKind::File, 1), + SecretMaterial::from_slice(&[1; 31]).unwrap(), + AccessPolicy::standard() + ), + Err(WorkspaceError::Unavailable) + )); + assert!(matches!( + WorkspaceCrypto::new( + Arc::new(MemoryProvider::new()), + reference("grant-key", BackendKind::Memory, 1), + SecretMaterial::from_slice(&[1; 32]).unwrap(), + AccessPolicy::standard() + ), + Err(WorkspaceError::Unavailable) + )); + let crypto = fixture.crypto(); + let boundary = vec![b'x'; crypto::PRIVATE_PAYLOAD_MAX_BYTES]; + let sealed = crypto + .seal(input.workspace_id(), input.grant_id(), &boundary) + .await + .unwrap(); + crypto + .open(input.workspace_id(), input.grant_id(), &sealed) + .await + .unwrap() + .expose_secret(|value| assert_eq!(value, boundary)); + assert!(matches!( + crypto + .open(WorkspaceId::from_bytes([9; 32]), input.grant_id(), &sealed) + .await, + Err(WorkspaceError::RecoveryRequired) + )); + assert!(matches!( + crypto + .open(input.workspace_id(), GrantId::from_bytes([9; 32]), &sealed) + .await, + Err(WorkspaceError::RecoveryRequired) + )); + let oversized = vec![b'x'; crypto::PRIVATE_PAYLOAD_MAX_BYTES + 1]; + assert!(matches!( + crypto + .seal(input.workspace_id(), input.grant_id(), &oversized) + .await, + Err(WorkspaceError::InvalidInput) + )); + assert!(matches!( + crypto + .open( + input.workspace_id(), + input.grant_id(), + &vec![0; crypto::PROTECTED_MAX_BYTES + 1] + ) + .await, + Err(WorkspaceError::RecoveryRequired) + )); + let sealed = envelope( + fixture.provider.as_ref(), + reference("grant-key", BackendKind::File, 1), + &oversized, + 0x61, + ) + .await; + assert!(matches!( + crypto + .open(input.workspace_id(), input.grant_id(), &sealed) + .await, + Err(WorkspaceError::RecoveryRequired) + )); + for (id, version, nonce) in [("other-key", 1, 0x12), ("grant-key", 2, 0x13)] { + fixture.provision(&reference(id, BackendKind::File, version), nonce); + let sealed = envelope( + fixture.provider.as_ref(), + reference(id, BackendKind::File, version), + b"private", + nonce + 0x60, + ) + .await; + assert!(matches!( + crypto + .open(input.workspace_id(), input.grant_id(), &sealed) + .await, + Err(WorkspaceError::RecoveryRequired) + )); + } + let memory = MemoryProvider::new(); + memory + .provision( + &reference("grant-key", BackendKind::Memory, 1), + SecretMaterial::from_slice(&[0x41; 32]).unwrap(), + ) + .unwrap(); + let sealed = envelope( + &memory, + reference("grant-key", BackendKind::Memory, 1), + b"private", + 0x64, + ) + .await; + assert!(matches!( + crypto + .open(input.workspace_id(), input.grant_id(), &sealed) + .await, + Err(WorkspaceError::RecoveryRequired) + )); +} + +#[test] +fn persisted_grant_refuses_inconsistent_scope_actor_and_revisions() { + use serde_json::{Value, json}; + let input = selection(); + let proof = AttachmentProof::from_protected_input(&[7; 32]).unwrap(); + let record = record::GrantRecord::new( + input.clone(), + ActorRef::new( + participant(), + ActorRole::Buyer, + None, + Some(input.grant_id()), + ), + "synthetic-device".into(), + UnixSeconds::new(200).unwrap(), + &proof, + ) + .unwrap(); + let encoded = record.encode().unwrap(); + let original: Value = serde_json::from_slice(&encoded).unwrap(); + let second_key = "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"; + for (pointer, value) in [ + ("/version", json!(2)), + ("/scope", json!("seller_stock")), + ("/actor/role", json!("seller")), + ("/actor/organization", json!(participant().to_hex())), + ("/actor/participant", json!(second_key)), + ("/actor/grant_id", Value::Null), + ("/principal", json!("")), + ("/principal", json!("x".repeat(129))), + ("/principal", json!("bad\nlabel")), + ("/revision", json!("0")), + ("/expires_at", json!("0")), + ] { + let mut changed = original.clone(); + *changed.pointer_mut(pointer).unwrap() = value; + assert!( + matches!( + record::GrantRecord::decode(&serde_json::to_vec(&changed).unwrap()), + Err(WorkspaceError::RecoveryRequired) + ), + "{pointer}" + ); + } + let mut unknown = original.clone(); + unknown["unknown"] = json!(true); + assert!(matches!( + record::GrantRecord::decode(&serde_json::to_vec(&unknown).unwrap()), + Err(WorkspaceError::RecoveryRequired) + )); + let mut exhausted = original; + exhausted["revision"] = json!(i64::MAX.to_string()); + let mut exhausted = + record::GrantRecord::decode(&serde_json::to_vec(&exhausted).unwrap()).unwrap(); + assert_eq!(exhausted.revoke(), Err(WorkspaceError::RecoveryRequired)); + let record = record::GrantRecord::decode(&encoded).unwrap(); + assert_eq!( + record + .authenticate(&input, &proof, UnixSeconds::new(100).unwrap()) + .unwrap() + .grant_revision() + .get(), + 1 + ); +} + +struct FixedClock(u64); +impl WorkspaceClock for FixedClock { + fn now(&self) -> Result<UnixSeconds, WorkspaceError> { + UnixSeconds::new(self.0).map_err(|_| WorkspaceError::Unavailable) + } +} +#[tokio::test] +async fn enrollment_requires_bounded_principal_current_time_and_usable_key() { + for principal in [String::new(), "x".repeat(129), "bad\nlabel".into()] { + assert!(matches!( + LocalOutboxConfig::new( + participant(), + participant(), + principal, + UnixSeconds::new(200).unwrap() + ), + Err(WorkspaceError::InvalidInput) + )); + } + assert!(matches!( + LocalOutboxConfig::new( + participant(), + participant(), + "device", + UnixSeconds::new(0).unwrap() + ), + Err(WorkspaceError::InvalidInput) + )); + let fixture = CryptoFixture::new(); + for (now, expiry, expected) in [ + (0, 200, WorkspaceError::Unavailable), + (100, 100, WorkspaceError::GrantExpired), + ] { + let path = fixture + ._temp + .path() + .canonicalize() + .unwrap() + .join(format!("refused-{now}")); + let result = NativeWorkspace::initialize_local_outbox( + &path, + LocalOutboxConfig::new( + participant(), + participant(), + "device", + UnixSeconds::new(expiry).unwrap(), + ) + .unwrap(), + fixture.crypto(), + Arc::new(FixedClock(now)), + ) + .await; + assert!(matches!(result, Err(error) if error == expected)); + assert!(!path.exists()); + } + let wrong = WorkspaceCrypto::new( + fixture.provider.clone(), + reference("grant-key", BackendKind::File, 1), + SecretMaterial::from_slice(&[0x42; 32]).unwrap(), + AccessPolicy::standard(), + ) + .unwrap(); + let path = fixture + ._temp + .path() + .canonicalize() + .unwrap() + .join("wrong-key"); + assert!(matches!( + NativeWorkspace::initialize_local_outbox( + &path, + LocalOutboxConfig::new( + participant(), + participant(), + "device", + UnixSeconds::new(200).unwrap() + ) + .unwrap(), + wrong, + Arc::new(FixedClock(100)) + ) + .await, + Err(WorkspaceError::Unavailable) + )); + // Failed initialization remains visible. A second call cannot overwrite it. + assert!(matches!( + NativeWorkspace::initialize_local_outbox( + &path, + LocalOutboxConfig::new( + participant(), + participant(), + "device", + UnixSeconds::new(200).unwrap() + ) + .unwrap(), + fixture.crypto(), + Arc::new(FixedClock(100)) + ) + .await, + Err(WorkspaceError::NamespaceUnavailable) + )); +} + +fn set_mode(path: &std::path::Path, mode: u32) { + host_fs::set_permissions(path, host_fs::Permissions::from_mode(mode)).unwrap(); +} +#[test] +fn namespace_rechecks_permissions_links_replacement_and_sidecars() { + for fault in 0..8 { + let temp = tempfile::tempdir().unwrap(); + let base = temp.path().canonicalize().unwrap(); + let path = base.join("outbox"); + let namespace = fs::Namespace::acquire(&path, true).unwrap(); + let database = namespace.database_path(); + match fault { + 0 => set_mode(&path, 0o750), + 1 => set_mode(&database, 0o640), + 2 => { + host_fs::hard_link(&database, base.join("linked-database")).unwrap(); + } + 3 => { + host_fs::rename(&database, base.join("old-database")).unwrap(); + host_fs::write(&database, b"replacement").unwrap(); + set_mode(&database, 0o600); + } + 4 => { + let lock = path.join(".execution_v1.lock"); + host_fs::rename(&lock, base.join("old-lock")).unwrap(); + host_fs::write(&lock, b"").unwrap(); + set_mode(&lock, 0o600); + } + 5 => { + host_fs::rename(&path, base.join("old-root")).unwrap(); + host_fs::DirBuilder::new() + .mode(0o700) + .create(&path) + .unwrap(); + } + 6 => { + let sidecar = path.join("execution_v1.sqlite-wal"); + host_fs::write(&sidecar, b"").unwrap(); + set_mode(&sidecar, 0o644); + } + 7 => { + symlink(&database, path.join("execution_v1.sqlite-wal")).unwrap(); + } + _ => unreachable!(), + } + assert_eq!( + namespace.validate(), + Err(WorkspaceError::NamespaceUnavailable), + "fault {fault}" + ); + drop(namespace); + } + let temp = tempfile::tempdir().unwrap(); + let base = temp.path().canonicalize().unwrap(); + let path = base.join("outbox"); + let namespace = fs::Namespace::acquire(&path, true).unwrap(); + for suffix in ["-wal", "-shm", "-journal"] { + let path = path.join(format!("execution_v1.sqlite{suffix}")); + host_fs::write(&path, b"").unwrap(); + set_mode(&path, 0o600); + } + namespace.validate().unwrap(); + host_fs::write(path.join("unexpected"), b"retain").unwrap(); + assert_eq!(namespace.validate(), Err(WorkspaceError::RecoveryRequired)); + assert_eq!(host_fs::read(path.join("unexpected")).unwrap(), b"retain"); +} + +#[test] +fn namespace_refuses_unsafe_paths_empty_database_and_nonempty_lock_without_repair() { + assert!(matches!( + fs::Namespace::acquire(std::path::Path::new("relative"), false), + Err(WorkspaceError::NamespaceUnavailable) + )); + let temp = tempfile::tempdir().unwrap(); + let base = temp.path().canonicalize().unwrap(); + assert!(matches!( + fs::Namespace::acquire(&base.join("child/../outbox"), true), + Err(WorkspaceError::NamespaceUnavailable) + )); + let mutable = base.join("mutable"); + host_fs::create_dir(&mutable).unwrap(); + set_mode(&mutable, 0o777); + assert!(matches!( + fs::Namespace::acquire(&mutable.join("outbox"), true), + Err(WorkspaceError::NamespaceUnavailable) + )); + let regular = base.join("regular"); + host_fs::write(&regular, b"retain").unwrap(); + assert!(matches!( + fs::Namespace::acquire(&regular, false), + Err(WorkspaceError::NamespaceUnavailable) + )); + let target = base.join("target"); + host_fs::create_dir(&target).unwrap(); + symlink(&target, base.join("alias")).unwrap(); + assert!(matches!( + fs::Namespace::acquire(&base.join("alias/outbox"), true), + Err(WorkspaceError::NamespaceUnavailable) + )); + for nonempty_lock in [false, true] { + let path = base.join(format!("existing-{nonempty_lock}")); + let namespace = fs::Namespace::acquire(&path, true).unwrap(); + drop(namespace); + if nonempty_lock { + host_fs::write(path.join(".execution_v1.lock"), b"retain").unwrap(); + } + assert!(matches!( + fs::Namespace::acquire(&path, false), + Err(WorkspaceError::RecoveryRequired) + )); + if nonempty_lock { + assert_eq!( + host_fs::read(path.join(".execution_v1.lock")).unwrap(), + b"retain" + ); + } + } +} + +#[tokio::test] +async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_rows_without_repair() +{ + use sqlx::Connection; + let fixture = CryptoFixture::new(); + let base = fixture._temp.path().canonicalize().unwrap(); + for fault in 0..7 { + let path = base.join(format!("corrupt-{fault}")); + let (store, input, proof) = NativeWorkspace::initialize_local_outbox( + &path, + LocalOutboxConfig::new( + participant(), + participant(), + "device", + UnixSeconds::new(200).unwrap(), + ) + .unwrap(), + fixture.crypto(), + Arc::new(FixedClock(100)), + ) + .await + .unwrap(); + let options = sqlx::sqlite::SqliteConnectOptions::new() + .filename(path.join("execution_v1.sqlite")) + .create_if_missing(false); + let mut connection = sqlx::SqliteConnection::connect_with(&options) + .await + .unwrap(); + sqlx::query("PRAGMA ignore_check_constraints=ON") + .execute(&mut connection) + .await + .unwrap(); + let statement = match fault { + 0 => "PRAGMA user_version=2", + 1 => "DELETE FROM workspace_grant", + 2 => "UPDATE workspace_grant SET grant_id=zeroblob(31)", + 3 => "UPDATE workspace_grant SET protected=zeroblob(0)", + 4 => "UPDATE workspace_grant SET protected=zeroblob(262145)", + 5 => "UPDATE workspace_grant SET protected=zeroblob(262144)", + 6 => "UPDATE workspace_grant SET workspace=zeroblob(31)", + _ => unreachable!(), + }; + sqlx::query(statement) + .execute(&mut connection) + .await + .unwrap(); + connection.close().await.unwrap(); + if fault != 0 { + assert!( + matches!( + store.authenticate(input.clone(), &proof).await, + Err(WorkspaceError::RecoveryRequired) + ), + "live fault {fault}" + ); + } + store.close().await.unwrap(); + let result = NativeWorkspace::open_existing( + &path, + input, + fixture.crypto(), + Arc::new(FixedClock(100)), + ) + .await; + assert!( + matches!(&result, Err(WorkspaceError::RecoveryRequired)), + "fault {fault}: {result:?}" + ); + let mut connection = sqlx::SqliteConnection::connect_with(&options.clone().read_only(true)) + .await + .unwrap(); + let version: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&mut connection) + .await + .unwrap(); + let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM workspace_grant") + .fetch_one(&mut connection) + .await + .unwrap(); + assert_eq!(version, if fault == 0 { 2 } else { 1 }); + assert_eq!(rows, if fault == 1 { 0 } else { 1 }); + if (3..=5).contains(&fault) { + let size: i64 = sqlx::query_scalar("SELECT length(protected) FROM workspace_grant") + .fetch_one(&mut connection) + .await + .unwrap(); + assert_eq!(size, [0, 262145, 262144][fault - 3]); + } + connection.close().await.unwrap(); + } +} diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -0,0 +1,400 @@ +use super::{ + AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceCrypto, + WorkspaceError, fs::Namespace, record::GrantRecord, +}; +use sqlx::{ + Connection, Row, SqliteConnection, + sqlite::{SqliteConnectOptions, SqliteJournalMode, SqliteSynchronous}, +}; +use std::{ + path::PathBuf, + sync::{ + Arc, Mutex, + mpsc::{self, SyncSender}, + }, + thread::JoinHandle, + time::Duration, +}; +use tokio::sync::{oneshot, watch}; + +// Each request holds bounded descriptors and one 32-byte proof. With 32 +// queued requests and a single in-flight request this is below the 4 MiB +// contract. No raw event/command/SQL or unbounded payload enters this queue. +const QUEUE_CAPACITY: usize = 32; +const TABLE: &str = "CREATE TABLE workspace_grant (singleton INTEGER PRIMARY KEY CHECK(singleton=1), workspace BLOB NOT NULL CHECK(length(workspace)=32), grant_id BLOB NOT NULL CHECK(length(grant_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT"; +type Reply<T> = oneshot::Sender<Result<T, WorkspaceError>>; +enum Job { + Authenticate(AttachmentInput, AttachmentProof, Reply<WorkspaceBinding>), + Revoke(AttachmentInput, AttachmentProof, Reply<()>), +} +pub(super) struct Handle { + sender: Mutex<Option<SyncSender<Job>>>, + completed: watch::Receiver<Option<Result<(), WorkspaceError>>>, + thread: Mutex<Option<JoinHandle<()>>>, +} +impl Handle { + pub(super) async fn launch( + path: PathBuf, + input: AttachmentInput, + initial: Option<GrantRecord>, + crypto: WorkspaceCrypto, + clock: Arc<dyn WorkspaceClock>, + ) -> Result<Self, WorkspaceError> { + let (sender, requests) = mpsc::sync_channel(QUEUE_CAPACITY); + let (ready, started) = oneshot::channel(); + let (completion, completed) = watch::channel(None); + let thread = std::thread::Builder::new() + .name("radroots_workspace".into()) + .spawn(move || { + let runtime = match tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + { + Ok(runtime) => runtime, + Err(_) => { + let _ = ready.send(Err(WorkspaceError::Unavailable)); + let _ = completion.send(Some(Err(WorkspaceError::Unavailable))); + return; + } + }; + // 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()) { + Ok(namespace) => namespace, + Err(error) => { + let _ = ready.send(Err(error)); + let _ = completion.send(Some(Err(error))); + return; + } + }; + let result = runtime.block_on(async { + if initial.is_none() { + let preflight = preflight_existing(&namespace, &input, &crypto).await; + if let Err(error) = preflight { + let _ = ready.send(Err(error)); + return Err(error); + } + } + let options = SqliteConnectOptions::new() + .filename(namespace.database_path()) + .create_if_missing(false) + .journal_mode(SqliteJournalMode::Wal) + .synchronous(SqliteSynchronous::Full) + .foreign_keys(true) + .busy_timeout(Duration::from_secs(5)); + let mut connection = match SqliteConnection::connect_with(&options).await { + Ok(connection) => connection, + Err(_) => { + let _ = ready.send(Err(WorkspaceError::StorageFailure)); + return Err(WorkspaceError::StorageFailure); + } + }; + let initialized = + initialize(&mut connection, &namespace, &input, initial, &crypto).await; + if let Err(error) = initialized { + let _ = ready.send(Err(error)); + // Do not release namespace authority at the first failure; + // first await the actual connection's close completion. + let _ = connection.close().await; + return Err(error); + } + if ready.send(Ok(())).is_ok() { + while let Ok(job) = requests.recv() { + match job { + Job::Authenticate(selected, proof, reply) => { + let result = authenticate( + &mut connection, + &namespace, + &input, + &crypto, + clock.as_ref(), + &selected, + &proof, + ) + .await + .map(|(_, binding)| binding); + let _ = reply.send(result); + } + Job::Revoke(selected, proof, reply) => { + let result = revoke( + &mut connection, + &namespace, + &input, + &crypto, + clock.as_ref(), + &selected, + &proof, + ) + .await; + let _ = reply.send(result); + } + } + } + } + // The admission sender is gone. All admitted work has drained. + let checkpoint = sqlx::query("PRAGMA wal_checkpoint(TRUNCATE)") + .fetch_one(&mut connection) + .await; + let checked = match checkpoint { + Ok(row) if row.try_get::<i64, _>(0).ok() == Some(0) => Ok(()), + _ => Err(WorkspaceError::StorageFailure), + }; + let closed = connection + .close() + .await + .map_err(|_| WorkspaceError::StorageFailure); + checked.and(closed).and_then(|()| namespace.validate()) + }); + drop(namespace); + let _ = completion.send(Some(result)); + }) + .map_err(|_| WorkspaceError::Unavailable)?; + let handle = Self { + sender: Mutex::new(Some(sender)), + completed, + thread: Mutex::new(Some(thread)), + }; + match started.await { + Ok(Ok(())) => Ok(handle), + Ok(Err(error)) => { + let _ = handle.close().await; + Err(error) + } + Err(_) => { + let _ = handle.close().await; + Err(WorkspaceError::Unavailable) + } + } + } + fn send(&self, job: Job) -> Result<(), WorkspaceError> { + self.sender + .lock() + .map_err(|_| WorkspaceError::Unavailable)? + .as_ref() + .ok_or(WorkspaceError::Closed)? + .try_send(job) + .map_err(|error| match error { + mpsc::TrySendError::Full(_) => WorkspaceError::Unavailable, + mpsc::TrySendError::Disconnected(_) => WorkspaceError::Closed, + }) + } + pub(super) async fn authenticate( + &self, + input: AttachmentInput, + proof: AttachmentProof, + ) -> Result<WorkspaceBinding, WorkspaceError> { + let (reply, result) = oneshot::channel(); + self.send(Job::Authenticate(input, proof, reply))?; + result.await.map_err(|_| WorkspaceError::Unavailable)? + } + pub(super) async fn revoke( + &self, + input: AttachmentInput, + proof: &AttachmentProof, + ) -> Result<(), WorkspaceError> { + let proof = proof.with_secret(|secret| AttachmentProof::from_protected_input(secret))?; + let (reply, result) = oneshot::channel(); + self.send(Job::Revoke(input, proof, reply))?; + result.await.map_err(|_| WorkspaceError::CommitUnknown)? + } + pub(super) async fn close(&self) -> Result<(), WorkspaceError> { + self.sender + .lock() + .map_err(|_| WorkspaceError::Unavailable)? + .take(); + let mut completed = self.completed.clone(); + let result = loop { + if let Some(result) = *completed.borrow_and_update() { + break result; + } + completed + .changed() + .await + .map_err(|_| WorkspaceError::Unavailable)?; + }; + if let Some(thread) = self + .thread + .lock() + .map_err(|_| WorkspaceError::Unavailable)? + .take() + { + thread.join().map_err(|_| WorkspaceError::Unavailable)?; + } + result + } +} + +async fn preflight_existing( + namespace: &Namespace, + expected: &AttachmentInput, + crypto: &WorkspaceCrypto, +) -> Result<(), WorkspaceError> { + // Inspect through SQLite read-only before any persistent journal setting or + // writable connection. Do not turn a foreign schema into a workspace. + let options = SqliteConnectOptions::new() + .filename(namespace.database_path()) + .read_only(true) + .create_if_missing(false) + .pragma("query_only", "ON") + .busy_timeout(Duration::from_secs(5)); + let mut connection = SqliteConnection::connect_with(&options) + .await + .map_err(|_| WorkspaceError::RecoveryRequired)?; + let inspected = initialize(&mut connection, namespace, expected, None, crypto).await; + let closed = connection + .close() + .await + .map_err(|_| WorkspaceError::StorageFailure); + inspected.and(closed) +} + +async fn initialize( + connection: &mut SqliteConnection, + namespace: &Namespace, + expected: &AttachmentInput, + initial: Option<GrantRecord>, + crypto: &WorkspaceCrypto, +) -> Result<(), WorkspaceError> { + namespace.validate()?; + if let Some(initial) = initial { + let plaintext = initial.encode()?; + let protected = crypto + .seal(expected.workspace_id(), expected.grant_id(), &plaintext) + .await?; + let mut transaction = connection + .begin() + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + sqlx::raw_sql(TABLE) + .execute(&mut *transaction) + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + sqlx::query("PRAGMA user_version=1") + .execute(&mut *transaction) + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + sqlx::query( + "INSERT INTO workspace_grant(singleton,workspace,grant_id,protected) VALUES(1,?,?,?)", + ) + .bind(expected.workspace_id().as_bytes().as_slice()) + .bind(expected.grant_id().as_bytes().as_slice()) + .bind(protected) + .execute(&mut *transaction) + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + transaction + .commit() + .await + .map_err(|_| WorkspaceError::CommitUnknown)?; + } + let version: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&mut *connection) + .await + .map_err(|_| WorkspaceError::RecoveryRequired)?; + if version != 1 { + return Err(WorkspaceError::RecoveryRequired); + } + let catalog_matches: i64 = sqlx::query_scalar("SELECT CASE WHEN count(*)=1 AND sum(CASE WHEN type='table' AND name='workspace_grant' AND tbl_name='workspace_grant' AND sql=? THEN 1 ELSE 0 END)=1 THEN 1 ELSE 0 END FROM sqlite_schema") + .bind(TABLE).fetch_one(&mut *connection).await.map_err(|_| WorkspaceError::RecoveryRequired)?; + if catalog_matches != 1 { + return Err(WorkspaceError::RecoveryRequired); + } + let integrity: String = sqlx::query_scalar("PRAGMA quick_check(1)") + .fetch_one(&mut *connection) + .await + .map_err(|_| WorkspaceError::RecoveryRequired)?; + if integrity != "ok" { + return Err(WorkspaceError::RecoveryRequired); + } + let protected = read(connection, expected).await?; + let plaintext = crypto + .open(expected.workspace_id(), expected.grant_id(), &protected) + .await?; + plaintext.expose_secret(GrantRecord::decode)?; + namespace.validate() +} +async fn read( + connection: &mut SqliteConnection, + expected: &AttachmentInput, +) -> Result<Vec<u8>, WorkspaceError> { + // Refuse oversized input in SQL before materializing the protected blob. + let row = sqlx::query("SELECT CASE WHEN length(workspace)=32 THEN workspace END,CASE WHEN length(grant_id)=32 THEN grant_id END,length(protected),CASE WHEN length(protected)<=262144 THEN protected END FROM workspace_grant WHERE singleton=1") + .fetch_optional(connection).await.map_err(|_| WorkspaceError::RecoveryRequired)?.ok_or(WorkspaceError::RecoveryRequired)?; + let workspace: Vec<u8> = row + .try_get::<Option<Vec<u8>>, _>(0) + .map_err(|_| WorkspaceError::RecoveryRequired)? + .ok_or(WorkspaceError::RecoveryRequired)?; + let grant: Vec<u8> = row + .try_get::<Option<Vec<u8>>, _>(1) + .map_err(|_| WorkspaceError::RecoveryRequired)? + .ok_or(WorkspaceError::RecoveryRequired)?; + if workspace != expected.workspace_id().as_bytes() || grant != expected.grant_id().as_bytes() { + return Err(WorkspaceError::WrongNamespace); + } + let length: i64 = row + .try_get(2) + .map_err(|_| WorkspaceError::RecoveryRequired)?; + if length <= 0 || length > 262144 { + return Err(WorkspaceError::RecoveryRequired); + } + row.try_get(3).map_err(|_| WorkspaceError::RecoveryRequired) +} +async fn authenticate( + connection: &mut SqliteConnection, + namespace: &Namespace, + expected: &AttachmentInput, + crypto: &WorkspaceCrypto, + clock: &dyn WorkspaceClock, + selected: &AttachmentInput, + proof: &AttachmentProof, +) -> Result<(GrantRecord, WorkspaceBinding), WorkspaceError> { + namespace.validate()?; + let protected = read(connection, expected).await?; + let plaintext = crypto + .open(expected.workspace_id(), expected.grant_id(), &protected) + .await?; + let record = plaintext.expose_secret(GrantRecord::decode)?; + let binding = record.authenticate(selected, proof, clock.now()?)?; + namespace.validate()?; + Ok((record, binding)) +} +async fn revoke( + connection: &mut SqliteConnection, + namespace: &Namespace, + expected: &AttachmentInput, + crypto: &WorkspaceCrypto, + clock: &dyn WorkspaceClock, + selected: &AttachmentInput, + proof: &AttachmentProof, +) -> Result<(), WorkspaceError> { + let (mut record, _) = authenticate( + connection, namespace, expected, crypto, clock, selected, proof, + ) + .await?; + record.revoke()?; + let plaintext = record.encode()?; + let protected = crypto + .seal(expected.workspace_id(), expected.grant_id(), &plaintext) + .await?; + namespace.validate()?; + let mut transaction = connection + .begin() + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + let changed = sqlx::query( + "UPDATE workspace_grant SET protected=? WHERE singleton=1 AND workspace=? AND grant_id=?", + ) + .bind(protected) + .bind(expected.workspace_id().as_bytes().as_slice()) + .bind(expected.grant_id().as_bytes().as_slice()) + .execute(&mut *transaction) + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + if changed.rows_affected() != 1 { + return Err(WorkspaceError::RecoveryRequired); + } + transaction + .commit() + .await + .map_err(|_| WorkspaceError::CommitUnknown) +} diff --git a/crates/storage_sqlite/tests/package_boundary.rs b/crates/storage_sqlite/tests/package_boundary.rs @@ -24,6 +24,8 @@ fn sqlite_storage_declares_the_final_backend_boundaries() { dependency_keys(MANIFEST), BTreeSet::from([ "fs2", + "getrandom", + "radroots_domain", "radroots_event", "radroots_event_codec", "radroots_secrets", @@ -32,7 +34,11 @@ fn sqlite_storage_declares_the_final_backend_boundaries() { "serde", "serde_json", "sha2", + "rustix", + "subtle", "sqlx", + "tokio", + "zeroize", ]) ); assert!(!ROOT.contains("SqlitePool")); @@ -60,6 +66,7 @@ fn sqlite_storage_declares_the_final_backend_boundaries() { "migration", "open", "status", + "workspace", ]) ); } diff --git a/crates/storage_sqlite/tests/workspace_attachment.rs b/crates/storage_sqlite/tests/workspace_attachment.rs @@ -0,0 +1,504 @@ +#![cfg(unix)] + +use radroots_domain::{ + ActorRole, AuthorityRef, CheckpointDigest, CheckpointRef, ExecutorId, Generation, GrantId, + PublicKey, RouteDigest, UnixSeconds, WorkspaceId, +}; +use radroots_secrets::{ + SecretId, SecretRef, + envelope::Nonce, + file::{FileOpenMode, FileProvider}, + id::{BackendKind, KeyVersion}, + provider::AccessPolicy, + wrapping::SecretMaterial, +}; +use radroots_storage::workspace::{ + AttachmentInput, AttachmentProof, WorkspaceClock, WorkspaceError, +}; +use radroots_storage_sqlite::workspace::{LocalOutboxConfig, NativeWorkspace, WorkspaceCrypto}; +use std::{ + path::PathBuf, + sync::{ + Arc, + atomic::{AtomicU64, Ordering}, + }, +}; + +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 Fixture { + _temp: tempfile::TempDir, + path: PathBuf, + provider: Arc<FileProvider>, + reference: SecretRef, + clock: Arc<Clock>, +} +impl Fixture { + fn new() -> Self { + let temp = tempfile::tempdir().unwrap(); + let base = temp.path().canonicalize().unwrap(); + let provider = Arc::new( + FileProvider::open( + base.join("vault"), + FileOpenMode::CreateNew, + SecretMaterial::from_slice(&[0xA5; 32]).unwrap(), + ) + .unwrap(), + ); + let reference = SecretRef::new( + SecretId::parse("workspace-key").unwrap(), + BackendKind::File, + KeyVersion::new(1).unwrap(), + ); + provider + .provision( + &reference, + &SecretMaterial::from_slice(&[0x41; 32]).unwrap(), + Nonce::new([0x11; 24]), + ) + .unwrap(); + Self { + _temp: temp, + path: base.join("outbox"), + provider, + reference, + clock: Arc::new(Clock(AtomicU64::new(100))), + } + } + fn crypto(&self) -> WorkspaceCrypto { + self.crypto_with([0x41; 32]) + } + fn crypto_with(&self, key: [u8; 32]) -> WorkspaceCrypto { + let reference = SecretRef::new( + self.reference.id().clone(), + self.reference.backend(), + self.reference.key_version(), + ); + WorkspaceCrypto::new( + self.provider.clone(), + reference, + SecretMaterial::from_slice(&key).unwrap(), + AccessPolicy::standard(), + ) + .unwrap() + } + fn config(&self) -> LocalOutboxConfig { + LocalOutboxConfig::new( + key(), + key(), + "synthetic-device", + UnixSeconds::new(200).unwrap(), + ) + .unwrap() + } + async fn create(&self) -> (NativeWorkspace, AttachmentInput, AttachmentProof) { + NativeWorkspace::initialize_local_outbox( + &self.path, + self.config(), + self.crypto(), + self.clock.clone(), + ) + .await + .unwrap() + } +} +fn key() -> PublicKey { + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() +} +fn second_key() -> PublicKey { + PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5").unwrap() +} +fn altered(input: &AttachmentInput, field: u8) -> AttachmentInput { + AttachmentInput::new( + if field == 0 { + WorkspaceId::from_bytes([9; 32]) + } else { + input.workspace_id() + }, + if field == 1 { + AuthorityRef::new( + ExecutorId::from_bytes([9; 32]), + input.authority().generation(), + ) + } else if field == 2 { + AuthorityRef::new(input.authority().executor_id(), Generation::new(2).unwrap()) + } else { + input.authority() + }, + if field == 3 { + second_key() + } else { + input.participant() + }, + if field == 4 { + "local://other" + } else { + input.endpoint() + }, + if field == 5 { + second_key() + } else { + input.endpoint_identity() + }, + if field == 6 { + GrantId::from_bytes([9; 32]) + } else { + input.grant_id() + }, + if field == 7 { + CheckpointRef::new( + CheckpointDigest::from_bytes([9; 32]), + input.checkpoint().sequence(), + input.checkpoint().coverage(), + vec![], + ) + .unwrap() + } else { + input.checkpoint().clone() + }, + if field == 8 { + RouteDigest::from_bytes([9; 32]) + } else { + input.route_digest() + }, + ) + .unwrap() +} + +#[tokio::test] +async fn actual_protected_outbox_authenticates_exact_selection_and_reopens() { + let fixture = Fixture::new(); + let (store, input, proof) = fixture.create().await; + let binding = store.authenticate(input.clone(), &proof).await.unwrap(); + assert_eq!(binding.actor().role(), ActorRole::Buyer); + assert_eq!(binding.actor().grant_id(), Some(input.grant_id())); + assert_eq!(binding.principal_id(), "synthetic-device"); + assert_eq!(binding.observed_at().get(), 100); + assert_eq!(binding.grant_revision().get(), 1); + assert_eq!(input.checkpoint().sequence().get(), 0); + assert_eq!( + input.checkpoint().coverage(), + radroots_domain::Coverage::Partial + ); + for field in 0..9 { + assert!( + store + .authenticate(altered(&input, field), &proof) + .await + .is_err(), + "field {field}" + ); + } + let wrong = AttachmentProof::from_protected_input(&[0; 32]).unwrap(); + assert_eq!( + store.authenticate(input.clone(), &wrong).await.unwrap_err(), + WorkspaceError::Unauthorized + ); + assert!(matches!( + NativeWorkspace::open_existing( + &fixture.path, + input.clone(), + fixture.crypto(), + fixture.clock.clone() + ) + .await, + Err(WorkspaceError::WriterActive) + )); + let mut files = std::fs::read_dir(&fixture.path) + .unwrap() + .map(|entry| entry.unwrap().path()) + .collect::<Vec<_>>(); + files.push(fixture.path.join("execution_v1.sqlite")); + for path in files { + if !path.is_file() { + continue; + } + let bytes = std::fs::read(path).unwrap(); + assert!( + !bytes + .windows(b"synthetic-device".len()) + .any(|window| window == b"synthetic-device") + ); + proof.with_secret(|secret| assert!(!bytes.windows(32).any(|window| window == secret))); + } + assert_eq!(format!("{proof:?}"), "AttachmentProof(<redacted>)"); + assert_eq!(format!("{store:?}"), "NativeWorkspace(<redacted>)"); + store.close().await.unwrap(); + store.close().await.unwrap(); + assert_eq!( + store.authenticate(input.clone(), &proof).await.unwrap_err(), + WorkspaceError::Closed + ); + let reopened = NativeWorkspace::open_existing( + &fixture.path, + input.clone(), + fixture.crypto(), + fixture.clock.clone(), + ) + .await + .unwrap(); + reopened.authenticate(input.clone(), &proof).await.unwrap(); + reopened.close().await.unwrap(); + assert!(matches!( + NativeWorkspace::open_existing( + &fixture.path, + input, + fixture.crypto_with([0x42; 32]), + fixture.clock.clone() + ) + .await, + Err(WorkspaceError::Unavailable) + )); +} + +#[tokio::test] +async fn actual_revocation_and_expiry_survive_reopen_without_reenrollment() { + let fixture = Fixture::new(); + let (store, input, proof) = fixture.create().await; + fixture.clock.0.store(200, Ordering::SeqCst); + assert_eq!( + store.authenticate(input.clone(), &proof).await.unwrap_err(), + WorkspaceError::GrantExpired + ); + fixture.clock.0.store(0, Ordering::SeqCst); + assert_eq!( + store.authenticate(input.clone(), &proof).await.unwrap_err(), + WorkspaceError::Unavailable + ); + fixture.clock.0.store(101, Ordering::SeqCst); + store.revoke(input.clone(), &proof).await.unwrap(); + assert_eq!( + store.authenticate(input.clone(), &proof).await.unwrap_err(), + WorkspaceError::GrantRevoked + ); + store.close().await.unwrap(); + let reopened = NativeWorkspace::open_existing( + &fixture.path, + input.clone(), + fixture.crypto(), + fixture.clock.clone(), + ) + .await + .unwrap(); + assert_eq!( + reopened.authenticate(input, &proof).await.unwrap_err(), + WorkspaceError::GrantRevoked + ); + reopened.close().await.unwrap(); + assert!( + NativeWorkspace::initialize_local_outbox( + &fixture.path, + fixture.config(), + fixture.crypto(), + fixture.clock.clone() + ) + .await + .is_err() + ); +} + +#[tokio::test] +async fn existing_open_never_creates_or_accepts_wrong_namespace_or_ciphertext() { + let fixture = Fixture::new(); + let (store, input, proof) = fixture.create().await; + store.close().await.unwrap(); + assert!(matches!( + NativeWorkspace::open_existing( + &fixture.path, + altered(&input, 0), + fixture.crypto(), + fixture.clock.clone() + ) + .await, + Err(WorkspaceError::WrongNamespace) + )); + let missing = fixture.path.with_file_name("missing"); + assert!( + NativeWorkspace::open_existing( + &missing, + input.clone(), + fixture.crypto(), + fixture.clock.clone() + ) + .await + .is_err() + ); + assert!(!missing.exists()); + use sqlx::Connection; + let options = sqlx::sqlite::SqliteConnectOptions::new() + .filename(fixture.path.join("execution_v1.sqlite")); + let mut connection = sqlx::SqliteConnection::connect_with(&options) + .await + .unwrap(); + sqlx::query("UPDATE workspace_grant SET protected=zeroblob(1024)") + .execute(&mut connection) + .await + .unwrap(); + connection.close().await.unwrap(); + assert!(matches!( + NativeWorkspace::open_existing( + &fixture.path, + input, + fixture.crypto(), + fixture.clock.clone() + ) + .await, + Err(WorkspaceError::RecoveryRequired) + )); + assert_eq!(format!("{proof:?}"), "AttachmentProof(<redacted>)"); +} + +struct PausedClock { + state: std::sync::Mutex<(bool, bool, bool)>, + changed: std::sync::Condvar, +} +impl PausedClock { + fn arm(&self) { + *self.state.lock().unwrap() = (true, false, false); + } + fn entered(&self) { + let state = self.state.lock().unwrap(); + let (state, timeout) = self + .changed + .wait_timeout_while(state, std::time::Duration::from_secs(5), |state| !state.1) + .unwrap(); + assert!( + state.1 && !timeout.timed_out(), + "worker did not reach injected clock" + ); + } + fn release(&self) { + self.state.lock().unwrap().2 = true; + self.changed.notify_all(); + } +} +impl WorkspaceClock for PausedClock { + fn now(&self) -> Result<UnixSeconds, WorkspaceError> { + let mut state = self.state.lock().unwrap(); + if state.0 { + state.1 = true; + self.changed.notify_all(); + while !state.2 { + state = self.changed.wait(state).unwrap(); + } + state.0 = false; + } + Ok(UnixSeconds::new(100).unwrap()) + } +} +#[tokio::test] +async fn cancelled_authentication_and_close_keep_writer_until_owned_work_drains() { + let fixture = Fixture::new(); + let clock = Arc::new(PausedClock { + state: std::sync::Mutex::new((false, false, false)), + changed: std::sync::Condvar::new(), + }); + let (store, input, proof) = NativeWorkspace::initialize_local_outbox( + &fixture.path, + fixture.config(), + fixture.crypto(), + clock.clone(), + ) + .await + .unwrap(); + clock.arm(); + let mut auth = Box::pin(store.authenticate(input.clone(), &proof)); + assert!(futures::poll!(auth.as_mut()).is_pending()); + clock.entered(); + let mut closing = Box::pin(store.close()); + assert!(futures::poll!(closing.as_mut()).is_pending()); + drop(auth); + drop(closing); + assert!(matches!( + NativeWorkspace::open_existing( + &fixture.path, + input.clone(), + fixture.crypto(), + fixture.clock.clone() + ) + .await, + Err(WorkspaceError::WriterActive) + )); + clock.release(); + store.close().await.unwrap(); + let reopened = NativeWorkspace::open_existing( + &fixture.path, + input.clone(), + fixture.crypto(), + fixture.clock.clone(), + ) + .await + .unwrap(); + reopened.authenticate(input, &proof).await.unwrap(); + reopened.close().await.unwrap(); +} + +#[tokio::test] +async fn unsafe_links_permissions_and_schema_are_refused_without_repair() { + use std::os::unix::fs::{PermissionsExt, symlink}; + let fixture = Fixture::new(); + let (store, input, _proof) = fixture.create().await; + store.close().await.unwrap(); + let database = fixture.path.join("execution_v1.sqlite"); + let retained = fixture.path.join("retained.sqlite"); + std::fs::rename(&database, &retained).unwrap(); + symlink(&retained, &database).unwrap(); + assert!( + NativeWorkspace::open_existing( + &fixture.path, + input.clone(), + fixture.crypto(), + fixture.clock.clone() + ) + .await + .is_err() + ); + assert!( + std::fs::symlink_metadata(&database) + .unwrap() + .file_type() + .is_symlink() + ); + std::fs::remove_file(&database).unwrap(); + std::fs::rename(&retained, &database).unwrap(); + std::fs::set_permissions(&database, std::fs::Permissions::from_mode(0o644)).unwrap(); + assert!( + NativeWorkspace::open_existing( + &fixture.path, + input.clone(), + fixture.crypto(), + fixture.clock.clone() + ) + .await + .is_err() + ); + assert_eq!( + std::fs::metadata(&database).unwrap().permissions().mode() & 0o777, + 0o644 + ); + std::fs::set_permissions(&database, std::fs::Permissions::from_mode(0o600)).unwrap(); + use sqlx::Connection; + let options = sqlx::sqlite::SqliteConnectOptions::new().filename(&database); + let mut connection = sqlx::SqliteConnection::connect_with(&options) + .await + .unwrap(); + sqlx::query("CREATE TABLE unrelated(value TEXT)") + .execute(&mut connection) + .await + .unwrap(); + connection.close().await.unwrap(); + assert!(matches!( + NativeWorkspace::open_existing( + &fixture.path, + input, + fixture.crypto(), + fixture.clock.clone() + ) + .await, + Err(WorkspaceError::RecoveryRequired) + )); +}