commit 51e65ed095b46ce7e717a08ecda9fd7de5b77778 parent d5e023b3fc97764a7821b347756eb8987dc78739 Author: triesap <tyson@radroots.org> Date: Sun, 18 Oct 2026 23:36:33 +0000 storage: Own authenticated browser local outboxes - Share bounded buyer enrollment and protected grant rules between hosts. - Retain exclusive writer ownership through drained IndexedDB closure. - Recheck time eligibility inside active atomic write callbacks. - Exercise browser restarts, lease loss and native inquiry recovery. Diffstat:
31 files changed, 1732 insertions(+), 284 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock @@ -3649,6 +3649,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "subtle", "zeroize", ] @@ -3658,10 +3659,15 @@ version = "0.1.0-alpha" dependencies = [ "futures", "js-sys", + "radroots_domain", + "radroots_secrets", "radroots_storage", + "radroots_transport", + "sha2", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", + "zeroize", ] [[package]] diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -2178,7 +2178,31 @@ pub fn radroots_storage::status::StorageStatusProvider::storage_status(&self) -> 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 +pub mod radroots_storage::workspace::local_outbox +pub struct radroots_storage::workspace::local_outbox::LocalOutboxConfig +impl radroots_storage::workspace::local_outbox::LocalOutboxConfig +pub fn radroots_storage::workspace::local_outbox::LocalOutboxConfig::enroll(self, radroots_domain::context::UnixSeconds, radroots_domain::identifier::WorkspaceId, radroots_domain::identifier::ExecutorId, radroots_domain::identifier::GrantId, radroots_storage::workspace::AttachmentProof) -> core::result::Result<(radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof, radroots_storage::workspace::local_outbox::LocalOutboxGrant), radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage::workspace::local_outbox::LocalOutboxConfig::validate_at(&self, radroots_domain::context::UnixSeconds) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> +impl radroots_storage::workspace::local_outbox::LocalOutboxConfig +pub fn radroots_storage::workspace::local_outbox::LocalOutboxConfig::new(radroots_identity::key::PublicKey, radroots_identity::key::PublicKey, impl core::convert::AsRef<str>, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> +impl core::fmt::Debug for radroots_storage::workspace::local_outbox::LocalOutboxConfig +pub fn radroots_storage::workspace::local_outbox::LocalOutboxConfig::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::workspace::local_outbox::LocalOutboxGrant +impl radroots_storage::workspace::local_outbox::LocalOutboxGrant +pub fn radroots_storage::workspace::local_outbox::LocalOutboxGrant::authenticate(&self, &radroots_storage::workspace::AttachmentInput, &radroots_storage::workspace::AttachmentProof, radroots_domain::context::UnixSeconds) -> core::result::Result<radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage::workspace::local_outbox::LocalOutboxGrant::authenticate_retained_capture(&self, &radroots_storage::workspace::AttachmentInput, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage::workspace::local_outbox::LocalOutboxGrant::decode(&[u8]) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage::workspace::local_outbox::LocalOutboxGrant::encode(&self) -> core::result::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>, radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage::workspace::local_outbox::LocalOutboxGrant::new(radroots_storage::workspace::AttachmentInput, radroots_domain::context::ActorRef, alloc::string::String, radroots_domain::context::UnixSeconds, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage::workspace::local_outbox::LocalOutboxGrant::revoke(&mut self) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> +impl core::ops::drop::Drop for radroots_storage::workspace::local_outbox::LocalOutboxGrant +pub fn radroots_storage::workspace::local_outbox::LocalOutboxGrant::drop(&mut self) +pub const radroots_storage::workspace::local_outbox::GRANT_BYTES_MAX: usize +pub const radroots_storage::workspace::local_outbox::GRANT_ENVELOPE_PURPOSE: &str +pub const radroots_storage::workspace::local_outbox::GRANT_PAYLOAD_SCHEMA: &str +pub fn radroots_storage::workspace::local_outbox::grant_envelope_subject(radroots_domain::identifier::WorkspaceId, radroots_domain::identifier::GrantId) -> alloc::string::String #[non_exhaustive] pub enum radroots_storage::workspace::WorkspaceError +pub radroots_storage::workspace::WorkspaceError::Capacity pub radroots_storage::workspace::WorkspaceError::Closed pub radroots_storage::workspace::WorkspaceError::CommitUnknown pub radroots_storage::workspace::WorkspaceError::GrantExpired diff --git a/contracts/api_baselines/radroots_storage_indexeddb.wasm32_workspace.txt b/contracts/api_baselines/radroots_storage_indexeddb.wasm32_workspace.txt @@ -0,0 +1,69 @@ +pub mod radroots_storage_indexeddb +pub mod radroots_storage_indexeddb::workspace +pub use radroots_storage_indexeddb::workspace::LocalOutboxConfig +pub struct radroots_storage_indexeddb::workspace::BrowserWorkspace +impl radroots_storage_indexeddb::workspace::BrowserWorkspace +pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::close(&self) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> +pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::initialize_local_outbox(radroots_storage::workspace::local_outbox::LocalOutboxConfig, alloc::rc::Rc<dyn radroots_secrets::provider::SecretProvider>, radroots_secrets::id::SecretRef, radroots_secrets::provider::AccessPolicy, alloc::rc::Rc<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_indexeddb::workspace::BrowserWorkspace::open_existing(radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof, alloc::rc::Rc<dyn radroots_secrets::provider::SecretProvider>, radroots_secrets::id::SecretRef, radroots_secrets::provider::AccessPolicy, alloc::rc::Rc<dyn radroots_storage::workspace::WorkspaceClock>) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> +pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::revoke(&self, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> +impl core::fmt::Debug for radroots_storage_indexeddb::workspace::BrowserWorkspace +pub fn radroots_storage_indexeddb::workspace::BrowserWorkspace::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl radroots_storage::workspace::WorkspaceStore for radroots_storage_indexeddb::workspace::BrowserWorkspace +pub fn radroots_storage_indexeddb::workspace::BrowserWorkspace::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_indexeddb::workspace::BrowserWorkspace::close_workspace(&self) -> radroots_transport::source::BoxFuture<'_, core::result::Result<(), radroots_storage::workspace::WorkspaceError>> +#[non_exhaustive] pub enum radroots_storage_indexeddb::Error +pub radroots_storage_indexeddb::Error::Aborted +pub radroots_storage_indexeddb::Error::Capacity +pub radroots_storage_indexeddb::Error::Closed +pub radroots_storage_indexeddb::Error::CommitUnknown +pub radroots_storage_indexeddb::Error::Conflict +pub radroots_storage_indexeddb::Error::CorruptRecord +pub radroots_storage_indexeddb::Error::GuardRefused +pub radroots_storage_indexeddb::Error::IncompatibleSchema +pub radroots_storage_indexeddb::Error::InvalidInput +pub radroots_storage_indexeddb::Error::MissingNamespace +pub radroots_storage_indexeddb::Error::NamespaceExists +pub radroots_storage_indexeddb::Error::Unavailable +impl radroots_storage_indexeddb::Error +pub const fn radroots_storage_indexeddb::Error::code(self) -> &'static str +impl core::error::Error for radroots_storage_indexeddb::Error +impl core::fmt::Display for radroots_storage_indexeddb::Error +pub fn radroots_storage_indexeddb::Error::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub enum radroots_storage_indexeddb::OpenMode +pub radroots_storage_indexeddb::OpenMode::CreateNew +pub radroots_storage_indexeddb::OpenMode::Existing +pub struct radroots_storage_indexeddb::Batch +impl radroots_storage_indexeddb::Batch +pub fn radroots_storage_indexeddb::Batch::is_empty(&self) -> bool +pub fn radroots_storage_indexeddb::Batch::len(&self) -> usize +pub fn radroots_storage_indexeddb::Batch::new(alloc::vec::Vec<radroots_storage_indexeddb::Mutation>) -> core::result::Result<Self, radroots_storage_indexeddb::Error> +pub const fn radroots_storage_indexeddb::Batch::retained_bytes(&self) -> usize +impl core::fmt::Debug for radroots_storage_indexeddb::Batch +pub fn radroots_storage_indexeddb::Batch::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_indexeddb::Commit +impl radroots_storage_indexeddb::Commit +pub const fn radroots_storage_indexeddb::Commit::records(self) -> usize +pub struct radroots_storage_indexeddb::Database +impl radroots_storage_indexeddb::Database +pub async fn radroots_storage_indexeddb::Database::close(&self) -> core::result::Result<(), radroots_storage_indexeddb::Error> +pub async fn radroots_storage_indexeddb::Database::compare_exchange(&self, radroots_storage_indexeddb::Batch) -> core::result::Result<radroots_storage_indexeddb::Commit, radroots_storage_indexeddb::Error> +pub async fn radroots_storage_indexeddb::Database::compare_exchange_checked(&self, radroots_storage_indexeddb::Batch, impl core::ops::function::Fn() -> bool + 'static) -> core::result::Result<radroots_storage_indexeddb::Commit, radroots_storage_indexeddb::Error> +pub async fn radroots_storage_indexeddb::Database::get(&self, radroots_storage_indexeddb::RecordKey) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, radroots_storage_indexeddb::Error> +pub async fn radroots_storage_indexeddb::Database::open(radroots_storage_indexeddb::Namespace, radroots_storage_indexeddb::OpenMode) -> core::result::Result<Self, radroots_storage_indexeddb::Error> +pub struct radroots_storage_indexeddb::Mutation +impl radroots_storage_indexeddb::Mutation +pub fn radroots_storage_indexeddb::Mutation::new(radroots_storage_indexeddb::RecordKey, core::option::Option<alloc::vec::Vec<u8>>, core::option::Option<alloc::vec::Vec<u8>>) -> core::result::Result<Self, radroots_storage_indexeddb::Error> +impl core::fmt::Debug for radroots_storage_indexeddb::Mutation +pub fn radroots_storage_indexeddb::Mutation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_indexeddb::Namespace(_) +impl radroots_storage_indexeddb::Namespace +pub fn radroots_storage_indexeddb::Namespace::name(self) -> alloc::string::String +pub const fn radroots_storage_indexeddb::Namespace::new(radroots_storage::event::SourceGeneration) -> Self +pub struct radroots_storage_indexeddb::RecordKey(_) +impl radroots_storage_indexeddb::RecordKey +pub const fn radroots_storage_indexeddb::RecordKey::as_bytes(&self) -> &[u8; 32] +pub const fn radroots_storage_indexeddb::RecordKey::new([u8; 32]) -> Self +pub const radroots_storage_indexeddb::BATCH_RECORDS_MAX: usize +pub const radroots_storage_indexeddb::LIVE_BYTES_MAX: usize +pub const radroots_storage_indexeddb::RECORD_BYTES_MAX: usize diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -362,19 +362,15 @@ 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::LocalOutboxConfig 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::initialize_local_outbox(&std::path::Path, radroots_storage::workspace::local_outbox::LocalOutboxConfig, radroots_storage_sqlite::workspace::WorkspaceCrypto, alloc::sync::Arc<dyn radroots_storage::workspace::WorkspaceClock>) -> core::result::Result<(Self, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof), radroots_storage::workspace::WorkspaceError> pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::open_existing(&std::path::Path, radroots_storage::workspace::AttachmentInput, radroots_storage_sqlite::workspace::WorkspaceCrypto, alloc::sync::Arc<dyn radroots_storage::workspace::WorkspaceClock>) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::revoke(&self, radroots_storage::workspace::AttachmentInput, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> impl core::fmt::Debug for radroots_storage_sqlite::workspace::NativeWorkspace diff --git a/contracts/architecture/decisions/browser_workspace.v1.json b/contracts/architecture/decisions/browser_workspace.v1.json @@ -0,0 +1,65 @@ +{ + "schema_version": 1, + "contract_id": "radroots.storage.browser_workspace.v1", + "state": "implemented_workspace_component", + "owner": "radroots_storage_indexeddb", + "feature": "workspace", + "target": "wasm32-unknown-unknown", + "shared_policy": "radroots_storage::workspace::local_outbox", + "native_policy_consumer": "radroots_storage_sqlite::workspace", + "shared_grant_wire_private": true, + "default_import_side_effects": false, + "scope": "fresh_unrelated_buyer_outbox", + "stock_authority": false, + "participant_key_is_workspace_proof": false, + "full_operation_journal_or_client_claim": false, + "storage": { + "namespace_domain": "radroots.browser.local_outbox.namespace.v1", + "grant_key_domain": "radroots.browser.local_outbox.grant.v1", + "create_and_existing_open_separate": true, + "existing_requires_selection_and_protected_proof": true, + "grant_acknowledgement": "actual_indexeddb_transaction_completion", + "missing_or_damaged_state_replacement_allowed": false, + "envelope_version": 2, + "fresh_key_and_nonce_per_grant_seal": true, + "native_context_and_wire_preserved": true + }, + "writer": { + "mechanism": "origin_scoped_web_locks", + "mode": "exclusive", + "if_available": true, + "fallback_allowed": false, + "accepted_jobs_serial": true, + "accepted_work_rust_owned": true, + "admission_and_active_write_check_lease": true, + "active_write_callback_rechecks_clock_and_expiry": true, + "guard_refusal_aborts_whole_batch": true, + "close_order": [ + "stop_admission", + "drain_accepted_jobs", + "close_database", + "observe_released_lock_promise" + ] + }, + "resources": { + "clear_grant_bytes_max": 16384, + "protected_grant_bytes_max": 32768, + "conservative_job_reservation_bytes": 524288, + "live_job_bytes_max": 4194304, + "live_jobs_max_per_workspace": 8, + "setup_jobs_max_per_host_thread": 8, + "close_observers_max": 32, + "whole_browser_memory_bound_claim": false + }, + "qualification": { + "browsers": [ + "chromium", + "firefox", + "webkit" + ], + "main_thread_and_worker_required": true, + "actual_worker_termination_and_page_restart_required": true, + "native_workspace_and_ordinary_inquiry_regressions_required": true, + "final_phone_or_full_rcld_claim": false + } +} diff --git a/contracts/crates/catalog.v2.toml b/contracts/crates/catalog.v2.toml @@ -360,7 +360,7 @@ license = "MIT OR Apache-2.0" platforms = ["wasm32"] groups = ["coverage_required", "wasm"] owners = ["storage"] -permitted_dependency_tiers = ["spi"] +permitted_dependency_tiers = ["domain", "spi"] provenance_kind = "native" introduction_tree_sha256 = "82fc3620ff91692beab1d10d0f5384dc48fa236f0fe14d506ec12f28c9759b6c" compatibility = ["package_private", "rust_api"] diff --git a/contracts/crates/generated/package_groups.v1.toml b/contracts/crates/generated/package_groups.v1.toml @@ -1,5 +1,5 @@ schema = "radroots.workspace.package-groups.v1" -catalog_sha256 = "a64c4056370fcd715f6f13df879c71cf34f22520f29a53c0b8b17c7e9d17bde7" +catalog_sha256 = "39ff80bd34966be30ef54f5591d9ca149b869864ac3bcf1c7b97d91041759caa" [[group]] id = "boundaries" diff --git a/contracts/crates/generated/platform_inventory.v1.toml b/contracts/crates/generated/platform_inventory.v1.toml @@ -1,5 +1,5 @@ schema = "radroots.workspace.platform-inventory.v1" -catalog_sha256 = "a64c4056370fcd715f6f13df879c71cf34f22520f29a53c0b8b17c7e9d17bde7" +catalog_sha256 = "39ff80bd34966be30ef54f5591d9ca149b869864ac3bcf1c7b97d91041759caa" [[platform]] id = "any" diff --git a/contracts/crates/generated/release_inventory.v2.toml b/contracts/crates/generated/release_inventory.v2.toml @@ -1,5 +1,5 @@ schema = "radroots.workspace.release-inventory.v2" -catalog_sha256 = "a64c4056370fcd715f6f13df879c71cf34f22520f29a53c0b8b17c7e9d17bde7" +catalog_sha256 = "39ff80bd34966be30ef54f5591d9ca149b869864ac3bcf1c7b97d91041759caa" architecture = "radroots.crates.release.v2" version = "0.1.0-alpha" public_packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_domain", "radroots_event", "radroots_event_codec", "radroots_execution", "radroots_geonames", "radroots_identity", "radroots_nostr", "radroots_nostr_connect", "radroots_protocol", "radroots_sdk", "radroots_secrets", "radroots_signing", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_trade", "radroots_transport", "radroots_transport_nostr"] diff --git a/crates/storage/Cargo.toml b/crates/storage/Cargo.toml @@ -36,6 +36,7 @@ name = "radroots_storage" default = ["memory", "serde"] memory = [] command_journal = ["radroots_protocol/chat", "radroots_protocol/intent"] +protected_outbox = ["command_journal", "serde", "dep:serde_json", "dep:subtle"] serde = [ "dep:serde", "radroots_domain/serde", @@ -59,6 +60,8 @@ serde = { workspace = true, default-features = false, features = [ "derive", ], optional = true } sha2 = { workspace = true, default-features = false } +serde_json = { workspace = true, optional = true } +subtle = { workspace = true, optional = true } zeroize = { workspace = true, default-features = false } [dev-dependencies] diff --git a/crates/storage/README.md b/crates/storage/README.md @@ -73,10 +73,20 @@ protected-record internals. All SPIs are externally implementable and dyn-compatible. Native traits retain `Send + Sync` and boxed `Future + Send`; browser traits and futures may stay local. Every SPI uses the same target-aware transport host bounds and future -alias, allowing the host to choose the async executor. Implementations must not +alias, allowing the host to choose the async executor. SPI declarations and +pure value imports do not install an executor, spawn hidden workers, read a clock, generate identities, or perform implicit retries. +The opt-in `protected_outbox` feature supplies the pure local buyer-outbox +enrollment and validated protected-grant codec at `workspace::local_outbox`. +Concrete native/browser hosts share these rules and exact envelope context. +The codec's Serde wire stays private; decoding enforces the 16 KiB limit and +validates current scope. Enrollment takes qualified host identities and proof +without acquiring a backend or establishing durable authority. Concrete hosts +must protect, commit and authenticate that state through their explicit owned +lifecycle. This feature does not enable a database, provider or runtime. + `BackupSource::settle_backup_writes` waits for earlier owner writes, including work whose caller was cancelled. The host excludes new writes before settling and retains that exclusion through related inventory and capture. Settling does diff --git a/crates/storage/src/workspace.rs b/crates/storage/src/workspace.rs @@ -9,6 +9,9 @@ use radroots_domain::{ use radroots_transport::{BoxFuture, host::HostBound}; use zeroize::Zeroizing; +#[cfg(feature = "protected_outbox")] +pub mod local_outbox; + /// A fixed workspace boundary error; no path, credential, SQL or caller prose. #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[non_exhaustive] @@ -37,6 +40,8 @@ pub enum WorkspaceError { StaleCheckpoint, /// Admission is permanently closed. Closed, + /// The bounded host queue or close-observer budget is exhausted. + Capacity, /// Storage reports a known failure before confirmed completion. StorageFailure, /// Transaction completion is uncertain and must be reconciled. @@ -58,6 +63,7 @@ impl WorkspaceError { Self::StaleAuthority => "stale_authority", Self::StaleCheckpoint => "stale_checkpoint", Self::Closed => "closed", + Self::Capacity => "capacity_exhausted", Self::StorageFailure => "storage_failure", Self::CommitUnknown => "commit_unknown", } diff --git a/crates/storage/src/workspace/local_outbox.rs b/crates/storage/src/workspace/local_outbox.rs @@ -0,0 +1,294 @@ +//! Shared pure enrollment and protected grant rules for concrete local hosts. +//! No database, runtime, signer or provider is acquired here. +use super::{AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceError}; +use radroots_domain::{ + ActorRef, ActorRole, AuthorityRef, CheckpointDigest, CheckpointRef, Coverage, ExecutorId, + Generation, GrantId, PublicKey, RouteDigest, Sequence, UnixSeconds, WorkspaceId, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use subtle::ConstantTimeEq; +use zeroize::{Zeroize, Zeroizing}; +/// Maximum cleartext grant record, checked before decoding. +pub const GRANT_BYTES_MAX: usize = 16 * 1024; +/// Exact protected grant context, shared by concrete storage hosts. +pub const GRANT_ENVELOPE_PURPOSE: &str = "radroots.workspace.grant"; +pub const GRANT_PAYLOAD_SCHEMA: &str = "radroots.workspace.grant.v1"; +pub fn grant_envelope_subject(workspace: WorkspaceId, grant: GrantId) -> String { + // Both IDs have fixed-width canonical hexadecimal representations. + format!("{workspace}{grant}") +} +/// 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 AsRef<str>, + expires_at: UnixSeconds, + ) -> Result<Self, WorkspaceError> { + let principal = principal.as_ref(); + if principal.is_empty() + || principal.len() > 128 + || principal.chars().any(char::is_control) + || expires_at.get() == 0 + { + return Err(WorkspaceError::InvalidInput); + } + Ok(Self { + participant, + endpoint_identity, + principal: principal.to_owned(), + expires_at, + }) + } +} +impl std::fmt::Debug for LocalOutboxConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("LocalOutboxConfig(<redacted>)") + } +} + +impl LocalOutboxConfig { + /// Checks enrollment time without acquiring entropy or a host resource. + pub fn validate_at(&self, now: UnixSeconds) -> Result<(), WorkspaceError> { + if now.get() == 0 { + return Err(WorkspaceError::Unavailable); + } + if self.expires_at <= now { + return Err(WorkspaceError::GrantExpired); + } + Ok(()) + } + /// Pure trusted-host enrollment. Concrete hosts supply qualified fresh IDs + /// and a protected proof; this does not acquire or persist any authority. + pub fn enroll( + self, + now: UnixSeconds, + workspace: WorkspaceId, + executor: ExecutorId, + grant: GrantId, + proof: AttachmentProof, + ) -> Result<(AttachmentInput, AttachmentProof, LocalOutboxGrant), WorkspaceError> { + self.validate_at(now)?; + 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(self.endpoint_identity.as_bytes()); + route.update(endpoint.as_bytes()); + let route = RouteDigest::from_bytes(route.finalize().into()); + let mut checkpoint = Sha256::new(); + checkpoint.update(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, + self.participant, + endpoint, + self.endpoint_identity, + grant, + checkpoint, + route, + )?; + let actor = ActorRef::new(self.participant, ActorRole::Buyer, None, Some(grant)); + let record = LocalOutboxGrant::new( + input.clone(), + actor, + self.principal, + self.expires_at, + &proof, + )?; + Ok((input, proof, record)) + } +} +/// Validated protected local-outbox grant codec and current authorization rules. +/// Hosts authenticate its envelope before decoding; this value alone is no authority. +/// Raw Serde construction cannot bypass the bounded validating codec. +pub struct LocalOutboxGrant { + wire: GrantWire, +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct GrantWire { + 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 LocalOutboxGrant { + fn drop(&mut self) { + self.wire.verifier.zeroize(); + } +} +impl LocalOutboxGrant { + pub fn new( + input: AttachmentInput, + actor: ActorRef, + principal: String, + expires_at: UnixSeconds, + proof: &AttachmentProof, + ) -> Result<Self, WorkspaceError> { + let verifier = verifier(&input, proof); + let record = Self { + wire: GrantWire { + 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 fn decode(bytes: &[u8]) -> Result<Self, WorkspaceError> { + if bytes.len() > GRANT_BYTES_MAX { + return Err(WorkspaceError::RecoveryRequired); + } + let record = Self { + wire: serde_json::from_slice(bytes).map_err(|_| WorkspaceError::RecoveryRequired)?, + }; + record + .validate() + .map_err(|_| WorkspaceError::RecoveryRequired)?; + Ok(record) + } + pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>, WorkspaceError> { + self.validate()?; + let bytes = Zeroizing::new( + serde_json::to_vec(&self.wire).map_err(|_| WorkspaceError::StorageFailure)?, + ); + if bytes.len() > GRANT_BYTES_MAX { + return Err(WorkspaceError::InvalidInput); + } + Ok(bytes) + } + fn validate(&self) -> Result<(), WorkspaceError> { + if self.wire.version != 1 + || self.wire.actor.role() != ActorRole::Buyer + || self.wire.actor.organization().is_some() + || self.wire.actor.participant() != self.wire.input.participant() + || self.wire.actor.grant_id() != Some(self.wire.input.grant_id()) + || self.wire.principal.is_empty() + || self.wire.principal.len() > 128 + || self.wire.principal.chars().any(char::is_control) + || self.wire.revision.get() == 0 + || self.wire.expires_at.get() == 0 + { + return Err(WorkspaceError::InvalidInput); + } + Ok(()) + } + pub fn authenticate( + &self, + input: &AttachmentInput, + proof: &AttachmentProof, + now: UnixSeconds, + ) -> Result<WorkspaceBinding, WorkspaceError> { + self.authenticate_retained_capture(input, proof)?; + if self.wire.revoked { + return Err(WorkspaceError::GrantRevoked); + } + if now.get() == 0 { + return Err(WorkspaceError::Unavailable); + } + if self.wire.expires_at <= now { + return Err(WorkspaceError::GrantExpired); + } + self.validate()?; + WorkspaceBinding::from_authenticated_host( + self.wire.input.clone(), + self.wire.actor, + self.wire.principal.clone(), + self.wire.revision, + self.wire.expires_at, + now, + ) + } + /// Checks only the original protected credential and exact namespace scope. + /// This path is exclusively for appending a matching already obtained + /// artifact to an actual existing claim, never for new issuance or reads. + pub fn authenticate_retained_capture( + &self, + input: &AttachmentInput, + proof: &AttachmentProof, + ) -> Result<(), WorkspaceError> { + // Check the complete secret commitment before projecting detailed state. + let observed = Zeroizing::new(verifier(&self.wire.input, proof)); + if !bool::from(observed.as_ref().ct_eq(&self.wire.verifier)) { + return Err(WorkspaceError::Unauthorized); + } + if self.wire.input.workspace_id() != input.workspace_id() { + return Err(WorkspaceError::WrongNamespace); + } + if self.wire.input.authority() != input.authority() { + return Err(WorkspaceError::StaleAuthority); + } + if self.wire.input.checkpoint() != input.checkpoint() { + return Err(WorkspaceError::StaleCheckpoint); + } + if &self.wire.input != input { + return Err(WorkspaceError::Unauthorized); + } + self.validate() + } + pub fn revoke(&mut self) -> Result<(), WorkspaceError> { + self.wire.revoked = true; + self.wire.revision = Sequence::new( + self.wire + .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_indexeddb/Cargo.toml b/crates/storage_indexeddb/Cargo.toml @@ -11,15 +11,24 @@ homepage.workspace = true description = "Per-client IndexedDB atomic persistence for Radroots browser hosts" readme = "README.md" +[features] +default = [] +workspace = ["radroots_storage/protected_outbox", "dep:radroots_domain", "dep:radroots_secrets", "radroots_secrets/std", "dep:radroots_transport", "dep:sha2", "dep:zeroize"] + [dependencies] radroots_storage = { workspace = true } +radroots_domain = { workspace = true, optional = true } +radroots_secrets = { workspace = true, default-features = false, optional = true } +radroots_transport = { workspace = true, optional = true } +sha2 = { workspace = true, optional = true } +zeroize = { workspace = true, optional = true } [target.'cfg(target_arch = "wasm32")'.dependencies] futures = { workspace = true } js-sys = { workspace = true } wasm-bindgen = { workspace = true } wasm-bindgen-futures = { workspace = true } -web-sys = { workspace = true, features = ["DomException", "DomStringList", "Event", "EventTarget", "IdbDatabase", "IdbFactory", "IdbObjectStore", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "IdbVersionChangeEvent"] } +web-sys = { workspace = true, features = ["Crypto", "DomException", "DomStringList", "Event", "EventTarget", "IdbDatabase", "IdbFactory", "IdbObjectStore", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "IdbVersionChangeEvent"] } [lints] workspace = true diff --git a/crates/storage_indexeddb/README.md b/crates/storage_indexeddb/README.md @@ -11,9 +11,30 @@ IndexedDB callbacks. Success is returned only after `complete`; request success alone never acknowledges a commit. Accepted work remains owned after its observer is dropped. Closing stops admission and waits for accepted work. -This initial private host stores opaque bytes. It supplies no participant -custody, authenticated workspace, complete storage SPI or stock authority. -Callers must apply their own protected record codecs and exact journal rules. +The default private host stores opaque bytes. The opt-in `workspace` feature +adds `workspace::BrowserWorkspace`: an authenticated protected local buyer +outbox using the shared storage enrollment/grant rules and an explicitly +selected nonvolatile provider. It creates only a fresh unrelated outbox; +opening existing data requires its retained selection and protected proof. +It supplies no participant custody, complete operation journal/storage SPI or +stock authority. + +The workspace holds an actual exclusive origin Web Lock. Unavailable or +contended acquisition refuses; no in-memory substitute is selected. Accepted +jobs remain Rust-owned and serial through cancelled observation. Closing stops +admission, drains the jobs, closes IndexedDB, then observes actual lock release. +Its setup/connection queues reserve a conservative 512 KiB per job, accept at +most eight jobs within 4 MiB, and retain at most 32 weak close observations. +These limits cover owned inputs, not browser-internal or whole-process memory. +Clear grants are bounded to 16 KiB and their protected representation to 32 KiB. + +`compare_exchange_checked` runs a trusted host's synchronous eligibility check +in active write callbacks, after asynchronous crypto completes. Refusal aborts +the whole transaction. The workspace uses it to recheck current expiry/clock +and writer ownership before grant writes. Native and browser hosts share the +same grant context; generic authenticated envelope v2 remains unchanged. +No JavaScript object or key handle is exposed by the workspace API. The Web +Lock follows the [standard holding and released promise lifecycle](https://www.w3.org/TR/web-locks/#locks). Browser storage can be evicted; opening an absent namespace reports its absence. No SQL global, memory fallback, network, implicit migration or automatic replay is used. The transaction behavior follows the diff --git a/crates/storage_indexeddb/src/browser.rs b/crates/storage_indexeddb/src/browser.rs @@ -160,6 +160,23 @@ impl Database { /// All requests are enqueued in active callbacks; no user future runs /// inside a transaction. Only the complete event returns a Commit. pub async fn compare_exchange(&self, batch: Batch) -> Result<Commit, Error> { + self.exchange(batch, None).await + } + /// Runs a trusted host's synchronous eligibility check in each active + /// write callback. Refusal aborts the whole transaction, including earlier + /// writes. Captures must obey the concrete host's retained-input budget. + pub async fn compare_exchange_checked( + &self, + batch: Batch, + guard: impl Fn() -> bool + 'static, + ) -> Result<Commit, Error> { + self.exchange(batch, Some(Rc::new(guard))).await + } + async fn exchange( + &self, + batch: Batch, + guard: Option<Rc<dyn Fn() -> bool>>, + ) -> Result<Commit, Error> { let work = self.state.admit(batch.bytes)?; let (send, observe) = oneshot::channel(); spawn_local(async move { @@ -169,7 +186,7 @@ impl Database { .db .transaction_with_str_and_mode(STORE, IdbTransactionMode::Readwrite) { - Ok(tx) => exchange(tx, batch).await, + Ok(tx) => exchange(tx, batch, guard).await, Err(error) => Err(classify(error)), }; let _ = send.send(result); @@ -459,7 +476,11 @@ async fn read(tx: IdbTransaction, record: RecordKey) -> Result<Option<Vec<u8>>, completion.wait().await?; value.borrow_mut().take().ok_or(Error::CommitUnknown) } -async fn exchange(tx: IdbTransaction, batch: Batch) -> Result<Commit, Error> { +async fn exchange( + tx: IdbTransaction, + batch: Batch, + guard: Option<Rc<dyn Fn() -> bool>>, +) -> Result<Commit, Error> { let failure = Rc::new(Cell::new(None)); let mut completion = Completion::new(tx.clone(), failure.clone()); let mut handlers = Vec::with_capacity(batch.entries.len()); @@ -487,10 +508,15 @@ async fn exchange(tx: IdbTransaction, batch: Batch) -> Result<Commit, Error> { let store = store.clone(); let tx = tx.clone(); let failure = failure.clone(); + let guard = guard.clone(); Closure::new(move |_: Event| { if failure.get().is_some() { return; } + if guard.as_ref().is_some_and(|check| !check()) { + refuse(&tx, &failure, Error::GuardRefused); + return; + } if let Err(error) = apply(&store, &request, &entry) { refuse(&tx, &failure, error); } diff --git a/crates/storage_indexeddb/src/lib.rs b/crates/storage_indexeddb/src/lib.rs @@ -9,6 +9,9 @@ mod browser; #[cfg(target_arch = "wasm32")] pub use browser::Database; +#[cfg(all(feature = "workspace", target_arch = "wasm32"))] +pub mod workspace; + /// Maximum opaque record size; private codecs must enforce their lower limit. pub const RECORD_BYTES_MAX: usize = 64 * 1024; /// Maximum atomic batch width. @@ -28,6 +31,7 @@ pub enum Error { Closed, Capacity, Conflict, + GuardRefused, CorruptRecord, Aborted, CommitUnknown, @@ -43,6 +47,7 @@ impl Error { Self::Closed => "closed", Self::Capacity => "capacity_exhausted", Self::Conflict => "record_conflict", + Self::GuardRefused => "transaction_precondition_refused", Self::CorruptRecord => "corrupt_record", Self::Aborted => "transaction_aborted", Self::CommitUnknown => "commit_unknown", @@ -262,6 +267,7 @@ mod tests { Error::Closed, Error::Capacity, Error::Conflict, + Error::GuardRefused, Error::CorruptRecord, Error::Aborted, Error::CommitUnknown, diff --git a/crates/storage_indexeddb/src/workspace/crypto.rs b/crates/storage_indexeddb/src/workspace/crypto.rs @@ -0,0 +1,101 @@ +use js_sys::Reflect; +use radroots_domain::{GrantId, WorkspaceId}; +use radroots_secrets::{ + EncryptedEnvelope, SecretRef, + context::{EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId}, + envelope::{Nonce, SealMaterial, SealRequest}, + provider::SecretProvider, + wrapping::SecretMaterial, +}; +use radroots_storage::workspace::local_outbox::{ + GRANT_ENVELOPE_PURPOSE, GRANT_PAYLOAD_SCHEMA, grant_envelope_subject, +}; +use radroots_storage::workspace::{WorkspaceError, local_outbox::GRANT_BYTES_MAX}; +use wasm_bindgen::{JsCast, JsValue}; +use zeroize::Zeroizing; + +pub(super) const PROTECTED_MAX: usize = 32 * 1024; +pub(super) fn random<const N: usize>() -> Result<Zeroizing<[u8; N]>, WorkspaceError> { + let crypto = Reflect::get(&js_sys::global(), &JsValue::from_str("crypto")) + .map_err(|_| WorkspaceError::Unavailable)? + .dyn_into::<web_sys::Crypto>() + .map_err(|_| WorkspaceError::Unavailable)?; + let mut bytes = Zeroizing::new([0; N]); + crypto + .get_random_values_with_u8_array(bytes.as_mut()) + .map_err(|_| WorkspaceError::Unavailable)?; + Ok(bytes) +} +fn context(workspace: WorkspaceId, grant: GrantId) -> Result<EnvelopeContext, WorkspaceError> { + Ok(EnvelopeContext::new( + EnvelopePurpose::parse(GRANT_ENVELOPE_PURPOSE).map_err(|_| WorkspaceError::InvalidInput)?, + EnvelopeSubject::parse("workspace_grant", grant_envelope_subject(workspace, grant)) + .map_err(|_| WorkspaceError::InvalidInput)?, + PayloadSchemaId::parse(GRANT_PAYLOAD_SCHEMA).map_err(|_| WorkspaceError::InvalidInput)?, + )) +} +pub(super) async fn seal( + provider: &dyn SecretProvider, + reference: &SecretRef, + workspace: WorkspaceId, + grant: GrantId, + plaintext: &[u8], +) -> Result<Vec<u8>, WorkspaceError> { + if plaintext.len() > GRANT_BYTES_MAX { + return Err(WorkspaceError::InvalidInput); + } + let key = random::<32>()?; + let material = + SecretMaterial::from_slice(key.as_ref()).map_err(|_| WorkspaceError::Unavailable)?; + let plaintext = + SecretMaterial::from_slice(plaintext).map_err(|_| WorkspaceError::InvalidInput)?; + let nonce = random::<24>()?; + let result = EncryptedEnvelope::seal( + provider, + SealRequest::new( + SecretRef::new( + reference.id().clone(), + reference.backend(), + reference.key_version(), + ), + context(workspace, grant)?, + &plaintext, + SealMaterial::new(material, Nonce::new(*nonce)), + ), + ) + .await + .map_err(|_| WorkspaceError::Unavailable)? + .encode() + .map_err(|_| WorkspaceError::StorageFailure)?; + if result.len() > PROTECTED_MAX { + return Err(WorkspaceError::InvalidInput); + } + Ok(result) +} +pub(super) async fn open( + provider: &dyn SecretProvider, + reference: &SecretRef, + workspace: WorkspaceId, + grant: GrantId, + protected: &[u8], +) -> Result<SecretMaterial, WorkspaceError> { + if protected.len() > PROTECTED_MAX { + return Err(WorkspaceError::RecoveryRequired); + } + let envelope = + EncryptedEnvelope::decode(protected).map_err(|_| WorkspaceError::RecoveryRequired)?; + if envelope.reference().backend() != reference.backend() + || envelope.reference().id() != reference.id() + || envelope.reference().key_version() != reference.key_version() + { + return Err(WorkspaceError::RecoveryRequired); + } + let plaintext = envelope + .open(provider, &context(workspace, grant)?) + .await + .map_err(|_| WorkspaceError::RecoveryRequired)?; + if plaintext.len() > GRANT_BYTES_MAX { + return Err(WorkspaceError::RecoveryRequired); + } + Ok(plaintext) +} diff --git a/crates/storage_indexeddb/src/workspace/lease.rs b/crates/storage_indexeddb/src/workspace/lease.rs @@ -0,0 +1,109 @@ +//! Origin-scoped Web Lock, held until the actual database owner is finished. +use futures::channel::oneshot; +use js_sys::{Function, Object, Promise, Reflect}; +use radroots_storage::workspace::WorkspaceError; +use std::{ + cell::{Cell, RefCell}, + rc::Rc, +}; +use wasm_bindgen::{JsCast, JsValue, closure::Closure}; +use wasm_bindgen_futures::{JsFuture, future_to_promise, spawn_local}; + +pub(super) struct Lease { + release: Option<oneshot::Sender<()>>, + finished: Option<oneshot::Receiver<Result<(), WorkspaceError>>>, + active: Rc<Cell<bool>>, +} +impl Lease { + pub async fn acquire(name: &str) -> Result<Self, WorkspaceError> { + let unavailable = |_| WorkspaceError::Unavailable; + let navigator = + Reflect::get(&js_sys::global(), &"navigator".into()).map_err(unavailable)?; + let locks = Reflect::get(&navigator, &"locks".into()).map_err(unavailable)?; + let request = Reflect::get(&locks, &"request".into()) + .map_err(unavailable)? + .dyn_into::<Function>() + .map_err(unavailable)?; + let options = Object::new(); + Reflect::set(&options, &"mode".into(), &"exclusive".into()).map_err(unavailable)?; + Reflect::set(&options, &"ifAvailable".into(), &JsValue::TRUE).map_err(unavailable)?; + let (acquired, observe) = oneshot::channel(); + let acquired = Rc::new(RefCell::new(Some(acquired))); + let (release, released) = oneshot::channel(); + let mut released = Some(released); + let signal = acquired.clone(); + let active = Rc::new(Cell::new(false)); + let granted = active.clone(); + let callback = Closure::<dyn FnMut(JsValue) -> Promise>::new(move |lock: JsValue| { + if lock.is_null() || lock.is_undefined() { + if let Some(send) = signal.borrow_mut().take() { + let _ = send.send(Err(WorkspaceError::WriterActive)); + } + return Promise::resolve(&JsValue::UNDEFINED); + } + granted.set(true); + if let Some(send) = signal.borrow_mut().take() { + let _ = send.send(Ok(())); + } + let wait = released.take(); + future_to_promise(async move { + if let Some(wait) = wait { + let _ = wait.await; + } + Ok(JsValue::UNDEFINED) + }) + }); + // The stable Web Locks API is called locally; no global unstable + // web-sys compiler flag or public JavaScript object is required. + let promise = request + .call3( + &locks, + &JsValue::from_str(name), + &options, + callback.as_ref().unchecked_ref(), + ) + .map_err(unavailable)? + .dyn_into::<Promise>() + .map_err(unavailable)?; + let (done, finished) = oneshot::channel(); + let lifetime = active.clone(); + spawn_local(async move { + let result = JsFuture::from(promise) + .await + .map(|_| ()) + .map_err(unavailable); + lifetime.set(false); + if let Some(send) = acquired.borrow_mut().take() { + let _ = send.send(Err(WorkspaceError::Unavailable)); + } + let _ = done.send(result); + drop(callback); + }); + let lease = Self { + release: Some(release), + finished: Some(finished), + active, + }; + observe.await.map_err(|_| WorkspaceError::Unavailable)??; + Ok(lease) + } + pub fn active(&self) -> Rc<Cell<bool>> { + self.active.clone() + } + pub async fn release(mut self) -> Result<(), WorkspaceError> { + if let Some(send) = self.release.take() { + let _ = send.send(()); + } + match self.finished.take() { + Some(done) => done.await.map_err(|_| WorkspaceError::Unavailable)?, + None => Err(WorkspaceError::Unavailable), + } + } +} +impl Drop for Lease { + fn drop(&mut self) { + if let Some(send) = self.release.take() { + let _ = send.send(()); + } + } +} diff --git a/crates/storage_indexeddb/src/workspace/mod.rs b/crates/storage_indexeddb/src/workspace/mod.rs @@ -0,0 +1,498 @@ +//! Authenticated browser local outboxes, independent of participant signing. +//! Creation establishes a fresh unrelated buyer outbox only. Existing state +//! requires its independently retained selection and protected proof. +mod crypto; +mod lease; + +use super::{Batch, Database, Error, Mutation, Namespace, OpenMode, RecordKey}; +use futures::{channel::oneshot, lock::Mutex}; +use radroots_domain::{ExecutorId, GrantId, UnixSeconds, WorkspaceId}; +use radroots_secrets::{ + SecretRef, + provider::{AccessPolicy, ResidencySupport, SecretProvider, SelectionPolicy}, +}; +pub use radroots_storage::workspace::local_outbox::LocalOutboxConfig; +use radroots_storage::{ + event::SourceGeneration, + workspace::{ + AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceError, + WorkspaceStore, local_outbox::LocalOutboxGrant, + }, +}; +use radroots_transport::BoxFuture; +use sha2::{Digest, Sha256}; +use std::{ + cell::{Cell, RefCell}, + fmt, + future::{Future, poll_fn}, + rc::{Rc, Weak}, + task::{Poll, Waker}, +}; +use wasm_bindgen_futures::spawn_local; + +const JOB_BYTES: usize = 512 * 1024; +const LIVE_BYTES: usize = 4 * 1024 * 1024; +const JOBS: usize = LIVE_BYTES / JOB_BYTES; +const WAITERS: usize = 32; +type Signal = RefCell<Option<Waker>>; +thread_local! { static SETUPS: Cell<usize> = const { Cell::new(0) }; } +struct Setup; +impl Setup { + fn admit() -> Result<Self, WorkspaceError> { + SETUPS.with(|count| { + if count.get() >= JOBS { + return Err(WorkspaceError::Capacity); + } + count.set(count.get() + 1); + Ok(Self) + }) + } +} +impl Drop for Setup { + fn drop(&mut self) { + SETUPS.with(|count| count.set(count.get() - 1)); + } +} +fn stored(error: Error) -> WorkspaceError { + match error { + Error::Closed => WorkspaceError::Closed, + Error::Capacity => WorkspaceError::Capacity, + Error::CommitUnknown => WorkspaceError::CommitUnknown, + Error::MissingNamespace | Error::NamespaceExists => WorkspaceError::NamespaceUnavailable, + _ => WorkspaceError::RecoveryRequired, + } +} +fn namespace(input: &AttachmentInput) -> Result<Namespace, WorkspaceError> { + let mut digest = Sha256::new(); + digest.update(b"radroots.browser.local_outbox.namespace.v1\0"); + digest.update(input.workspace_id().as_bytes()); + SourceGeneration::new(digest.finalize().into()) + .map(Namespace::new) + .map_err(|_| WorkspaceError::InvalidInput) +} +fn grant_key() -> RecordKey { + RecordKey::new(Sha256::digest(b"radroots.browser.local_outbox.grant.v1\0").into()) +} +async fn commit_current( + db: &Database, + batch: Batch, + clock: Rc<dyn WorkspaceClock>, + observed: UnixSeconds, + expires: UnixSeconds, + active: Rc<Cell<bool>>, +) -> Result<(), WorkspaceError> { + let failure = Rc::new(Cell::new(None)); + let guard_failure = failure.clone(); + let result = db + .compare_exchange_checked(batch, move || { + let eligible = (|| { + if !active.get() { + return Err(WorkspaceError::Closed); + } + let now = clock.now()?; + if now.get() == 0 || now < observed { + return Err(WorkspaceError::Unavailable); + } + if now >= expires { + return Err(WorkspaceError::GrantExpired); + } + Ok(()) + })(); + if let Err(error) = eligible { + guard_failure.set(Some(error)); + false + } else { + true + } + }) + .await; + if let Some(error) = failure.get() { + return Err(error); + } + result.map(|_| ()).map_err(stored) +} +fn select( + provider: &dyn SecretProvider, + reference: &SecretRef, + policy: AccessPolicy, +) -> Result<(), WorkspaceError> { + if provider.capabilities().residency() == ResidencySupport::Volatile { + return Err(WorkspaceError::Unavailable); + } + SelectionPolicy::new(reference.backend(), policy) + .select(&[provider]) + .map_err(|_| WorkspaceError::Unavailable)?; + Ok(()) +} +struct State { + // Database drops before the lease if an unobserved owner is discarded. + db: Database, + provider: Rc<dyn SecretProvider>, + reference: SecretRef, + selected: AttachmentInput, + clock: Rc<dyn WorkspaceClock>, + lease: RefCell<Option<lease::Lease>>, + serial: Mutex<()>, + jobs: Cell<usize>, + closing: Cell<bool>, + closed: Cell<Option<Result<(), WorkspaceError>>>, + drain: RefCell<Option<Waker>>, + waiters: RefCell<Vec<Weak<Signal>>>, +} +impl State { + fn active(&self) -> Result<Rc<Cell<bool>>, WorkspaceError> { + let active = self + .lease + .borrow() + .as_ref() + .map(lease::Lease::active) + .ok_or(WorkspaceError::Closed)?; + if !active.get() { + return Err(WorkspaceError::Closed); + } + Ok(active) + } + fn admit(self: &Rc<Self>) -> Result<Work, WorkspaceError> { + if self.closing.get() { + return Err(WorkspaceError::Closed); + } + if self.active().is_err() { + self.stop(); + return Err(WorkspaceError::Closed); + } + if self.jobs.get() >= JOBS { + return Err(WorkspaceError::Capacity); + } + self.jobs.set(self.jobs.get() + 1); + Ok(Work(self.clone())) + } + fn stop(self: &Rc<Self>) { + if self.closing.replace(true) { + return; + } + let state = self.clone(); + spawn_local(async move { + poll_fn(|cx| { + if state.jobs.get() == 0 { + Poll::Ready(()) + } else { + *state.drain.borrow_mut() = Some(cx.waker().clone()); + Poll::Pending + } + }) + .await; + let database = state.db.close().await.map_err(stored); + let lease = state.lease.borrow_mut().take(); + let released = match lease { + Some(lease) => lease.release().await, + None => Err(WorkspaceError::RecoveryRequired), + }; + state.closed.set(Some(database.and(released))); + state.waiters.borrow_mut().retain(|weak| { + if let Some(signal) = weak.upgrade() { + if let Some(waker) = signal.borrow_mut().take() { + waker.wake(); + } + true + } else { + false + } + }); + }); + } + async fn access( + &self, + input: &AttachmentInput, + proof: &AttachmentProof, + ) -> Result<(LocalOutboxGrant, Vec<u8>, WorkspaceBinding), WorkspaceError> { + self.active()?; + if input != &self.selected { + return Err(WorkspaceError::Unauthorized); + } + let protected = self + .db + .get(grant_key()) + .await + .map_err(stored)? + .ok_or(WorkspaceError::RecoveryRequired)?; + let plaintext = crypto::open( + self.provider.as_ref(), + &self.reference, + self.selected.workspace_id(), + self.selected.grant_id(), + &protected, + ) + .await?; + let record = plaintext.expose_secret(LocalOutboxGrant::decode)?; + let binding = record.authenticate(input, proof, self.clock.now()?)?; + self.active()?; + Ok((record, protected, binding)) + } +} +struct Work(Rc<State>); +impl Drop for Work { + fn drop(&mut self) { + self.0.jobs.set(self.0.jobs.get() - 1); + if self.0.jobs.get() == 0 { + if let Some(waker) = self.0.drain.borrow_mut().take() { + waker.wake(); + } + } + } +} +async fn owned<T: 'static>( + work: Work, + future: impl Future<Output = Result<T, WorkspaceError>> + 'static, +) -> Result<T, WorkspaceError> { + let (send, observe) = oneshot::channel(); + spawn_local(async move { + let state = work.0.clone(); + let _work = work; + let _serial = state.serial.lock().await; + let result = future.await; + if matches!( + result, + Err(WorkspaceError::Closed + | WorkspaceError::Unavailable + | WorkspaceError::RecoveryRequired + | WorkspaceError::CommitUnknown) + ) { + state.stop(); + } + let _ = send.send(result); + }); + observe.await.unwrap_or(Err(WorkspaceError::CommitUnknown)) +} +/// One bounded browser writer. Clones share admission, serial work and actual +/// close completion. No proof or participant signer is retained in the handle. +#[derive(Clone)] +pub struct BrowserWorkspace { + state: Rc<State>, +} +impl BrowserWorkspace { + /// Enrolls only a new unrelated buyer outbox and returns its independently + /// retained selection/proof after the protected grant actually commits. + pub async fn initialize_local_outbox( + config: LocalOutboxConfig, + provider: Rc<dyn SecretProvider>, + reference: SecretRef, + policy: AccessPolicy, + clock: Rc<dyn WorkspaceClock>, + ) -> Result<(Self, AttachmentInput, AttachmentProof), WorkspaceError> { + select(provider.as_ref(), &reference, policy)?; + let setup = Setup::admit()?; + let now = clock.now()?; + config.validate_at(now)?; + let workspace = WorkspaceId::from_bytes(*crypto::random::<32>()?); + let executor = ExecutorId::from_bytes(*crypto::random::<32>()?); + let grant = GrantId::from_bytes(*crypto::random::<32>()?); + let secret = crypto::random::<32>()?; + let proof = AttachmentProof::from_protected_input(secret.as_ref())?; + let (input, proof, record) = config.enroll(now, workspace, executor, grant, proof)?; + let (send, observe) = oneshot::channel(); + spawn_local(async move { + let _setup = setup; + let result = async { + let selected = namespace(&input)?; + let lease = lease::Lease::acquire(&selected.name()).await?; + let db = match Database::open(selected, OpenMode::CreateNew).await { + Ok(db) => db, + Err(error) => { + lease.release().await?; + return Err(stored(error)); + } + }; + let owner = Self::assemble(db, provider, reference, input.clone(), clock, lease); + let initialized = async { + let bytes = record.encode()?; + let binding = record.authenticate(&input, &proof, now)?; + let protected = crypto::seal( + owner.state.provider.as_ref(), + &owner.state.reference, + workspace, + grant, + &bytes, + ) + .await?; + let batch = Batch::new(vec![ + Mutation::new(grant_key(), None, Some(protected)).map_err(stored)?, + ]) + .map_err(stored)?; + commit_current( + &owner.state.db, + batch, + owner.state.clock.clone(), + binding.observed_at(), + binding.expires_at(), + owner.state.active()?, + ) + .await?; + record.authenticate(&input, &proof, owner.state.clock.now()?)?; + Ok::<(), WorkspaceError>(()) + } + .await; + if let Err(error) = initialized { + owner.close().await?; + return Err(error); + } + Ok((owner, input, proof)) + } + .await; + let _ = send.send(result); + }); + observe.await.unwrap_or(Err(WorkspaceError::CommitUnknown)) + } + /// Opens an exact existing outbox and authenticates its retained protected + /// proof. Missing records never become a newly enrolled grant. + pub async fn open_existing( + input: AttachmentInput, + proof: AttachmentProof, + provider: Rc<dyn SecretProvider>, + reference: SecretRef, + policy: AccessPolicy, + clock: Rc<dyn WorkspaceClock>, + ) -> Result<Self, WorkspaceError> { + select(provider.as_ref(), &reference, policy)?; + let setup = Setup::admit()?; + let (send, observe) = oneshot::channel(); + spawn_local(async move { + let _setup = setup; + let result = async { + let selected = namespace(&input)?; + let lease = lease::Lease::acquire(&selected.name()).await?; + let db = match Database::open(selected, OpenMode::Existing).await { + Ok(db) => db, + Err(error) => { + lease.release().await?; + return Err(stored(error)); + } + }; + let owner = Self::assemble(db, provider, reference, input.clone(), clock, lease); + if let Err(error) = owner.state.access(&input, &proof).await { + owner.close().await?; + return Err(error); + } + Ok(owner) + } + .await; + let _ = send.send(result); + }); + observe.await.unwrap_or(Err(WorkspaceError::CommitUnknown)) + } + fn assemble( + db: Database, + provider: Rc<dyn SecretProvider>, + reference: SecretRef, + selected: AttachmentInput, + clock: Rc<dyn WorkspaceClock>, + lease: lease::Lease, + ) -> Self { + Self { + state: Rc::new(State { + db, + provider, + reference, + selected, + clock, + lease: RefCell::new(Some(lease)), + serial: Mutex::new(()), + jobs: Cell::new(0), + closing: Cell::new(false), + closed: Cell::new(None), + drain: RefCell::new(None), + waiters: RefCell::new(Vec::new()), + }), + } + } + /// Authenticates and atomically revokes the current protected grant. + pub async fn revoke( + &self, + input: AttachmentInput, + proof: AttachmentProof, + ) -> Result<(), WorkspaceError> { + let work = self.state.admit()?; + let state = self.state.clone(); + owned(work, async move { + let (mut record, expected, current) = state.access(&input, &proof).await?; + record.revoke()?; + let bytes = record.encode()?; + let protected = crypto::seal( + state.provider.as_ref(), + &state.reference, + input.workspace_id(), + input.grant_id(), + &bytes, + ) + .await?; + // A foreign writer cannot substitute the grant across async crypto. + let batch = Batch::new(vec![ + Mutation::new(grant_key(), Some(expected), Some(protected)).map_err(stored)?, + ]) + .map_err(stored)?; + commit_current( + &state.db, + batch, + state.clock.clone(), + current.observed_at(), + current.expires_at(), + state.active()?, + ) + .await?; + Ok(()) + }) + .await + } + /// Stops admission and observes drained database closure and Web Lock release. + /// Dropping this observation does not cancel the Rust-owned close operation. + pub async fn close(&self) -> Result<(), WorkspaceError> { + self.state.stop(); + if let Some(result) = self.state.closed.get() { + return result; + } + let signal = Rc::new(RefCell::new(None)); + { + let mut waiters = self.state.waiters.borrow_mut(); + waiters.retain(|weak| weak.strong_count() > 0); + if waiters.len() >= WAITERS { + return Err(WorkspaceError::Capacity); + } + waiters.push(Rc::downgrade(&signal)); + } + poll_fn(|cx| { + if let Some(result) = self.state.closed.get() { + Poll::Ready(result) + } else { + *signal.borrow_mut() = Some(cx.waker().clone()); + Poll::Pending + } + }) + .await + } +} +impl fmt::Debug for BrowserWorkspace { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("BrowserWorkspace(<redacted>)") + } +} +impl WorkspaceStore for BrowserWorkspace { + fn authenticate( + &self, + input: AttachmentInput, + proof: AttachmentProof, + ) -> BoxFuture<'_, Result<WorkspaceBinding, WorkspaceError>> { + Box::pin(async move { + let work = self.state.admit()?; + let state = self.state.clone(); + owned(work, async move { + state + .access(&input, &proof) + .await + .map(|(_, _, binding)| binding) + }) + .await + }) + } + fn close_workspace(&self) -> BoxFuture<'_, Result<(), WorkspaceError>> { + Box::pin(self.close()) + } +} diff --git a/crates/storage_indexeddb/tests/browser/Cargo.lock b/crates/storage_indexeddb/tests/browser/Cargo.lock @@ -636,9 +636,12 @@ dependencies = [ "futures", "hex", "js-sys", + "radroots_domain", "radroots_secrets", "radroots_storage", "radroots_storage_indexeddb", + "serde_json", + "sha2", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", @@ -648,8 +651,10 @@ dependencies = [ name = "radroots_protocol" version = "0.1.0-alpha" dependencies = [ + "radroots_domain", "radroots_identity", "serde", + "serde_json", "sha2", "zeroize", ] @@ -681,7 +686,9 @@ dependencies = [ "radroots_trade", "radroots_transport", "serde", + "serde_json", "sha2", + "subtle", "zeroize", ] @@ -691,10 +698,15 @@ version = "0.1.0-alpha" dependencies = [ "futures", "js-sys", + "radroots_domain", + "radroots_secrets", "radroots_storage", + "radroots_transport", + "sha2", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", + "zeroize", ] [[package]] diff --git a/crates/storage_indexeddb/tests/browser/Cargo.toml b/crates/storage_indexeddb/tests/browser/Cargo.toml @@ -11,8 +11,11 @@ rust-version = "1.99.0" crate-type = ["cdylib"] [dependencies] -radroots_storage_indexeddb = { path = "../.." } +radroots_storage_indexeddb = { path = "../..", features = ["workspace"] } radroots_storage = { path = "../../../storage" } +radroots_domain = { path = "../../../domain", features = ["serde", "std"] } +serde_json = "=1.0.149" +sha2 = "=0.10.9" radroots_secrets = { path = "../../../secrets", features = ["memory", "browser"] } futures = "=0.3.32" hex = "=0.4.3" diff --git a/crates/storage_indexeddb/tests/browser/run.mjs b/crates/storage_indexeddb/tests/browser/run.mjs @@ -20,9 +20,11 @@ const server = createServer(async (req,res) => { } if (path.endsWith('/worker.js')) { res.setHeader('content-type','text/javascript'); - res.end(`import init, {Fixture,Persistent,protected_round_trip} from './fixture.js'; + res.end(`import init, {Fixture,Persistent,WorkspaceFixture,protected_round_trip} from './fixture.js'; await init(); + let retainedWorkspace; self.onmessage=async(event)=>{try{ + if(event.data?.kind==='workspace_open'||event.data?.kind==='workspace_hold'){const m=event.data;const owner=await WorkspaceFixture.open(m.n,new Uint8Array(m.fingerprint),new Uint8Array(m.selection),new Uint8Array(m.proof));const revision=await owner.authenticate();if(m.kind==='workspace_hold')retainedWorkspace=owner;else await owner.close();self.postMessage({revision});return;} if(event.data?.kind==='persistent_create'){const provider=await Persistent.create(90);const fingerprint=provider.fingerprint();const encoded=await provider.protect(new Uint8Array([90,91,92]));await provider.close();self.postMessage({fingerprint:Array.from(fingerprint),encoded:Array.from(encoded)});return;} if(event.data?.kind==='persistent_open'){const provider=await Persistent.open(90,new Uint8Array(event.data.fingerprint));const plain=await provider.reveal(new Uint8Array(event.data.encoded));await provider.close();self.postMessage({plain:Array.from(plain)});return;} await protected_round_trip(79);const db=await Fixture.open(77,true);await db.write(1,undefined,new Uint8Array([77]));await db.close();const again=await Fixture.open(77,false);const value=await again.read(1);await again.close();self.postMessage({value:Array.from(value)});}catch(error){self.postMessage({error:String(error)});}}; @@ -43,7 +45,7 @@ try { page.on('console',message=>{if(message.type()==='log')console.log(message.text());}); await page.goto(`http://127.0.0.1:${server.address().port}/index.html`); const result=await page.evaluate(async()=>{ - const {default:init,Fixture,Persistent,protected_round_trip}=await import('./fixture.js'); await init(); + const {default:init,Fixture,Persistent,WorkspaceFixture,protected_round_trip}=await import('./fixture.js'); await init(); console.log('STEP wasm_initialized'); const events=[]; const nativeTransaction=IDBDatabase.prototype.transaction; @@ -93,6 +95,11 @@ try { await rejects(()=>db.atomic_pair(99),'record_conflict'); if(!events.slice(failedBefore).includes('abort'))throw Error('no actual atomic abort'); same(await value(db,1),[1]);same(await value(db,2),[2]); + const refusedAt=events.length; + await rejects(()=>db.refused_pair(),'transaction_precondition_refused'); + same(await value(db,1),[1]);same(await value(db,2),[2]); + if(!events.slice(refusedAt).includes('abort'))throw Error('no actual precondition abort'); + passed('synchronous eligibility refusal aborts the whole real compare/exchange batch'); const nativePut=IDBObjectStore.prototype.put; let firstWriteSucceeded=false; IDBObjectStore.prototype.put=function(...args) { @@ -224,11 +231,60 @@ try { await rejects(()=>Fixture.open(18,false),'missing_namespace');passed('actual namespace deletion cannot silently recreate'); const workerResult=await new Promise((resolve,reject)=>{const worker=new Worker('./worker.js',{type:'module'});worker.onmessage=e=>{if(e.data.ready){worker.postMessage('run');return;}worker.terminate();resolve(e.data);};worker.onerror=e=>{worker.terminate();reject(Error(e.message));};}); same(workerResult,{value:[77]});passed('dedicated worker actual WASM and IndexedDB reopen'); + const outbox=await WorkspaceFixture.create(160); + const workspaceReceipt={n:160,fingerprint:Array.from(outbox.fingerprint()),selection:Array.from(outbox.selection()),proof:Array.from(outbox.proof()),namespace:outbox.data_namespace()}; + same(await outbox.authenticate(),1); + await rejects(()=>outbox.wrong_proof(),'unauthorized');await rejects(()=>outbox.wrong_selection(),'unauthorized'); + await rejects(()=>outbox.contended_open(),'writer_active');same(await outbox.authenticate(),1); + passed('actual protected browser buyer enrollment, authentication and exclusive writer contention'); + const rawWorkspace=receipt=>new Promise((resolve,reject)=>{const r=indexedDB.open(receipt.namespace,1);r.onupgradeneeded=()=>r.transaction.abort();r.onsuccess=()=>resolve(r.result);r.onerror=reject;}); + const workspaceBytes=async receipt=>{const raw=await rawWorkspace(receipt);try{return await new Promise((resolve,reject)=>{const tx=raw.transaction('records','readonly');const store=tx.objectStore('records');let keys,values;store.getAllKeys().onsuccess=e=>keys=e.target.result;store.getAll().onsuccess=e=>values=e.target.result;tx.oncomplete=()=>resolve({keys,values});tx.onabort=reject;});}finally{raw.close();}}; + const changeWorkspace=async(receipt,change)=>{const raw=await rawWorkspace(receipt);try{await new Promise((resolve,reject)=>{const tx=raw.transaction('records','readwrite');change(tx.objectStore('records'));tx.oncomplete=resolve;tx.onabort=reject;});}finally{raw.close();}}; + const originalGrant=await workspaceBytes(workspaceReceipt);same(originalGrant.values.length,1); + outbox.expire_after_next_read();await rejects(()=>outbox.revoke(),'grant_expired');outbox.set_time(1000); + const afterRefusal=await workspaceBytes(workspaceReceipt);same(Array.from(afterRefusal.values[0]),Array.from(originalGrant.values[0]));same(await outbox.authenticate(),1); + outbox.set_time(2000);await rejects(()=>outbox.authenticate(),'grant_expired');outbox.set_time(1000); + passed('actual active write callback refuses expiry after asynchronous wrapping and retains the original grant'); + const workCall=message=>new Promise((resolve,reject)=>{const worker=new Worker('./worker.js',{type:'module'});worker.onmessage=e=>{if(e.data.ready){worker.postMessage(message);return;}worker.terminate();resolve(e.data);};worker.onerror=e=>{worker.terminate();reject(Error(e.message));};}); + same(await workCall({kind:'workspace_open',...workspaceReceipt}),{error:'writer_active'}); + same(outbox.abandon_auths(9),8);for(let n=0;n<64;n++)outbox.abandon_close();await outbox.close(); + await rejects(()=>outbox.authenticate(),'closed'); + same(await workCall({kind:'workspace_open',...workspaceReceipt}),{revision:1}); + passed('bounded owned authentication and cancelled close drain before actual cross-worker writer acquisition'); + let heldWorker; + const held=await new Promise((resolve,reject)=>{heldWorker=new Worker('./worker.js',{type:'module'});heldWorker.onmessage=e=>{if(e.data.ready){heldWorker.postMessage({kind:'workspace_hold',...workspaceReceipt});return;}resolve(e.data);};heldWorker.onerror=e=>reject(Error(e.message));}); + same(held,{revision:1}); + const openReceipt=r=>WorkspaceFixture.open(r.n,new Uint8Array(r.fingerprint),new Uint8Array(r.selection),new Uint8Array(r.proof)); + await rejects(()=>openReceipt(workspaceReceipt),'writer_active');heldWorker.terminate(); + await navigator.locks.request(workspaceReceipt.namespace,()=>{}); + const recoveredWorkspace=await openReceipt(workspaceReceipt);same(await recoveredWorkspace.authenticate(),1);await recoveredWorkspace.close(); + passed('actual worker termination releases writer ownership and the same protected outbox reopens'); + const source=await WorkspaceFixture.create(164);const target=await source.sibling(); + const sourceReceipt={namespace:source.data_namespace()},targetReceipt={namespace:target.data_namespace()}; + const sourceBytes=await workspaceBytes(sourceReceipt),targetBytes=await workspaceBytes(targetReceipt); + await changeWorkspace(targetReceipt,store=>store.put(sourceBytes.values[0],targetBytes.keys[0])); + await rejects(()=>target.authenticate(),'recovery_required');await target.close();await source.close(); + passed('copied protected grants under the same provider cannot cross workspace context'); + const revocable=await WorkspaceFixture.create(166);const revokedReceipt={n:166,fingerprint:Array.from(revocable.fingerprint()),selection:Array.from(revocable.selection()),proof:Array.from(revocable.proof()),namespace:revocable.data_namespace()}; + await revocable.revoke();await rejects(()=>revocable.authenticate(),'grant_revoked');await revocable.close();await rejects(()=>openReceipt(revokedReceipt),'grant_revoked'); + const removed=await WorkspaceFixture.create(167);const removedReceipt={n:167,fingerprint:Array.from(removed.fingerprint()),selection:Array.from(removed.selection()),proof:Array.from(removed.proof()),namespace:removed.data_namespace()};await removed.close(); + await changeWorkspace(removedReceipt,store=>store.clear());await rejects(()=>openReceipt(removedReceipt),'recovery_required'); + await new Promise((resolve,reject)=>{const r=indexedDB.deleteDatabase(removedReceipt.namespace);r.onsuccess=resolve;r.onerror=reject;});await rejects(()=>openReceipt(removedReceipt),'namespace_unavailable'); + passed('revoked, empty and evicted browser workspaces refuse exact reopen without fresh enrollment'); + const displaced=await WorkspaceFixture.create(169);const displacedReceipt={n:169,fingerprint:Array.from(displaced.fingerprint()),selection:Array.from(displaced.selection()),proof:Array.from(displaced.proof()),namespace:displaced.data_namespace()}; + let releaseForeign,foreignAcquired;const foreignHold=new Promise(resolve=>releaseForeign=resolve);const acquiredForeign=new Promise(resolve=>foreignAcquired=resolve); + const foreignLock=navigator.locks.request(displacedReceipt.namespace,{steal:true},()=>{foreignAcquired();return foreignHold;}); + try{await acquiredForeign;await rejects(()=>displaced.authenticate(),'closed');await rejects(()=>displaced.close(),'workspace_unavailable');} + finally{releaseForeign();await foreignLock;} + const afterDisplacement=await openReceipt(displacedReceipt);same(await afterDisplacement.authenticate(),1);await afterDisplacement.close(); + passed('actual unexpected Web Lock loss stops admission and remains visible through owned close'); + await rejects(()=>WorkspaceFixture.create_expiring(168),'grant_expired'); + passed('expired creation exposes no workspace or protected proof'); const workerCall=message=>new Promise((resolve,reject)=>{const worker=new Worker('./worker.js',{type:'module'});worker.onmessage=e=>{if(e.data.ready){worker.postMessage(message);return;}worker.terminate();if(e.data.error)reject(Error(e.data.error));else resolve(e.data);};worker.onerror=e=>{worker.terminate();reject(Error(e.message));};}); const workerCreated=await workerCall({kind:'persistent_create'}); same(await workerCall({kind:'persistent_open',...workerCreated}),{plain:[90,91,92]}); passed('persistent provider survives actual worker termination and new worker instance'); - return {tests,events:events.reduce((all,event)=>(all[event]=(all[event]??0)+1,all),{}),persistent:{fingerprint,encoded}}; + return {tests,events:events.reduce((all,event)=>(all[event]=(all[event]??0)+1,all),{}),persistent:{fingerprint,encoded},workspace:workspaceReceipt}; } finally {IDBDatabase.prototype.transaction=nativeTransaction;} }); await page.reload(); @@ -240,6 +296,8 @@ try { },result.persistent); assert.deepEqual(restarted,[80,81,82]); result.tests.push('persistent provider and encrypted data survive actual page and WASM restart'); + const workspaceRestart=await page.evaluate(async receipt=>{const {default:init,WorkspaceFixture}=await import('./fixture.js');await init();const owner=await WorkspaceFixture.open(receipt.n,new Uint8Array(receipt.fingerprint),new Uint8Array(receipt.selection),new Uint8Array(receipt.proof));const revision=await owner.authenticate();await owner.close();return revision;},result.workspace); + assert.equal(workspaceRestart,1);result.tests.push('authenticated browser workspace survives actual page and WASM restart');delete result.workspace; delete result.persistent; console.log(JSON.stringify({engine,version:browser.version(),...result})); } finally { diff --git a/crates/storage_indexeddb/tests/browser/src/lib.rs b/crates/storage_indexeddb/tests/browser/src/lib.rs @@ -9,6 +9,8 @@ mod protected; pub use protected::protected_round_trip; mod persistent; pub use persistent::Persistent; +mod workspace; +pub use workspace::WorkspaceFixture; fn failure(error: Error) -> JsValue { JsValue::from_str(error.code()) @@ -77,6 +79,21 @@ impl Fixture { .map_err(failure)? .records()) } + pub async fn refused_pair(&self) -> Result<(), JsValue> { + let n = std::cell::Cell::new(0usize); + let entries = vec![ + Mutation::new(key(1), Some(vec![1]), Some(vec![3])).map_err(failure)?, + Mutation::new(key(2), Some(vec![2]), Some(vec![4])).map_err(failure)?, + ]; + self.db + .compare_exchange_checked(Batch::new(entries).map_err(failure)?, move || { + n.set(n.get() + 1); + n.get() == 1 + }) + .await + .map(|_| ()) + .map_err(failure) + } pub fn abandon_write(&self, n: u8) -> Result<(), JsValue> { let result = self .db diff --git a/crates/storage_indexeddb/tests/browser/src/workspace.rs b/crates/storage_indexeddb/tests/browser/src/workspace.rs @@ -0,0 +1,290 @@ +//! Synthetic isolated host-effect fixture, never a production custody API. +use futures::FutureExt; +use radroots_domain::{ActorRole, Coverage, PublicKey, UnixSeconds, WorkspaceId}; +use radroots_secrets::{ + SecretId, SecretRef, + browser::BrowserProvider, + id::{BackendKind, KeyVersion}, + provider::AccessPolicy, +}; +use radroots_storage::{ + event::SourceGeneration, + workspace::{AttachmentInput, AttachmentProof, WorkspaceClock, WorkspaceError, WorkspaceStore}, +}; +use radroots_storage_indexeddb::{ + Namespace, + workspace::{BrowserWorkspace, LocalOutboxConfig}, +}; +use sha2::{Digest, Sha256}; +use std::{cell::Cell, rc::Rc}; +use wasm_bindgen::prelude::*; + +fn fail(e: WorkspaceError) -> JsValue { + JsValue::from_str(e.code()) +} +fn reference() -> SecretRef { + SecretRef::new( + SecretId::parse("workspace_fixture_key").unwrap(), + BackendKind::External, + KeyVersion::new(1).unwrap(), + ) +} +fn key_namespace(n: u8) -> SecretId { + SecretId::parse(format!("workspace_fixture_{n}")).unwrap() +} +fn participant() -> PublicKey { + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() +} +fn copied(proof: &AttachmentProof) -> AttachmentProof { + proof.with_secret(|secret| AttachmentProof::from_protected_input(secret).unwrap()) +} +struct Clock { + now: Cell<u64>, + after: Cell<Option<u64>>, +} +impl Clock { + fn new() -> Self { + Self { + now: Cell::new(1000), + after: Cell::new(None), + } + } +} +impl WorkspaceClock for Clock { + fn now(&self) -> Result<UnixSeconds, WorkspaceError> { + let now = self.now.get(); + if let Some(next) = self.after.take() { + self.now.set(next); + } + if now == 0 { + return Err(WorkspaceError::Unavailable); + } + UnixSeconds::new(now).map_err(|_| WorkspaceError::Unavailable) + } +} +#[wasm_bindgen] +pub struct WorkspaceFixture { + owner: BrowserWorkspace, + provider: Rc<BrowserProvider>, + input: AttachmentInput, + proof: AttachmentProof, + clock: Rc<Clock>, +} +#[wasm_bindgen] +impl WorkspaceFixture { + pub async fn sibling(&self) -> Result<Self, JsValue> { + let clock = Rc::new(Clock::new()); + let config = LocalOutboxConfig::new( + participant(), + participant(), + "synthetic-browser", + UnixSeconds::new(2000).unwrap(), + ) + .map_err(fail)?; + let (owner, input, proof) = BrowserWorkspace::initialize_local_outbox( + config, + self.provider.clone(), + reference(), + AccessPolicy::standard(), + clock.clone(), + ) + .await + .map_err(fail)?; + Ok(Self { + owner, + provider: self.provider.clone(), + input, + proof, + clock, + }) + } + pub async fn create(n: u8) -> Result<Self, JsValue> { + Self::initialize(n, false).await + } + pub async fn create_expiring(n: u8) -> Result<(), JsValue> { + let owner = Self::initialize(n, true).await?; + owner.close().await + } + pub async fn open( + n: u8, + fingerprint: Vec<u8>, + selection: Vec<u8>, + proof: Vec<u8>, + ) -> Result<Self, JsValue> { + if selection.len() > 16 * 1024 { + return Err(JsValue::from_str("oversized_selection")); + } + let input: AttachmentInput = serde_json::from_slice(&selection) + .map_err(|_| JsValue::from_str("invalid_selection"))?; + let proof = AttachmentProof::from_protected_input(&proof).map_err(fail)?; + let fingerprint = fingerprint + .as_slice() + .try_into() + .map_err(|_| JsValue::from_str("invalid_fingerprint"))?; + let provider = Rc::new( + BrowserProvider::open(key_namespace(n), reference(), fingerprint) + .await + .map_err(|e| JsValue::from_str(e.code()))?, + ); + let clock = Rc::new(Clock::new()); + let owner = BrowserWorkspace::open_existing( + input.clone(), + copied(&proof), + provider.clone(), + reference(), + AccessPolicy::standard(), + clock.clone(), + ) + .await + .map_err(fail)?; + Ok(Self { + owner, + provider, + input, + proof, + clock, + }) + } + pub fn selection(&self) -> Vec<u8> { + serde_json::to_vec(&self.input).unwrap() + } + pub fn proof(&self) -> Vec<u8> { + self.proof.with_secret(|bytes| bytes.to_vec()) + } + pub fn fingerprint(&self) -> Vec<u8> { + self.provider.fingerprint().to_vec() + } + pub fn data_namespace(&self) -> String { + let mut h = Sha256::new(); + h.update(b"radroots.browser.local_outbox.namespace.v1\0"); + h.update(self.input.workspace_id().as_bytes()); + Namespace::new(SourceGeneration::new(h.finalize().into()).unwrap()).name() + } + pub fn set_time(&self, now: u32) { + self.clock.now.set(now as u64); + } + pub fn expire_after_next_read(&self) { + self.clock.after.set(Some(2000)); + } + pub async fn authenticate(&self) -> Result<u32, JsValue> { + let bound = self + .owner + .authenticate(self.input.clone(), copied(&self.proof)) + .await + .map_err(fail)?; + assert_eq!(bound.actor().role(), ActorRole::Buyer); + assert_eq!(bound.actor().organization(), None); + assert_eq!(bound.input(), &self.input); + assert_eq!(bound.actor().grant_id(), Some(self.input.grant_id())); + assert_eq!(bound.input().checkpoint().coverage(), Coverage::Partial); + Ok(bound.grant_revision().get() as u32) + } + pub async fn wrong_proof(&self) -> Result<(), JsValue> { + self.owner + .authenticate( + self.input.clone(), + AttachmentProof::from_protected_input(&[0x31; 32]).unwrap(), + ) + .await + .map(|_| ()) + .map_err(fail) + } + pub async fn wrong_selection(&self) -> Result<(), JsValue> { + let wrong = AttachmentInput::new( + WorkspaceId::from_bytes([3; 32]), + self.input.authority(), + self.input.participant(), + self.input.endpoint(), + self.input.endpoint_identity(), + self.input.grant_id(), + self.input.checkpoint().clone(), + self.input.route_digest(), + ) + .unwrap(); + self.owner + .authenticate(wrong, copied(&self.proof)) + .await + .map(|_| ()) + .map_err(fail) + } + pub async fn contended_open(&self) -> Result<(), JsValue> { + let owner = BrowserWorkspace::open_existing( + self.input.clone(), + copied(&self.proof), + self.provider.clone(), + reference(), + AccessPolicy::standard(), + self.clock.clone(), + ) + .await + .map_err(fail)?; + owner.close().await.map_err(fail) + } + pub async fn revoke(&self) -> Result<(), JsValue> { + self.owner + .revoke(self.input.clone(), copied(&self.proof)) + .await + .map_err(fail) + } + pub fn abandon_auths(&self, count: u32) -> Result<u32, JsValue> { + for n in 0..count { + if let Some(result) = self + .owner + .authenticate(self.input.clone(), copied(&self.proof)) + .now_or_never() + { + return if matches!(result, Err(WorkspaceError::Capacity)) { + Ok(n) + } else { + Err(JsValue::from_str("unexpected_immediate_auth")) + }; + } + } + Ok(count) + } + pub fn abandon_close(&self) -> Result<(), JsValue> { + if self.owner.close().now_or_never().is_some() { + return Err(JsValue::from_str("unexpected_immediate_workspace_close")); + } + Ok(()) + } + pub async fn close(&self) -> Result<(), JsValue> { + self.owner.close().await.map_err(fail) + } +} +impl WorkspaceFixture { + async fn initialize(n: u8, expire: bool) -> Result<Self, JsValue> { + let provider = Rc::new( + BrowserProvider::create(key_namespace(n), reference()) + .await + .map_err(|e| JsValue::from_str(e.code()))?, + ); + let clock = Rc::new(Clock::new()); + if expire { + clock.after.set(Some(2000)); + } + let config = LocalOutboxConfig::new( + participant(), + participant(), + "synthetic-browser", + UnixSeconds::new(2000).unwrap(), + ) + .map_err(fail)?; + let (owner, input, proof) = BrowserWorkspace::initialize_local_outbox( + config, + provider.clone(), + reference(), + AccessPolicy::standard(), + clock.clone(), + ) + .await + .map_err(fail)?; + Ok(Self { + owner, + provider, + input, + proof, + clock, + }) + } +} diff --git a/crates/storage_sqlite/Cargo.toml b/crates/storage_sqlite/Cargo.toml @@ -46,6 +46,7 @@ radroots_secrets = { workspace = true, default-features = false } radroots_storage = { workspace = true, default-features = false, features = [ "serde", "command_journal", + "protected_outbox", ] } radroots_transport = { workspace = true, default-features = false, features = [ "serde", diff --git a/crates/storage_sqlite/src/workspace/crypto.rs b/crates/storage_sqlite/src/workspace/crypto.rs @@ -7,6 +7,9 @@ use radroots_secrets::{ provider::{AccessPolicy, ResidencySupport, SecretProvider, SelectionPolicy}, wrapping::SecretMaterial, }; +use radroots_storage::workspace::local_outbox::{ + GRANT_ENVELOPE_PURPOSE, GRANT_PAYLOAD_SCHEMA, grant_envelope_subject, +}; use std::{fmt, sync::Arc}; pub(super) const PRIVATE_PAYLOAD_MAX_BYTES: usize = 16 * 1024; @@ -345,12 +348,10 @@ fn context(workspace: WorkspaceId, grant: GrantId) -> Result<EnvelopeContext, Wo // 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") + EnvelopePurpose::parse(GRANT_ENVELOPE_PURPOSE).map_err(|_| WorkspaceError::InvalidInput)?, + EnvelopeSubject::parse("workspace_grant", grant_envelope_subject(workspace, grant)) .map_err(|_| WorkspaceError::InvalidInput)?, + PayloadSchemaId::parse(GRANT_PAYLOAD_SCHEMA).map_err(|_| WorkspaceError::InvalidInput)?, )) } diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs @@ -28,53 +28,12 @@ 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_domain::{ExecutorId, GrantId, PublicKey, 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>)") - } -} +pub use radroots_storage::workspace::local_outbox::LocalOutboxConfig; /// One native local-outbox connection, with an owned bounded request worker. /// Clones refer to the same admission, writer authority and close completion. @@ -93,60 +52,15 @@ impl NativeWorkspace { 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, - )?; + config.validate_at(now)?; 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 (input, proof, record) = config.enroll( + now, + WorkspaceId::from_bytes(random()?), + ExecutorId::from_bytes(random()?), + GrantId::from_bytes(random()?), + proof, )?; let worker = worker::Handle::launch( path.to_path_buf(), diff --git a/crates/storage_sqlite/src/workspace/record.rs b/crates/storage_sqlite/src/workspace/record.rs @@ -1,155 +1 @@ -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> { - self.authenticate_retained_capture(input, proof)?; - 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, - ) - } - /// Checks only the original protected credential and exact namespace scope. - /// This path is exclusively for appending a matching already obtained - /// artifact to an actual existing claim, never for new issuance or reads. - pub(super) fn authenticate_retained_capture( - &self, - input: &AttachmentInput, - proof: &AttachmentProof, - ) -> Result<(), 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); - } - self.validate() - } - 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() -} +pub(super) use radroots_storage::workspace::local_outbox::LocalOutboxGrant as GrantRecord; diff --git a/crates/storage_sqlite/src/workspace/tests/mod.rs b/crates/storage_sqlite/src/workspace/tests/mod.rs @@ -1,4 +1,8 @@ use super::*; +use radroots_domain::{ + ActorRole, AuthorityRef, CheckpointDigest, CheckpointRef, Coverage, Generation, RouteDigest, + Sequence, UnixSeconds, +}; pub(super) mod issuance_records; mod operation_records; mod plan_records; @@ -531,7 +535,7 @@ async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_r use sqlx::Connection; let fixture = CryptoFixture::new(); let base = fixture._temp.path().canonicalize().unwrap(); - for fault in 0..7 { + for fault in 0..9 { let path = base.join(format!("corrupt-{fault}")); let (store, input, proof) = NativeWorkspace::initialize_local_outbox( &path, @@ -557,6 +561,21 @@ async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_r .execute(&mut connection) .await .unwrap(); + let retained_protected: Option<Vec<u8>> = if fault >= 7 { + Some( + sqlx::query_scalar("SELECT protected FROM workspace_grant") + .fetch_one(&mut connection) + .await + .unwrap(), + ) + } else { + None + }; + let expected_error = if fault >= 7 { + WorkspaceError::WrongNamespace + } else { + WorkspaceError::RecoveryRequired + }; let statement = match fault { 0 => "PRAGMA user_version=8", 1 => "DELETE FROM workspace_grant", @@ -565,6 +584,8 @@ async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_r 4 => "UPDATE workspace_grant SET protected=zeroblob(262145)", 5 => "UPDATE workspace_grant SET protected=zeroblob(262144)", 6 => "UPDATE workspace_grant SET workspace=zeroblob(31)", + 7 => "UPDATE workspace_grant SET workspace=zeroblob(32)", + 8 => "UPDATE workspace_grant SET grant_id=zeroblob(32)", _ => unreachable!(), }; sqlx::query(statement) @@ -573,11 +594,9 @@ async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_r .unwrap(); connection.close().await.unwrap(); if fault != 0 { - assert!( - matches!( - store.authenticate(input.clone(), &proof).await, - Err(WorkspaceError::RecoveryRequired) - ), + assert_eq!( + store.authenticate(input.clone(), &proof).await.err(), + Some(expected_error), "live fault {fault}" ); } @@ -590,7 +609,7 @@ async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_r ) .await; assert!( - matches!(&result, Err(WorkspaceError::RecoveryRequired)), + matches!(&result, Err(error) if *error == expected_error), "fault {fault}: {result:?}" ); let mut connection = sqlx::SqliteConnection::connect_with(&options.clone().read_only(true)) @@ -606,6 +625,16 @@ async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_r .unwrap(); assert_eq!(version, if fault == 0 { 8 } else { 7 }); assert_eq!(rows, if fault == 1 { 0 } else { 1 }); + if let Some(expected) = retained_protected { + let actual: Vec<u8> = sqlx::query_scalar("SELECT protected FROM workspace_grant") + .fetch_one(&mut connection) + .await + .unwrap(); + assert_eq!( + actual, expected, + "foreign row must retain its original ciphertext" + ); + } if (3..=5).contains(&fault) { let size: i64 = sqlx::query_scalar("SELECT length(protected) FROM workspace_grant") .fetch_one(&mut connection) diff --git a/crates/storage_sqlite/src/workspace/tests/plan_records.rs b/crates/storage_sqlite/src/workspace/tests/plan_records.rs @@ -11,6 +11,14 @@ use radroots_storage::command::{ }; use serde_json::{Value, json}; use sqlx::{Connection, SqliteConnection}; +use std::sync::atomic::{AtomicU64, Ordering}; + +struct MutableClock(AtomicU64); +impl WorkspaceClock for MutableClock { + fn now(&self) -> Result<UnixSeconds, WorkspaceError> { + UnixSeconds::new(self.0.load(Ordering::SeqCst)).map_err(|_| WorkspaceError::Unavailable) + } +} #[tokio::test] async fn authenticated_plan_manifest_parts_and_transaction_comparisons_refuse_each_inconsistency() { @@ -21,6 +29,7 @@ async fn authenticated_plan_manifest_parts_and_transaction_comparisons_refuse_ea .canonicalize() .unwrap() .join("plan-records"); + let clock = Arc::new(MutableClock(AtomicU64::new(100))); let (store, selected, proof) = NativeWorkspace::initialize_local_outbox( &path, LocalOutboxConfig::new( @@ -31,7 +40,7 @@ async fn authenticated_plan_manifest_parts_and_transaction_comparisons_refuse_ea ) .unwrap(), fixture.crypto(), - Arc::new(FixedClock(100)), + clock.clone(), ) .await .unwrap(); @@ -107,6 +116,7 @@ async fn authenticated_plan_manifest_parts_and_transaction_comparisons_refuse_ea .unwrap(); let digest = *plan.digest(); let original_wire = plan.protected_wire().to_vec(); + let rollback_plan = ChatSigningPlan::parse(&command, &original_wire).unwrap(); let copied = || proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes).unwrap()); assert!(matches!( @@ -119,6 +129,30 @@ async fn authenticated_plan_manifest_parts_and_transaction_comparisons_refuse_ea .unwrap(), AdmissionOutcome::Committed(_) )); + clock.0.store(90, Ordering::SeqCst); + assert!(matches!( + store + .bind_signing_intents(binding.clone(), rollback_plan, copied()) + .await, + Err(radroots_storage::command::OperationError::Workspace( + WorkspaceError::Unavailable + )) + )); + let mut unchanged = SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .filename(path.join("execution_v1.sqlite")) + .create_if_missing(false) + .read_only(true), + ) + .await + .unwrap(); + let plans: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_plans") + .fetch_one(&mut unchanged) + .await + .unwrap(); + assert_eq!(plans, 0, "clock rollback cannot install a signing plan"); + unchanged.close().await.unwrap(); + clock.0.store(100, Ordering::SeqCst); assert!(matches!( store .bind_signing_intents(binding, plan, copied())