lib

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

commit c8b656e4241ea959fa96001cecd53dab3336e8db
parent 51e65ed095b46ce7e717a08ecda9fd7de5b77778
Author: triesap <tyson@radroots.org>
Date:   Mon, 19 Oct 2026 00:21:11 +0000

storage: Retain authenticated browser operation preparation

- Share the immutable native and browser Prepared codec and scope checks.
- Commit bounded protected multipart T0 with exact replay and proof.
- Preserve uncertain original attempts and owned work through close.
- Verify native regressions, browser faults, APIs and unchanged gates.

Diffstat:
Mcontracts/api_baselines/radroots_storage.txt | 6++++++
Mcontracts/api_baselines/radroots_storage_indexeddb.wasm32_workspace.txt | 3+++
Mcontracts/architecture/decisions/browser_workspace.v1.json | 30+++++++++++++++++++++++++++++-
Mcrates/storage/README.md | 5+++++
Mcrates/storage/src/command.rs | 3+++
Acrates/storage/src/command/protected.rs | 303+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_indexeddb/README.md | 13+++++++++++++
Mcrates/storage_indexeddb/src/workspace/crypto.rs | 20++++++++++++++++++--
Acrates/storage_indexeddb/src/workspace/journal.rs | 400+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_indexeddb/src/workspace/mod.rs | 46+++++++++++++++++++++++++++++++++++-----------
Mcrates/storage_indexeddb/tests/browser/run.mjs | 98++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcrates/storage_indexeddb/tests/browser/src/workspace.rs | 159++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcrates/storage_sqlite/src/workspace/admission.rs | 15+--------------
Mcrates/storage_sqlite/src/workspace/operation.rs | 139++++++++++---------------------------------------------------------------------
14 files changed, 1088 insertions(+), 152 deletions(-)

diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -758,6 +758,12 @@ pub fn radroots_storage::memory::MemoryStorage::transition_restore(&self, radroo pub fn radroots_storage::memory::MemoryStorage::verify_backup(&self, radroots_storage::backup::BackupPlan, radroots_storage::backup::BackupManifest) -> radroots_transport::source::BoxFuture<'_, core::result::Result<(), radroots_storage::backup::BackupCapabilityError>> pub mod radroots_storage::command pub use radroots_storage::command::ChatSigningPlan +pub mod radroots_storage::command::protected +pub const radroots_storage::command::protected::PREPARED_BYTES_MAX: usize +pub fn radroots_storage::command::protected::check_digest(&radroots_storage::command::PreparedOperation, radroots_domain::context::ActorRef, core::option::Option<radroots_domain::identifier::CommandDigest>) -> core::result::Result<(), radroots_storage::command::OperationError> +pub fn radroots_storage::command::protected::decode(&[u8], &radroots_storage::workspace::AttachmentInput, radroots_domain::identifier::OperationId) -> core::result::Result<radroots_storage::command::PreparedOperation, radroots_storage::command::OperationError> +pub fn radroots_storage::command::protected::encode(&radroots_storage::command::AdmissionRequest, radroots_domain::identifier::TransactionId, radroots_domain::issuance::IssuanceWindow) -> core::result::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>, radroots_storage::command::OperationError> +pub fn radroots_storage::command::protected::same_binding(&radroots_storage::workspace::WorkspaceBinding, &radroots_storage::workspace::WorkspaceBinding) -> core::result::Result<(), radroots_storage::command::OperationError> pub enum radroots_storage::command::AdmissionOutcome pub radroots_storage::command::AdmissionOutcome::Committed(radroots_storage::command::PreparedOperation) pub radroots_storage::command::AdmissionOutcome::Unknown(radroots_storage::command::CommitAttempt) diff --git a/contracts/api_baselines/radroots_storage_indexeddb.wasm32_workspace.txt b/contracts/api_baselines/radroots_storage_indexeddb.wasm32_workspace.txt @@ -3,6 +3,9 @@ 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::admit_command_and_hold(&self, radroots_storage::command::AdmissionRequest, radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage::command::AdmissionOutcome, radroots_storage::command::OperationError> +pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::query_operation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage::command::PreparedOperation>, radroots_storage::command::OperationError> +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> diff --git a/contracts/architecture/decisions/browser_workspace.v1.json b/contracts/architecture/decisions/browser_workspace.v1.json @@ -1,7 +1,7 @@ { "schema_version": 1, "contract_id": "radroots.storage.browser_workspace.v1", - "state": "implemented_workspace_component", + "state": "implemented_admission_component", "owner": "radroots_storage_indexeddb", "feature": "workspace", "target": "wasm32-unknown-unknown", @@ -61,5 +61,33 @@ "actual_worker_termination_and_page_restart_required": true, "native_workspace_and_ordinary_inquiry_regressions_required": true, "final_phone_or_full_rcld_claim": false + }, + "shared_prepared_codec": "radroots_storage::command::protected", + "operation_admission": { + "phase": "T0_only", + "original_identity_and_window_retained": true, + "exact_replay_before_fresh_deadline_or_entropy": true, + "same_id_different_digest_refused": true, + "private_record_clear_bytes_max": 16384, + "complete_preparation_clear_bytes_max": 65536, + "manifest_clear_bytes": 40, + "part_count_max": 4, + "fixed_slots_compared_atomically": 5, + "grant_compared_in_same_transaction": true, + "part_context_binds": [ + "workspace", + "operation", + "position", + "complete_preparation_digest" + ], + "active_callback_checks": [ + "writer_lease", + "current_grant_and_proof", + "monotonic_positive_clock", + "fresh_first_issue_deadline" + ], + "unknown_completion": "retain_original_attempt_stop_admission_exact_reopen", + "orphan_or_corrupt_replacement_allowed": false, + "participant_issuance_installation_or_delivery": false } } diff --git a/crates/storage/README.md b/crates/storage/README.md @@ -86,6 +86,11 @@ 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. +Its `command::protected` module supplies the shared native/browser immutable +Prepared codec and pure binding/commitment checks. The complete codec is bounded +to 64 KiB; a concrete host must split it to meet any smaller private-record +budget, protect each record and atomically retain the full set. Decoding is a +historical observation and supplies no current grant, actual commit or issuance. `BackupSource::settle_backup_writes` waits for earlier owner writes, including work whose caller was cancelled. The host excludes new writes before settling diff --git a/crates/storage/src/command.rs b/crates/storage/src/command.rs @@ -11,6 +11,9 @@ pub use radroots_protocol::chat::ChatSigningPlan; use radroots_protocol::command::CapturedChatCommand; use radroots_transport::BoxFuture; +#[cfg(feature = "protected_outbox")] +pub mod protected; + mod delivery; mod delivery_summary; mod dm_source; diff --git a/crates/storage/src/command/protected.rs b/crates/storage/src/command/protected.rs @@ -0,0 +1,303 @@ +//! Bounded protected Prepared representation and pure scope checks shared by +//! concrete transaction hosts. Decoding supplies no current access or commit. +use super::{AdmissionRequest, OperationError, PreparedOperation}; +use crate::workspace::{AttachmentInput, WorkspaceBinding}; +use radroots_domain::{ + CommandDigest, IssuanceWindow, OperationId, Sequence, TransactionId, UnixSeconds, +}; +use serde::{Deserialize, Serialize}; +use zeroize::Zeroizing; + +/// Maximum complete preparation, before a host splits private records. +pub const PREPARED_BYTES_MAX: usize = 65_536; + +#[derive(Serialize)] +struct Encoded<'a> { + version: u8, + selection: &'a AttachmentInput, + principal: &'a str, + grant_revision: Sequence, + grant_expires_at: UnixSeconds, + captured_observed_at: UnixSeconds, + transaction_id: TransactionId, + revision: Sequence, + prepared_at: UnixSeconds, + first_issue_not_after: UnixSeconds, + command: &'a serde_json::value::RawValue, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Decoded<'a> { + version: u8, + selection: AttachmentInput, + principal: String, + grant_revision: Sequence, + grant_expires_at: UnixSeconds, + captured_observed_at: UnixSeconds, + transaction_id: TransactionId, + revision: Sequence, + prepared_at: UnixSeconds, + first_issue_not_after: UnixSeconds, + #[serde(borrow)] + command: &'a serde_json::value::RawValue, +} + +/// Encodes the original immutable preparation before encryption. A host must +/// independently commit it and enforce its smaller private record limit. +pub fn encode( + request: &AdmissionRequest, + transaction_id: TransactionId, + window: IssuanceWindow, +) -> Result<Zeroizing<Vec<u8>>, OperationError> { + let binding = request.binding(); + let encoded = Encoded { + version: 2, + selection: binding.input(), + principal: binding.principal_id(), + grant_revision: binding.grant_revision(), + grant_expires_at: binding.expires_at(), + captured_observed_at: binding.observed_at(), + transaction_id, + revision: Sequence::new(1).map_err(|_| OperationError::RecoveryRequired)?, + prepared_at: window.prepared_at(), + first_issue_not_after: window.first_issue_not_after(), + command: serde_json::from_slice(request.command().protected_wire()) + .map_err(|_| OperationError::InvalidCommand)?, + }; + let plaintext = + Zeroizing::new(serde_json::to_vec(&encoded).map_err(|_| OperationError::InvalidCommand)?); + if plaintext.len() > PREPARED_BYTES_MAX { + return Err(OperationError::InvalidCommand); + } + Ok(plaintext) +} + +/// Validates bounded decrypted retained bytes against the independently selected +/// namespace/operation. This is a historical observation, never current authority. +pub fn decode( + bytes: &[u8], + selected: &AttachmentInput, + operation_id: OperationId, +) -> Result<PreparedOperation, OperationError> { + if bytes.len() > PREPARED_BYTES_MAX { + return Err(OperationError::RecoveryRequired); + } + let decoded: Decoded<'_> = + serde_json::from_slice(bytes).map_err(|_| OperationError::RecoveryRequired)?; + if decoded.version != 2 || decoded.revision.get() != 1 { + return Err(OperationError::RecoveryRequired); + } + let command_context: radroots_domain::CommandContextData = { + #[derive(Deserialize)] + struct ContextOnly { + context: radroots_domain::CommandContextData, + } + serde_json::from_str::<ContextOnly>(decoded.command.get()) + .map_err(|_| OperationError::RecoveryRequired)? + .context + }; + let binding = WorkspaceBinding::from_authenticated_host( + decoded.selection, + command_context.actor(), + decoded.principal, + decoded.grant_revision, + decoded.grant_expires_at, + decoded.captured_observed_at, + )?; + if binding.input() != selected { + return Err(OperationError::RecoveryRequired); + } + let request = AdmissionRequest::from_protected_wire(binding, decoded.command.get().as_bytes())?; + let context = request.command().context(); + if context.workspace_id() != selected.workspace_id() || context.operation_id() != operation_id { + return Err(OperationError::RecoveryRequired); + } + let snapshot = PreparedOperation::from_committed_store( + request, + decoded.transaction_id, + decoded.revision, + IssuanceWindow::new(decoded.prepared_at, decoded.first_issue_not_after) + .map_err(|_| OperationError::RecoveryRequired)?, + )?; + Ok::<_, OperationError>(snapshot) +} + +/// Checks the actor and optional exact original commitment without fresh issuance. +pub fn check_digest( + snapshot: &PreparedOperation, + actor: radroots_domain::ActorRef, + expected: Option<CommandDigest>, +) -> Result<(), OperationError> { + if snapshot.request().command().context().actor().participant() != actor.participant() { + return Err(OperationError::Unauthorized); + } + if expected.is_some_and(|digest| digest != snapshot.request().command().digest()) { + return Err(OperationError::IdempotencyConflict); + } + Ok(()) +} + +/// Compares the retained scope and current grant revision; observation times may differ. +pub fn same_binding( + captured: &WorkspaceBinding, + current: &WorkspaceBinding, +) -> Result<(), OperationError> { + if captured.input() != current.input() + || captured.actor() != current.actor() + || captured.principal_id() != current.principal_id() + || captured.grant_revision() != current.grant_revision() + || captured.expires_at() != current.expires_at() + { + return Err(OperationError::Unauthorized); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::workspace::{AttachmentProof, local_outbox::LocalOutboxConfig}; + use radroots_domain::{CommandContextData, ExecutorId, GrantId, PublicKey, WorkspaceId}; + use serde_json::json; + + fn request() -> AdmissionRequest { + let participant = + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798") + .unwrap(); + let now = UnixSeconds::new(100).unwrap(); + let (input, proof, grant) = LocalOutboxConfig::new( + participant, + participant, + "synthetic-codec", + UnixSeconds::new(200).unwrap(), + ) + .unwrap() + .enroll( + now, + WorkspaceId::from_bytes([1; 32]), + ExecutorId::from_bytes([2; 32]), + GrantId::from_bytes([3; 32]), + AttachmentProof::from_protected_input(&[4; 32]).unwrap(), + ) + .unwrap(); + let binding = grant.authenticate(&input, &proof, now).unwrap(); + let context = CommandContextData::new( + OperationId::from_bytes([5; 32]), + binding.actor(), + input.workspace_id(), + input.authority(), + input.route_digest(), + None, + None, + UnixSeconds::new(150).unwrap(), + None, + ) + .unwrap(); + let wire = serde_json::to_vec(&json!({"type":"inbox.inquire","context":context, + "input":{"thread_id":"66".repeat(32),"peer":participant,"source":null,"text":"synthetic retained preparation"}})).unwrap(); + AdmissionRequest::from_protected_wire(binding, &wire).unwrap() + } + #[test] + fn original_preparation_round_trip_and_scope_are_checked_without_current_authority() { + let request = request(); + let operation = request.command().context().operation_id(); + let transaction = TransactionId::from_bytes([7; 32]); + let window = IssuanceWindow::capture( + UnixSeconds::new(100).unwrap(), + UnixSeconds::new(150).unwrap(), + ) + .unwrap(); + let bytes = encode(&request, transaction, window).unwrap(); + let decoded = decode(&bytes, request.binding().input(), operation).unwrap(); + assert_eq!(decoded.transaction_id(), transaction); + assert_eq!(decoded.issuance_window(), window); + assert_eq!( + decoded.request().command().protected_wire(), + request.command().protected_wire() + ); + assert!(same_binding(request.binding(), decoded.request().binding()).is_ok()); + assert!(check_digest(&decoded, request.binding().actor(), None).is_ok()); + assert!( + check_digest( + &decoded, + request.binding().actor(), + Some(request.command().digest()) + ) + .is_ok() + ); + assert_eq!( + check_digest( + &decoded, + request.binding().actor(), + Some(CommandDigest::from_bytes([8; 32])) + ), + Err(OperationError::IdempotencyConflict) + ); + assert!( + decode( + &bytes, + request.binding().input(), + OperationId::from_bytes([9; 32]) + ) + .is_err() + ); + assert!( + decode( + &vec![0; PREPARED_BYTES_MAX + 1], + request.binding().input(), + operation + ) + .is_err() + ); + assert!(decode(b"{}", request.binding().input(), operation).is_err()); + let original: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + for (pointer, value) in [ + ("/version", json!(1)), + ("/revision", json!("0")), + ("/revision", json!("2")), + ("/selection/workspace_id", json!("88".repeat(32))), + ("/principal", json!("")), + ("/prepared_at", json!("0")), + ("/prepared_at", json!("99")), + ("/first_issue_not_after", json!("100")), + ("/first_issue_not_after", json!("151")), + ("/command/type", json!("unknown")), + ("/command/context", json!({})), + ] { + let mut damaged = original.clone(); + *damaged.pointer_mut(pointer).unwrap() = value; + let wire = serde_json::to_vec(&damaged).unwrap(); + assert!( + decode(&wire, request.binding().input(), operation).is_err(), + "{pointer}" + ); + } + let binding = request.binding(); + let other = WorkspaceBinding::from_authenticated_host( + binding.input().clone(), + binding.actor(), + "foreign-principal", + binding.grant_revision(), + binding.expires_at(), + binding.observed_at(), + ) + .unwrap(); + assert_eq!( + same_binding(binding, &other), + Err(OperationError::Unauthorized) + ); + let foreign = + PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5") + .unwrap(); + let actor = radroots_domain::ActorRef::new( + foreign, + binding.actor().role(), + None, + binding.actor().grant_id(), + ); + assert_eq!( + check_digest(&decoded, actor, None), + Err(OperationError::Unauthorized) + ); + } +} diff --git a/crates/storage_indexeddb/README.md b/crates/storage_indexeddb/README.md @@ -19,6 +19,19 @@ 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 also executes immutable buyer operation admission and lookup. +It retains the original command, transaction identity and first-issue window; +an exact replay returns that preparation before acquiring entropy or applying +a fresh command deadline. A different command under the same ID refuses. +Preparation uses the shared native codec, split into at most four 16 KiB clear +parts and an authenticated manifest. Each part binds its workspace, operation, +position and full preparation digest. The grant comparison and all record slots +commit atomically, with current access, writer and fresh deadline checks inside +active callbacks. Unknown completion retains the original attempt and stops +admission until exact reopening. Queries compare the complete fixed record set; +missing, orphaned or damaged parts never trigger replacement. These methods +provide T0 only; they do not implement signing, installation or delivery. + 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 diff --git a/crates/storage_indexeddb/src/workspace/crypto.rs b/crates/storage_indexeddb/src/workspace/crypto.rs @@ -41,6 +41,14 @@ pub(super) async fn seal( grant: GrantId, plaintext: &[u8], ) -> Result<Vec<u8>, WorkspaceError> { + seal_bound(provider, reference, context(workspace, grant)?, plaintext).await +} +pub(super) async fn seal_bound( + provider: &dyn SecretProvider, + reference: &SecretRef, + context: EnvelopeContext, + plaintext: &[u8], +) -> Result<Vec<u8>, WorkspaceError> { if plaintext.len() > GRANT_BYTES_MAX { return Err(WorkspaceError::InvalidInput); } @@ -58,7 +66,7 @@ pub(super) async fn seal( reference.backend(), reference.key_version(), ), - context(workspace, grant)?, + context, &plaintext, SealMaterial::new(material, Nonce::new(*nonce)), ), @@ -79,6 +87,14 @@ pub(super) async fn open( grant: GrantId, protected: &[u8], ) -> Result<SecretMaterial, WorkspaceError> { + open_bound(provider, reference, context(workspace, grant)?, protected).await +} +pub(super) async fn open_bound( + provider: &dyn SecretProvider, + reference: &SecretRef, + context: EnvelopeContext, + protected: &[u8], +) -> Result<SecretMaterial, WorkspaceError> { if protected.len() > PROTECTED_MAX { return Err(WorkspaceError::RecoveryRequired); } @@ -91,7 +107,7 @@ pub(super) async fn open( return Err(WorkspaceError::RecoveryRequired); } let plaintext = envelope - .open(provider, &context(workspace, grant)?) + .open(provider, &context) .await .map_err(|_| WorkspaceError::RecoveryRequired)?; if plaintext.len() > GRANT_BYTES_MAX { diff --git a/crates/storage_indexeddb/src/workspace/journal.rs b/crates/storage_indexeddb/src/workspace/journal.rs @@ -0,0 +1,400 @@ +//! Protected immutable T0 records. No signer, network or business installation. +use super::{ + Batch, BrowserWorkspace, Error, Mutation, RecordKey, State, WorkspaceError, crypto, grant_key, + owned, +}; +use radroots_domain::{CommandDigest, IssuanceWindow, OperationId, Sequence, TransactionId}; +use radroots_secrets::context::{ + EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId, +}; +use radroots_storage::{ + command::{ + AdmissionOutcome, AdmissionRequest, CommitAttempt, OperationError, PreparedOperation, + protected, + }, + workspace::{AttachmentProof, WorkspaceBinding, local_outbox::LocalOutboxGrant}, +}; +use sha2::{Digest, Sha256}; +use std::{cell::Cell, rc::Rc}; +use zeroize::Zeroizing; + +const PART_BYTES: usize = 16 * 1024; +const PARTS: usize = protected::PREPARED_BYTES_MAX / PART_BYTES; +const SLOTS: usize = PARTS + 1; +type Records = Vec<Option<Vec<u8>>>; + +fn key(operation: OperationId, slot: usize) -> RecordKey { + let mut h = Sha256::new(); + h.update(b"radroots.browser.local_outbox.prepared.key.v1\0"); + h.update(operation.as_bytes()); + h.update((slot as u32).to_be_bytes()); + RecordKey::new(h.finalize().into()) +} +fn context( + state: &State, + operation: OperationId, + part: Option<(usize, &[u8])>, +) -> Result<EnvelopeContext, WorkspaceError> { + let mut h = Sha256::new(); + h.update(b"radroots.browser.local_outbox.prepared.context.v1\0"); + h.update(state.selected.workspace_id().as_bytes()); + h.update(operation.as_bytes()); + if let Some((index, digest)) = part { + h.update(b"part\0"); + h.update((index as u32).to_be_bytes()); + h.update(digest); + } else { + h.update(b"manifest\0"); + } + let subject = h + .finalize() + .iter() + .map(|b| format!("{b:02x}")) + .collect::<String>(); + Ok(EnvelopeContext::new( + EnvelopePurpose::parse("radroots.browser.workspace.prepared") + .map_err(|_| WorkspaceError::InvalidInput)?, + EnvelopeSubject::parse("workspace_prepared", subject) + .map_err(|_| WorkspaceError::InvalidInput)?, + PayloadSchemaId::parse("radroots.browser.workspace.prepared.v1") + .map_err(|_| WorkspaceError::InvalidInput)?, + )) +} +impl State { + async fn operation_records(&self, operation: OperationId) -> Result<Records, OperationError> { + let mut records = Vec::with_capacity(SLOTS); + for slot in 0..SLOTS { + let value = self + .db + .get(key(operation, slot)) + .await + .map_err(storage_error)?; + if value + .as_ref() + .is_some_and(|bytes| bytes.len() > crypto::PROTECTED_MAX) + { + return Err(OperationError::RecoveryRequired); + } + records.push(value); + } + Ok(records) + } + async fn preparation( + &self, + operation: OperationId, + records: &Records, + ) -> Result<Option<PreparedOperation>, OperationError> { + let Some(manifest) = &records[0] else { + if records.iter().any(Option::is_some) { + return Err(OperationError::RecoveryRequired); + } + return Ok(None); + }; + let manifest = crypto::open_bound( + self.provider.as_ref(), + &self.reference, + context(self, operation, None)?, + manifest, + ) + .await?; + let (length, digest) = manifest.expose_secret(|bytes| { + if bytes.len() != 40 || &bytes[..4] != b"RRP1" { + return Err(OperationError::RecoveryRequired); + } + let length = u32::from_be_bytes( + bytes[4..8] + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ) as usize; + if length == 0 || length > protected::PREPARED_BYTES_MAX { + return Err(OperationError::RecoveryRequired); + } + let digest: [u8; 32] = bytes[8..] + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?; + Ok((length, digest)) + })?; + let count = length.div_ceil(PART_BYTES); + let mut plaintext = Zeroizing::new(Vec::with_capacity(length)); + for index in 0..PARTS { + if index >= count { + if records[index + 1].is_some() { + return Err(OperationError::RecoveryRequired); + } + continue; + } + let part = records[index + 1] + .as_ref() + .ok_or(OperationError::RecoveryRequired)?; + let opened = crypto::open_bound( + self.provider.as_ref(), + &self.reference, + context(self, operation, Some((index, &digest)))?, + part, + ) + .await?; + let expected = (length - index * PART_BYTES).min(PART_BYTES); + opened.expose_secret(|bytes| { + if bytes.len() != expected { + return Err(OperationError::RecoveryRequired); + } + plaintext.extend_from_slice(bytes); + Ok(()) + })?; + } + if Sha256::digest(plaintext.as_slice()).as_slice() != digest { + return Err(OperationError::RecoveryRequired); + } + protected::decode(&plaintext, &self.selected, operation).map(Some) + } + async fn protect_preparation( + &self, + request: &AdmissionRequest, + transaction: TransactionId, + window: IssuanceWindow, + ) -> Result<Records, OperationError> { + let plaintext = protected::encode(request, transaction, window)?; + let digest = Sha256::digest(plaintext.as_slice()); + let mut manifest = Zeroizing::new(Vec::with_capacity(40)); + manifest.extend_from_slice(b"RRP1"); + manifest.extend_from_slice(&(plaintext.len() as u32).to_be_bytes()); + manifest.extend_from_slice(&digest); + let operation = request.command().context().operation_id(); + let mut records = Vec::with_capacity(SLOTS); + records.push(Some( + crypto::seal_bound( + self.provider.as_ref(), + &self.reference, + context(self, operation, None)?, + &manifest, + ) + .await?, + )); + for (index, bytes) in plaintext.chunks(PART_BYTES).enumerate() { + records.push(Some( + crypto::seal_bound( + self.provider.as_ref(), + &self.reference, + context(self, operation, Some((index, &digest)))?, + bytes, + ) + .await?, + )); + } + records.resize_with(SLOTS, || None); + Ok(records) + } +} +fn storage_error(error: Error) -> OperationError { + match error { + Error::Capacity => WorkspaceError::Capacity.into(), + Error::Closed => WorkspaceError::Closed.into(), + Error::Aborted | Error::Unavailable => OperationError::StorageFailure, + _ => OperationError::RecoveryRequired, + } +} +struct Access { + grant: LocalOutboxGrant, + protected: Vec<u8>, + binding: WorkspaceBinding, + proof: AttachmentProof, +} +impl State { + async fn operation_access( + &self, + binding: &WorkspaceBinding, + proof: AttachmentProof, + ) -> Result<Access, OperationError> { + let (grant, protected, current) = self.access(binding.input(), &proof).await?; + protected::same_binding(binding, &current)?; + Ok(Access { + grant, + protected, + binding: current, + proof, + }) + } + async fn check_operation( + &self, + access: Access, + operation: OperationId, + before: Records, + after: Option<Records>, + window: Option<IssuanceWindow>, + ) -> Result<(), OperationError> { + let mut mutations = Vec::with_capacity(SLOTS + 1); + mutations.push( + Mutation::new( + grant_key(), + Some(access.protected.clone()), + Some(access.protected), + ) + .map_err(storage_error)?, + ); + for (slot, old) in before.into_iter().enumerate() { + let new = after + .as_ref() + .map_or_else(|| old.clone(), |r| r[slot].clone()); + mutations.push(Mutation::new(key(operation, slot), old, new).map_err(storage_error)?); + } + let batch = Batch::new(mutations).map_err(storage_error)?; + let active = self.active()?; + let clock = self.clock.clone(); + let failure = Rc::new(Cell::new(None)); + let refused = failure.clone(); + let result = self + .db + .compare_exchange_checked(batch, move || { + let eligible = (|| { + if !active.get() { + return Err(WorkspaceError::Closed.into()); + } + let now = clock.now()?; + if now.get() == 0 || now < access.binding.observed_at() { + return Err(WorkspaceError::Unavailable.into()); + } + let current = + access + .grant + .authenticate(access.binding.input(), &access.proof, now)?; + protected::same_binding(&access.binding, &current)?; + if let Some(window) = window { + if now < window.prepared_at() { + return Err(WorkspaceError::Unavailable.into()); + } + if now >= window.first_issue_not_after() { + return Err(OperationError::DeadlineExceeded); + } + } + Ok(()) + })(); + if let Err(error) = eligible { + refused.set(Some(error)); + false + } else { + true + } + }) + .await; + if matches!(result, Err(Error::GuardRefused)) { + return Err(failure.get().unwrap_or(OperationError::RecoveryRequired)); + } + match result { + Ok(_) => Ok(()), + Err(Error::CommitUnknown) => Err(WorkspaceError::CommitUnknown.into()), + Err(error) => Err(storage_error(error)), + } + } +} +impl BrowserWorkspace { + /// Atomically retains an authenticated immutable local buyer preparation. + /// Only actual commit/re-read yields Prepared; no signing or delivery occurs. + pub async fn admit_command_and_hold( + &self, + request: AdmissionRequest, + proof: AttachmentProof, + ) -> Result<AdmissionOutcome, OperationError> { + let context = request.command().context(); + let fallback = CommitAttempt::new( + context.workspace_id(), + context.operation_id(), + request.command().digest(), + None, + ); + let work = self.state.admit()?; + let state = self.state.clone(); + let result = owned(work, async move { + let access = state.operation_access(request.binding(), proof).await?; + let context = request.command().context(); + let operation = context.operation_id(); + let before = state.operation_records(operation).await?; + let (prepared, after, fresh) = + if let Some(existing) = state.preparation(operation, &before).await? { + protected::check_digest( + &existing, + context.actor(), + Some(request.command().digest()), + )?; + (existing, None, false) + } else { + if request.command().parent().is_some() || context.expected().is_some() { + return Err(OperationError::MissingHistory); + } + if context.approval().is_some() { + return Err(OperationError::UnverifiedApproval); + } + if access.binding.observed_at() < request.binding().observed_at() { + return Err(WorkspaceError::Unavailable.into()); + } + if context.not_after() > access.binding.expires_at() { + return Err(OperationError::DeadlineExceeded); + } + let window = + IssuanceWindow::capture(access.binding.observed_at(), context.not_after()) + .map_err(|_| OperationError::DeadlineExceeded)?; + let transaction = TransactionId::from_bytes(*crypto::random::<32>()?); + let records = state + .protect_preparation(&request, transaction, window) + .await?; + let prepared = PreparedOperation::from_committed_store( + request, + transaction, + Sequence::new(1).map_err(|_| OperationError::RecoveryRequired)?, + window, + )?; + (prepared, Some(records), true) + }; + let attempt = prepared.identity(); + match state + .check_operation( + access, + operation, + before, + after, + fresh.then(|| prepared.issuance_window()), + ) + .await + { + Ok(()) => Ok(AdmissionOutcome::Committed(prepared)), + Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => { + state.stop(); + Ok(AdmissionOutcome::Unknown(attempt)) + } + Err(error) => Err(error), + } + }) + .await; + match result { + Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => { + self.state.stop(); + Ok(AdmissionOutcome::Unknown(fallback)) + } + other => other, + } + } + /// Reads the original preparation under current access without replaying it. + /// Absent results are confirmed atomically against every fixed record slot. + pub async fn query_operation( + &self, + binding: WorkspaceBinding, + operation: OperationId, + digest: Option<CommandDigest>, + proof: AttachmentProof, + ) -> Result<Option<PreparedOperation>, OperationError> { + let work = self.state.admit()?; + let state = self.state.clone(); + owned(work, async move { + let access = state.operation_access(&binding, proof).await?; + let records = state.operation_records(operation).await?; + let result = state.preparation(operation, &records).await?; + if let Some(prepared) = &result { + protected::check_digest(prepared, binding.actor(), digest)?; + } + state + .check_operation(access, operation, records, None, None) + .await?; + Ok(result) + }) + .await + } +} diff --git a/crates/storage_indexeddb/src/workspace/mod.rs b/crates/storage_indexeddb/src/workspace/mod.rs @@ -2,6 +2,7 @@ //! Creation establishes a fresh unrelated buyer outbox only. Existing state //! requires its independently retained selection and protected proof. mod crypto; +mod journal; mod lease; use super::{Batch, Database, Error, Mutation, Namespace, OpenMode, RecordKey}; @@ -106,8 +107,10 @@ async fn commit_current( } }) .await; - if let Some(error) = failure.get() { - return Err(error); + // Only a confirmed abort makes the callback refusal a known failure. + // A host that completed despite refusal must retain CommitUnknown. + if matches!(result, Err(Error::GuardRefused)) { + return Err(failure.get().unwrap_or(WorkspaceError::RecoveryRequired)); } result.map(|_| ()).map_err(stored) } @@ -240,10 +243,27 @@ impl Drop for Work { } } } -async fn owned<T: 'static>( +trait JobError: From<WorkspaceError> { + fn workspace_failure(&self) -> Option<WorkspaceError>; +} +impl JobError for WorkspaceError { + fn workspace_failure(&self) -> Option<WorkspaceError> { + Some(*self) + } +} +impl JobError for radroots_storage::command::OperationError { + fn workspace_failure(&self) -> Option<WorkspaceError> { + match self { + Self::Workspace(error) => Some(*error), + Self::RecoveryRequired => Some(WorkspaceError::RecoveryRequired), + _ => None, + } + } +} +async fn owned<T: 'static, E: JobError + 'static>( work: Work, - future: impl Future<Output = Result<T, WorkspaceError>> + 'static, -) -> Result<T, WorkspaceError> { + future: impl Future<Output = Result<T, E>> + 'static, +) -> Result<T, E> { let (send, observe) = oneshot::channel(); spawn_local(async move { let state = work.0.clone(); @@ -251,17 +271,21 @@ async fn owned<T: 'static>( let _serial = state.serial.lock().await; let result = future.await; if matches!( - result, - Err(WorkspaceError::Closed - | WorkspaceError::Unavailable - | WorkspaceError::RecoveryRequired - | WorkspaceError::CommitUnknown) + result.as_ref().err().and_then(JobError::workspace_failure), + Some( + WorkspaceError::Closed + | WorkspaceError::Unavailable + | WorkspaceError::RecoveryRequired + | WorkspaceError::CommitUnknown + ) ) { state.stop(); } let _ = send.send(result); }); - observe.await.unwrap_or(Err(WorkspaceError::CommitUnknown)) + observe + .await + .unwrap_or_else(|_| Err(WorkspaceError::CommitUnknown.into())) } /// One bounded browser writer. Clones share admission, serial work and actual /// close completion. No proof or participant signer is retained in the handle. diff --git a/crates/storage_indexeddb/tests/browser/run.mjs b/crates/storage_indexeddb/tests/browser/run.mjs @@ -25,6 +25,7 @@ const server = createServer(async (req,res) => { 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==='journal_query'){const m=event.data;const owner=await WorkspaceFixture.open(m.n,new Uint8Array(m.fingerprint),new Uint8Array(m.selection),new Uint8Array(m.proof));const preparation=Array.from(await owner.query(65));await owner.close();self.postMessage({preparation});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)});}}; @@ -245,7 +246,100 @@ try { 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 keyBytes=v=>Array.from(v instanceof ArrayBuffer?new Uint8Array(v):v); + const journal=await WorkspaceFixture.create(171); + const journalReceipt={n:171,fingerprint:Array.from(journal.fingerprint()),selection:Array.from(journal.selection()),proof:Array.from(journal.proof()),namespace:journal.data_namespace()}; + const originalPreparation=Array.from(await journal.admit(65,false));same(originalPreparation.length,80); + same(Array.from(await journal.query(65)),originalPreparation);same(Array.from(await journal.query(66)),[]); + const journalBytes=await workspaceBytes(journalReceipt);same(journalBytes.values.length,4); + for(const bytes of journalBytes.values)if(bytes.length>32768)throw Error('oversized protected private record'); + journal.set_time(1600); + const originalRandom=Crypto.prototype.getRandomValues; + try{Crypto.prototype.getRandomValues=()=>{throw Error('replay acquired new entropy');};same(Array.from(await journal.admit(65,false)),originalPreparation);} + finally{Crypto.prototype.getRandomValues=originalRandom;} + await rejects(()=>journal.admit(65,true),'idempotency_conflict'); + same(Array.from(await journal.query(65)),originalPreparation); + passed('actual atomic protected multipart T0 and exact late replay without new entropy'); + journal.set_time(1000);await rejects(()=>journal.admit_expiring(66),'deadline_exceeded'); + same(Array.from(await journal.query(66)),[]); + const afterLate=await workspaceBytes(journalReceipt); + same(afterLate.values.map(v=>Array.from(v)),journalBytes.values.map(v=>Array.from(v))); + same(afterLate.keys.map(keyBytes),journalBytes.keys.map(keyBytes)); + passed('late command expiry after actual encryption aborts every operation part'); + journal.set_time(1000); + const originalPut=IDBObjectStore.prototype.put;let puts=0; + try{IDBObjectStore.prototype.put=function(...args){const request=originalPut.apply(this,args);if(this.transaction.db.name===journalReceipt.namespace&&++puts===2)this.transaction.abort();return request;};await rejects(()=>journal.admit(69,false),'storage_failure');} + finally{IDBObjectStore.prototype.put=originalPut;} + same(puts,2);same(Array.from(await journal.query(69)),[]); + const afterAbort=await workspaceBytes(journalReceipt);same(afterAbort.values.map(v=>Array.from(v)),journalBytes.values.map(v=>Array.from(v))); + passed('actual aborted multipart admission leaves no acknowledged or partial preparation'); + journal.set_time(1000);await journal.abandon_admission(67);journal.abandon_close();await journal.close(); + let retainedJournal=await WorkspaceFixture.open(journalReceipt.n,new Uint8Array(journalReceipt.fingerprint),new Uint8Array(journalReceipt.selection),new Uint8Array(journalReceipt.proof)); + const abandonedPreparation=Array.from(await retainedJournal.query(67));same(abandonedPreparation.length,80); + same(Array.from(await retainedJournal.query(65)),originalPreparation);await retainedJournal.close(); + passed('unobserved accepted T0 survives cancelled close and exact protected reopen'); + const operationKey=async(n,slot)=>{const bytes=new Uint8Array([...new TextEncoder().encode('radroots.browser.local_outbox.prepared.key.v1\0'),...new Uint8Array(32).fill(n),0,0,0,slot]);return new Uint8Array(await crypto.subtle.digest('SHA-256',bytes));}; + const manifestKey=await operationKey(65,0),part1=await operationKey(65,1),part2=await operationKey(65,2); + const retainedJournalBytes=await workspaceBytes(journalReceipt); + const findBytes=k=>retainedJournalBytes.values[retainedJournalBytes.keys.findIndex(x=>JSON.stringify(keyBytes(x))===JSON.stringify(keyBytes(k)))]; + for(const mode of ['orphan','missing_part','tampered','swapped_parts','wrong_operation']){ + await changeWorkspace(journalReceipt,store=>{ + if(mode==='orphan')store.delete(manifestKey); + if(mode==='missing_part')store.delete(part1); + if(mode==='tampered'){const bytes=new Uint8Array(findBytes(part1));bytes[bytes.length-1]^=1;store.put(bytes,part1);} + if(mode==='swapped_parts'){store.put(findBytes(part1),part2);store.put(findBytes(part2),part1);} + }); + retainedJournal=await WorkspaceFixture.open(journalReceipt.n,new Uint8Array(journalReceipt.fingerprint),new Uint8Array(journalReceipt.selection),new Uint8Array(journalReceipt.proof)); + if(mode==='wrong_operation'){const foreignKey=await operationKey(68,0);await changeWorkspace(journalReceipt,store=>store.put(findBytes(manifestKey),foreignKey));} + const beforeFailure=await workspaceBytes(journalReceipt); + if(mode==='wrong_operation'){ + await rejects(()=>retainedJournal.query(68),'recovery_required'); + }else await rejects(()=>retainedJournal.query(65),'recovery_required'); + await retainedJournal.close(); + const damaged=await workspaceBytes(journalReceipt);same(damaged.keys.map(keyBytes),beforeFailure.keys.map(keyBytes));same(damaged.values.map(v=>Array.from(v)),beforeFailure.values.map(v=>Array.from(v))); + // Failed lookup does not repair or replace any retained bytes. + await changeWorkspace(journalReceipt,store=>{store.clear();retainedJournalBytes.keys.forEach((k,i)=>store.put(retainedJournalBytes.values[i],k));}); + if(!damaged.values.length)throw Error('failed lookup discarded the namespace'); + } + retainedJournal=await WorkspaceFixture.open(journalReceipt.n,new Uint8Array(journalReceipt.fingerprint),new Uint8Array(journalReceipt.selection),new Uint8Array(journalReceipt.proof)); + same(Array.from(await retainedJournal.query(65)),originalPreparation);await retainedJournal.close(); + passed('orphan, missing, tampered, swapped and foreign-context preparation parts refuse without replacement'); + const uncertain=await WorkspaceFixture.create(174); + const uncertainReceipt={n:174,fingerprint:Array.from(uncertain.fingerprint()),selection:Array.from(uncertain.selection()),proof:Array.from(uncertain.proof()),namespace:uncertain.data_namespace()}; + const actualAbort=IDBTransaction.prototype.abort;let refusedAbort=0; + let uncertainAnchor; + try{IDBTransaction.prototype.abort=function(){if(this.db.name===uncertainReceipt.namespace){refusedAbort++;return;}return actualAbort.call(this);};uncertainAnchor=Array.from(await uncertain.admit_uncertain(70));} + finally{IDBTransaction.prototype.abort=actualAbort;} + same(uncertainAnchor.length,96);same(uncertainAnchor.slice(0,32),new Array(32).fill(70));same(refusedAbort,1); + await uncertain.close();await rejects(()=>uncertain.authenticate(),'closed'); + const partial=await workspaceBytes(uncertainReceipt);same(partial.values.length,2); + const uncertainReopen=await WorkspaceFixture.open(uncertainReceipt.n,new Uint8Array(uncertainReceipt.fingerprint),new Uint8Array(uncertainReceipt.selection),new Uint8Array(uncertainReceipt.proof)); + await rejects(()=>uncertainReopen.query(70),'recovery_required');await uncertainReopen.close(); + const preservedPartial=await workspaceBytes(uncertainReceipt);same(preservedPartial.values.map(v=>Array.from(v)),partial.values.map(v=>Array.from(v))); + passed('actual completion despite suppressed abort retains original unknown attempt and refuses partial-state reopen'); + const uncertainGrant=await WorkspaceFixture.create(175); + const uncertainGrantReceipt={n:175,fingerprint:Array.from(uncertainGrant.fingerprint()),selection:Array.from(uncertainGrant.selection()),proof:Array.from(uncertainGrant.proof()),namespace:uncertainGrant.data_namespace()}; + const originalUncertainGrant=await workspaceBytes(uncertainGrantReceipt);uncertainGrant.expire_after_next_read(); + try{IDBTransaction.prototype.abort=function(){if(this.db.name===uncertainGrantReceipt.namespace)return;return actualAbort.call(this);};await rejects(()=>uncertainGrant.revoke(),'commit_unknown');} + finally{IDBTransaction.prototype.abort=actualAbort;} + await uncertainGrant.close();const afterUncertainGrant=await workspaceBytes(uncertainGrantReceipt); + same(afterUncertainGrant.values.map(v=>Array.from(v)),originalUncertainGrant.values.map(v=>Array.from(v))); + const grantReopen=await WorkspaceFixture.open(uncertainGrantReceipt.n,new Uint8Array(uncertainGrantReceipt.fingerprint),new Uint8Array(uncertainGrantReceipt.selection),new Uint8Array(uncertainGrantReceipt.proof));same(await grantReopen.authenticate(),1);await grantReopen.close(); + passed('grant refusal cannot conceal actual uncertain completion or replace original protected state'); + + const unknownRead=await WorkspaceFixture.create(176); + const unknownReadReceipt={n:176,fingerprint:Array.from(unknownRead.fingerprint()),selection:Array.from(unknownRead.selection()),proof:Array.from(unknownRead.proof()),namespace:unknownRead.data_namespace()}; + const actualGet=IDBObjectStore.prototype.get; + let originalFallback; + try{originalFallback=Array.from(await unknownRead.admit_read_unknown(72,()=>{ + IDBObjectStore.prototype.get=function(...args){if(this.transaction.db.name===unknownReadReceipt.namespace)throw new DOMException('synthetic host read failure','InvalidStateError');return actualGet.apply(this,args);}; + IDBTransaction.prototype.abort=function(){if(this.db.name===unknownReadReceipt.namespace)return;return actualAbort.call(this);}; + }));}finally{IDBObjectStore.prototype.get=actualGet;IDBTransaction.prototype.abort=actualAbort;} + same(originalFallback.length,64);same(originalFallback.slice(0,32),new Array(32).fill(72));await unknownRead.close(); + const readReopen=await WorkspaceFixture.open(unknownReadReceipt.n,new Uint8Array(unknownReadReceipt.fingerprint),new Uint8Array(unknownReadReceipt.selection),new Uint8Array(unknownReadReceipt.proof));same(Array.from(await readReopen.query(72)),[]);await readReopen.close(); + passed('uncertain original admission read retains the captured operation anchor without inventing a transaction'); 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:'journal_query',...journalReceipt}),{preparation:originalPreparation});passed('actual worker reopens and queries the original protected preparation'); 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'); @@ -284,7 +378,7 @@ try { 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},workspace:workspaceReceipt}; + return {tests,events:events.reduce((all,event)=>(all[event]=(all[event]??0)+1,all),{}),persistent:{fingerprint,encoded},workspace:workspaceReceipt,journal:{...journalReceipt,preparation:originalPreparation}}; } finally {IDBDatabase.prototype.transaction=nativeTransaction;} }); await page.reload(); @@ -298,6 +392,8 @@ try { 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; + const preparationRestart=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 prepared=Array.from(await owner.query(65));await owner.close();return prepared;},result.journal); + assert.deepEqual(preparationRestart,result.journal.preparation);result.tests.push('original protected operation survives actual page and WASM restart');delete result.journal; delete result.persistent; console.log(JSON.stringify({engine,version:browser.version(),...result})); } finally { diff --git a/crates/storage_indexeddb/tests/browser/src/workspace.rs b/crates/storage_indexeddb/tests/browser/src/workspace.rs @@ -1,6 +1,8 @@ //! Synthetic isolated host-effect fixture, never a production custody API. use futures::FutureExt; -use radroots_domain::{ActorRole, Coverage, PublicKey, UnixSeconds, WorkspaceId}; +use radroots_domain::{ + ActorRole, CommandContextData, Coverage, OperationId, PublicKey, UnixSeconds, WorkspaceId, +}; use radroots_secrets::{ SecretId, SecretRef, browser::BrowserProvider, @@ -8,6 +10,7 @@ use radroots_secrets::{ provider::AccessPolicy, }; use radroots_storage::{ + command::{AdmissionOutcome, AdmissionRequest, PreparedOperation}, event::SourceGeneration, workspace::{AttachmentInput, AttachmentProof, WorkspaceClock, WorkspaceError, WorkspaceStore}, }; @@ -41,12 +44,14 @@ fn copied(proof: &AttachmentProof) -> AttachmentProof { struct Clock { now: Cell<u64>, after: Cell<Option<u64>>, + countdown: Cell<Option<(u32, u64)>>, } impl Clock { fn new() -> Self { Self { now: Cell::new(1000), after: Cell::new(None), + countdown: Cell::new(None), } } } @@ -56,6 +61,13 @@ impl WorkspaceClock for Clock { if let Some(next) = self.after.take() { self.now.set(next); } + if let Some((remaining, next)) = self.countdown.take() { + if remaining == 1 { + self.now.set(next); + } else { + self.countdown.set(Some((remaining - 1, next))); + } + } if now == 0 { return Err(WorkspaceError::Unavailable); } @@ -72,6 +84,105 @@ pub struct WorkspaceFixture { } #[wasm_bindgen] impl WorkspaceFixture { + pub async fn admit_read_unknown( + &self, + n: u8, + hook: js_sys::Function, + ) -> Result<Vec<u8>, JsValue> { + let request = self.request(n, false).await?; + let digest = request.command().digest(); + hook.call0(&JsValue::NULL)?; + match self + .owner + .admit_command_and_hold(request, copied(&self.proof)) + .await + .map_err(|e| JsValue::from_str(e.code()))? + { + AdmissionOutcome::Committed(_) => Err(JsValue::from_str("unexpected_commit")), + AdmissionOutcome::Unknown(anchor) => { + assert_eq!(anchor.workspace_id(), self.input.workspace_id()); + assert_eq!(anchor.operation_id(), OperationId::from_bytes([n; 32])); + assert_eq!(anchor.command_digest(), digest); + assert_eq!(anchor.transaction_id(), None); + let mut bytes = anchor.operation_id().as_bytes().to_vec(); + bytes.extend_from_slice(anchor.command_digest().as_bytes()); + Ok(bytes) + } + } + } + pub async fn admit_uncertain(&self, n: u8) -> Result<Vec<u8>, JsValue> { + let request = self.request(n, false).await?; + let digest = request.command().digest(); + self.clock.countdown.set(Some((3, 1500))); + match self + .owner + .admit_command_and_hold(request, copied(&self.proof)) + .await + .map_err(|e| JsValue::from_str(e.code()))? + { + AdmissionOutcome::Committed(_) => Err(JsValue::from_str("unexpected_commit")), + AdmissionOutcome::Unknown(anchor) => { + assert_eq!(anchor.workspace_id(), self.input.workspace_id()); + assert_eq!(anchor.operation_id(), OperationId::from_bytes([n; 32])); + assert_eq!(anchor.command_digest(), digest); + let mut bytes = anchor.operation_id().as_bytes().to_vec(); + bytes.extend_from_slice(anchor.command_digest().as_bytes()); + bytes.extend_from_slice(anchor.transaction_id().unwrap().as_bytes()); + Ok(bytes) + } + } + } + pub async fn admit(&self, n: u8, changed: bool) -> Result<Vec<u8>, JsValue> { + let request = self.request(n, changed).await?; + match self + .owner + .admit_command_and_hold(request, copied(&self.proof)) + .await + .map_err(|e| JsValue::from_str(e.code()))? + { + AdmissionOutcome::Committed(prepared) => Ok(summary(prepared)), + AdmissionOutcome::Unknown(_) => Err(JsValue::from_str("commit_unknown")), + } + } + pub async fn query(&self, n: u8) -> Result<Vec<u8>, JsValue> { + let binding = self + .owner + .authenticate(self.input.clone(), copied(&self.proof)) + .await + .map_err(fail)?; + let result = self + .owner + .query_operation( + binding, + OperationId::from_bytes([n; 32]), + None, + copied(&self.proof), + ) + .await + .map_err(|e| JsValue::from_str(e.code()))?; + Ok(result.map(summary).unwrap_or_default()) + } + pub async fn admit_expiring(&self, n: u8) -> Result<(), JsValue> { + let request = self.request(n, false).await?; + self.clock.after.set(Some(1500)); + self.owner + .admit_command_and_hold(request, copied(&self.proof)) + .await + .map(|_| ()) + .map_err(|e| JsValue::from_str(e.code())) + } + pub async fn abandon_admission(&self, n: u8) -> Result<(), JsValue> { + let request = self.request(n, false).await?; + if self + .owner + .admit_command_and_hold(request, copied(&self.proof)) + .now_or_never() + .is_some() + { + return Err(JsValue::from_str("unexpected_immediate_admission")); + } + Ok(()) + } pub async fn sibling(&self) -> Result<Self, JsValue> { let clock = Rc::new(Clock::new()); let config = LocalOutboxConfig::new( @@ -253,6 +364,39 @@ impl WorkspaceFixture { } } impl WorkspaceFixture { + async fn request(&self, n: u8, changed: bool) -> Result<AdmissionRequest, JsValue> { + let binding = self + .owner + .authenticate(self.input.clone(), copied(&self.proof)) + .await + .map_err(fail)?; + let context = CommandContextData::new( + OperationId::from_bytes([n; 32]), + binding.actor(), + self.input.workspace_id(), + self.input.authority(), + self.input.route_digest(), + None, + None, + UnixSeconds::new(1500).unwrap(), + None, + ) + .unwrap(); + // Escaped control bytes exercise multiple private-record parts without + // exceeding the shared 4096-byte chat text limit. + let text = if changed { + "changed".to_string() + } else { + "\u{0001}".repeat(4096) + }; + let wire = serde_json::to_vec( + &serde_json::json!({"type":"inbox.inquire","context":context, + "input":{"thread_id":"66".repeat(32),"peer":participant(),"source":null,"text":text}}), + ) + .unwrap(); + AdmissionRequest::from_protected_wire(binding, &wire) + .map_err(|e| JsValue::from_str(e.code())) + } async fn initialize(n: u8, expire: bool) -> Result<Self, JsValue> { let provider = Rc::new( BrowserProvider::create(key_namespace(n), reference()) @@ -288,3 +432,16 @@ impl WorkspaceFixture { }) } } +fn summary(prepared: PreparedOperation) -> Vec<u8> { + let mut bytes = prepared.transaction_id().as_bytes().to_vec(); + bytes.extend_from_slice(prepared.request().command().digest().as_bytes()); + bytes.extend_from_slice(&prepared.issuance_window().prepared_at().get().to_be_bytes()); + bytes.extend_from_slice( + &prepared + .issuance_window() + .first_issue_not_after() + .get() + .to_be_bytes(), + ); + bytes +} diff --git a/crates/storage_sqlite/src/workspace/admission.rs b/crates/storage_sqlite/src/workspace/admission.rs @@ -403,20 +403,7 @@ impl Journal<'_> { } } -pub(super) fn same_binding( - captured: &WorkspaceBinding, - current: &WorkspaceBinding, -) -> Result<(), OperationError> { - if captured.input() != current.input() - || captured.actor() != current.actor() - || captured.principal_id() != current.principal_id() - || captured.grant_revision() != current.grant_revision() - || captured.expires_at() != current.expires_at() - { - return Err(OperationError::Unauthorized); - } - Ok(()) -} +pub(super) use radroots_storage::command::protected::same_binding; #[expect( clippy::too_many_arguments, diff --git a/crates/storage_sqlite/src/workspace/operation.rs b/crates/storage_sqlite/src/workspace/operation.rs @@ -1,78 +1,24 @@ //! Retained non-stock command preparation. No signing or delivery occurs here. -use super::{AttachmentInput, WorkspaceBinding, crypto::WorkspaceCrypto}; -use radroots_domain::{ - CommandDigest, IssuanceWindow, OperationId, Sequence, TransactionId, UnixSeconds, -}; +use super::{AttachmentInput, crypto::WorkspaceCrypto}; +use radroots_domain::{IssuanceWindow, OperationId, TransactionId}; use radroots_storage::command::{AdmissionRequest, OperationError, PreparedOperation}; -use serde::{Deserialize, Serialize}; use sqlx::{Row, SqliteConnection}; -use zeroize::Zeroizing; pub(super) const TABLE: &str = "CREATE TABLE operations (workspace BLOB NOT NULL CHECK(length(workspace)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL CHECK(length(grant_id)=32), command_type TEXT NOT NULL CHECK(command_type IN ('inbox.inquire','inbox.reply')), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), phase TEXT NOT NULL CHECK(phase='prepared'), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), grant_singleton INTEGER NOT NULL CHECK(grant_singleton=1) REFERENCES workspace_grant(singleton), PRIMARY KEY(workspace,operation_id)) STRICT, WITHOUT ROWID"; pub(super) const INDEX: &str = "CREATE UNIQUE INDEX operation_transaction_identity ON operations(workspace,transaction_id)"; -#[derive(Serialize)] -struct Encoded<'a> { - version: u8, - selection: &'a AttachmentInput, - principal: &'a str, - grant_revision: Sequence, - grant_expires_at: UnixSeconds, - captured_observed_at: UnixSeconds, - transaction_id: TransactionId, - revision: Sequence, - prepared_at: UnixSeconds, - first_issue_not_after: UnixSeconds, - command: &'a serde_json::value::RawValue, -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Decoded<'a> { - version: u8, - selection: AttachmentInput, - principal: String, - grant_revision: Sequence, - grant_expires_at: UnixSeconds, - captured_observed_at: UnixSeconds, - transaction_id: TransactionId, - revision: Sequence, - prepared_at: UnixSeconds, - first_issue_not_after: UnixSeconds, - #[serde(borrow)] - command: &'a serde_json::value::RawValue, -} - pub(super) async fn protect( request: &AdmissionRequest, transaction_id: TransactionId, window: IssuanceWindow, crypto: &WorkspaceCrypto, ) -> Result<Vec<u8>, OperationError> { - let binding = request.binding(); - let encoded = Encoded { - version: 2, - selection: binding.input(), - principal: binding.principal_id(), - grant_revision: binding.grant_revision(), - grant_expires_at: binding.expires_at(), - captured_observed_at: binding.observed_at(), - transaction_id, - revision: Sequence::new(1).map_err(|_| OperationError::RecoveryRequired)?, - prepared_at: window.prepared_at(), - first_issue_not_after: window.first_issue_not_after(), - command: serde_json::from_slice(request.command().protected_wire()) - .map_err(|_| OperationError::InvalidCommand)?, - }; - let plaintext = - Zeroizing::new(serde_json::to_vec(&encoded).map_err(|_| OperationError::InvalidCommand)?); - if plaintext.len() > 65_536 { - return Err(OperationError::InvalidCommand); - } + let plaintext = radroots_storage::command::protected::encode(request, transaction_id, window)?; Ok(crypto .seal_operation( - binding.input().workspace_id(), + request.binding().input().workspace_id(), request.command().context().operation_id(), &plaintext, ) @@ -116,58 +62,19 @@ pub(super) async fn read( .open_operation(selected.workspace_id(), operation_id, &protected) .await?; let snapshot = plaintext.expose_secret(|bytes| { - let decoded: Decoded<'_> = - serde_json::from_slice(bytes).map_err(|_| OperationError::RecoveryRequired)?; - if decoded.version != 2 - || decoded.revision.get() == 0 - || phase != "prepared" - || revision != 1 - || decoded.revision.get() != revision as u64 - { - return Err(OperationError::RecoveryRequired); - } - let command_context: radroots_domain::CommandContextData = { - #[derive(Deserialize)] - struct ContextOnly { - context: radroots_domain::CommandContextData, - } - serde_json::from_str::<ContextOnly>(decoded.command.get()) - .map_err(|_| OperationError::RecoveryRequired)? - .context - }; - let binding = WorkspaceBinding::from_authenticated_host( - decoded.selection, - command_context.actor(), - decoded.principal, - decoded.grant_revision, - decoded.grant_expires_at, - decoded.captured_observed_at, - )?; - if binding.input() != selected { - return Err(OperationError::RecoveryRequired); - } - let request = - AdmissionRequest::from_protected_wire(binding, decoded.command.get().as_bytes())?; - let context = request.command().context(); - if context.workspace_id() != selected.workspace_id() - || context.operation_id() != operation_id - || actor != context.actor().participant().as_bytes() - || grant != request.binding().input().grant_id().as_bytes() - || digest != request.command().digest().as_bytes() - || transaction != decoded.transaction_id.as_bytes() - || kind != request.command().kind().as_str() - { - return Err(OperationError::RecoveryRequired); - } - let snapshot = PreparedOperation::from_committed_store( - request, - decoded.transaction_id, - decoded.revision, - IssuanceWindow::new(decoded.prepared_at, decoded.first_issue_not_after) - .map_err(|_| OperationError::RecoveryRequired)?, - )?; - Ok::<_, OperationError>(snapshot) + radroots_storage::command::protected::decode(bytes, selected, operation_id) })?; + let request = snapshot.request(); + if phase != "prepared" + || revision != 1 + || actor != request.command().context().actor().participant().as_bytes() + || grant != request.binding().input().grant_id().as_bytes() + || digest != request.command().digest().as_bytes() + || transaction != snapshot.transaction_id().as_bytes() + || kind != request.command().kind().as_str() + { + return Err(OperationError::RecoveryRequired); + } Ok(Some((snapshot, protected))) } @@ -210,16 +117,4 @@ pub(super) async fn unchanged( Ok(()) } -pub(super) fn check_digest( - snapshot: &PreparedOperation, - actor: radroots_domain::ActorRef, - expected: Option<CommandDigest>, -) -> Result<(), OperationError> { - if snapshot.request().command().context().actor().participant() != actor.participant() { - return Err(OperationError::Unauthorized); - } - if expected.is_some_and(|digest| digest != snapshot.request().command().digest()) { - return Err(OperationError::IdempotencyConflict); - } - Ok(()) -} +pub(super) use radroots_storage::command::protected::check_digest;