lib

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

commit 9a2675ea0b7180301b757f99b3d38f76e226ddbf
parent dbb74f8cbfc30aa6e3cb063fe4427a264efac543
Author: triesap <tyson@radroots.org>
Date:   Mon, 19 Oct 2026 21:19:58 +0000

storage: Retain original browser chat installations

- Install obtained output once and append distinct recipient work
- Reconstruct coherent snapshots through shared checked models
- Refuse missing signing history with retained native descendants
- Verify real browser rollback, uncertainty and restart behavior

Diffstat:
Mcontracts/api_baselines/radroots_storage_indexeddb.wasm32_workspace.txt | 7+++++--
Mcontracts/architecture/decisions/browser_workspace.v2.json | 42++++++++++++++++++++++++++++++++++++------
Mcrates/radroots/tests/support/receipt_installation.rs | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_indexeddb/README.md | 23+++++++++++++++++++----
Mcrates/storage_indexeddb/src/workspace/address.rs | 4++++
Acrates/storage_indexeddb/src/workspace/installation.rs | 317+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_indexeddb/src/workspace/installation/codec.rs | 144+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_indexeddb/src/workspace/issuance.rs | 110++++++++++++++++++++++++++++++++++++++++++++-----------------------------------
Mcrates/storage_indexeddb/src/workspace/mod.rs | 10++++++----
Acrates/storage_indexeddb/src/workspace/retained.rs | 151++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_indexeddb/tests/browser/run.mjs | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcrates/storage_indexeddb/tests/browser/src/workspace.rs | 1+
Acrates/storage_indexeddb/tests/browser/src/workspace/installation.rs | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_indexeddb/tests/browser/src/workspace/issuance.rs | 26+++++++-------------------
Mcrates/storage_sqlite/src/workspace/issuance.rs | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/snapshot.rs | 136++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------
Mcrates/storage_sqlite/src/workspace/tests/issuance_records.rs | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
17 files changed, 1271 insertions(+), 140 deletions(-)

diff --git a/contracts/api_baselines/radroots_storage_indexeddb.wasm32_workspace.txt b/contracts/api_baselines/radroots_storage_indexeddb.wasm32_workspace.txt @@ -9,9 +9,9 @@ impl radroots_storage_indexeddb::workspace::BrowserWorkspace pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::bind_signing_intents(&self, radroots_storage::workspace::WorkspaceBinding, radroots_protocol::chat::plan::ChatSigningPlan, radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage::command::PlanBindingOutcome, radroots_storage::command::OperationError> pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::signing_plan(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage::command::BoundSigningPlan>, radroots_storage::command::OperationError> impl radroots_storage_indexeddb::workspace::BrowserWorkspace -pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::capture_signed_seal(&self, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof, radroots_storage::command::issuance::SealEvidence) -> core::result::Result<radroots_storage::command::issuance::EvidenceCaptureOutcome, radroots_storage::command::OperationError> -pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::captured_seal(&self, radroots_storage::command::issuance::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage::command::issuance::CapturedSeal>, radroots_storage::command::OperationError> +pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::capture_evidence(&self, radroots_storage::workspace::AttachmentInput, &radroots_storage::workspace::AttachmentProof, &radroots_storage::command::issuance::SealEvidence) -> core::result::Result<radroots_storage::command::issuance::EvidenceCaptureOutcome, radroots_storage::command::OperationError> pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::claim_attempt(&self, radroots_storage::command::issuance::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage::command::issuance::ClaimAttemptOutcome, radroots_storage::command::OperationError> +pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::obtained_evidence(&self, radroots_storage::command::issuance::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage::command::issuance::CapturedSeal>, radroots_storage::command::OperationError> pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::signing_attempt(&self, radroots_storage::command::issuance::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage::command::issuance::SigningAttempt>, 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> @@ -19,6 +19,9 @@ pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::initialize 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::open_existing_for_capture(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 radroots_storage_indexeddb::workspace::BrowserWorkspace +pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::install_transition_and_outbox(&self, radroots_storage::command::installation::InstallationRequest, radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage::command::installation::InstallationOutcome, radroots_storage::command::OperationError> +pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::operation_snapshot(&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::snapshot::OperationSnapshot>, radroots_storage::command::OperationError> 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 diff --git a/contracts/architecture/decisions/browser_workspace.v2.json b/contracts/architecture/decisions/browser_workspace.v2.json @@ -1,7 +1,7 @@ { "schema_version": 1, "contract_id": "radroots.storage.browser_workspace.v2", - "state": "implemented_verified_issuance_component", + "state": "implemented_verified_installation_component", "owner": "radroots_storage_indexeddb", "feature": "workspace", "target": "wasm32-unknown-unknown", @@ -69,7 +69,9 @@ "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 + "final_phone_or_full_rcld_claim": false, + "expanded_fixture_deadline_seconds": 180, + "fixture_deadline_is_product_performance_acceptance": false }, "shared_prepared_codec": "radroots_storage::command::protected", "operation_admission": { @@ -150,8 +152,6 @@ "delivery_request_index" ], "reserved_not_yet_implemented_families": [ - "installation", - "publication_work", "delivery_frame", "delivery_observation", "delivery_request_index" @@ -169,9 +169,39 @@ "fresh_time_or_revocation_discards_obtained_fact": false, "unknown_observation_time": "null", "capture_only_open_allows_fresh_authentication_or_commands": false, - "each_signed_field_id_and_signature_verified_against_stored_intent": true + "each_signed_field_id_and_signature_verified_against_stored_intent": true, + "caller_original_proof_and_evidence_borrowed": true, + "admitted_driver_retains_bounded_work_copy": true }, "qualification_state": "behavior_verified_native_and_three_browsers", "shared_claim_codec": "radroots_storage::command::protected::issuance::ClaimRecord", - "shared_obtained_metadata_codec": "radroots_storage::command::protected::issuance::EvidenceManifest" + "shared_obtained_metadata_codec": "radroots_storage::command::protected::issuance::EvidenceManifest", + "chat_installation": { + "phase": "T2", + "shared_checked_models": [ + "ChatInstallation", + "PublicationWork", + "OperationSnapshot" + ], + "private_wire": "fixed_binary_v2_468_bytes", + "body_in_original_command": true, + "one_original_message_and_basis": true, + "later_obtained_recipients_append_distinct_work": true, + "fresh_current_access_lease_and_clock_required": true, + "original_first_issue_window_applied_to_installation": false, + "exact_retained_replay_before_entropy": true, + "complete_prefix_checked_in_actual_transaction": true, + "unknown_original_attempt_retained": true, + "delivery_or_full_client_claim": false + }, + "concrete_ports": [ + "operation", + "signing_plan", + "claim_attempt", + "signing_attempt", + "capture_evidence", + "obtained_evidence", + "install_transition_and_outbox", + "operation_snapshot" + ] } diff --git a/crates/radroots/tests/support/receipt_installation.rs b/crates/radroots/tests/support/receipt_installation.rs @@ -65,6 +65,68 @@ async fn snapshot( } #[tokio::test] +async fn existing_peer_installation_allows_first_self_claim_within_original_window() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let (prepared, digest, recipients) = + prepare(&fixture, &store, &binding, &proof, 225, true).await; + let peer = *recipients + .iter() + .find(|recipient| **recipient != key()) + .unwrap(); + let peer_claim = claim( + store + .claim_attempt(selection(&binding, &prepared, digest, peer), copy(&proof)) + .await + .unwrap(), + ); + let peer_capture = capture(&store, &input, &proof, &peer_claim).await; + let original = installed( + store + .install_transition_and_outbox( + request_install(&binding, &prepared, digest), + copy(&proof), + ) + .await + .unwrap(), + ); + assert_eq!(original.basis(), peer_capture); + let partial = snapshot(&store, &binding, &prepared, &proof).await; + assert_eq!(partial.publications().len(), 1); + assert!( + partial + .recipients() + .iter() + .find(|value| value.recipient() == key()) + .unwrap() + .claim() + .is_none() + ); + fixture.clock.now.store(110, Ordering::SeqCst); + let own = claim( + store + .claim_attempt(selection(&binding, &prepared, digest, key()), copy(&proof)) + .await + .unwrap(), + ); + capture(&store, &input, &proof, &own).await; + let extended = installed( + store + .install_transition_and_outbox( + request_install(&binding, &prepared, digest), + copy(&proof), + ) + .await + .unwrap(), + ); + assert_eq!(extended, original); + let complete = snapshot(&store, &binding, &prepared, &proof).await; + assert_eq!(complete.publications().len(), 2); + assert_eq!(complete.installed_message(), partial.installed_message()); + store.close().await.unwrap(); +} + +#[tokio::test] async fn actual_peer_installation_and_late_self_capture_keep_one_original_message_and_distinct_work() { let fixture = Fixture::new(); diff --git a/crates/storage_indexeddb/README.md b/crates/storage_indexeddb/README.md @@ -51,8 +51,22 @@ observation in at most four 16 KiB parts plus an authenticated manifest. Actual signing happens outside storage. Capture requires retained proof and the actual original claim; expiry, revocation or an unavailable clock cannot discard already obtained output. Explicit capture-only opening permits this append and closure, -and denies current authentication and fresh work. Installation, delivery and a -complete journal/client remain separate phases. +and denies current authentication and fresh work. `capture_evidence` borrows +the original proof and output; accepted work retains its bounded owned copy +through caller cancellation. `obtained_evidence` reads original exact output. + +The owner installs an original logical chat once from actual obtained evidence, +then appends distinct publication work for later obtained recipients. Exact +replay preserves the message, basis and transaction before new entropy. The +original first-issue deadline limits signing, while installation of already +obtained bytes requires current grant/proof, lease and clock. Shared checked +installation/publication models validate relationships; host-private v2 metadata +is a closed 468-byte record under independent protection contexts. Bodies stay +in the original command. `operation_snapshot` verifies the complete retained +T0/T1/S/T2 graph and reconstructs its original message through the shared model. +All facts are witnessed and compared in the actual transaction before results +are returned. Missing predecessors with retained descendants refuse false +absence and new issuance. Delivery and a complete client remain separate phases. An owner-bound read snapshot witnesses at most 16,384 ordered opaque keys, lengths and SHA-256 digests, using a conservative 2 MiB scan reservation. Every @@ -99,5 +113,6 @@ fixture's lockfile, using an external output directory and the output name directory, that output directory, `chromium`, `firefox`, or `webkit`, and the preserved v1 fixture package directory for actual cross-version refusal checks. Both the page and dedicated worker import those generated bytes. The runner -uses isolated loopback origins and bounds each run to 90 seconds. Route builds, -generation and runner execution through `cargo extbuild run --`. +uses isolated loopback origins and bounds each expanded run to 180 seconds. +This harness ceiling is not a product deadline or performance acceptance. Route +builds, generation and runner execution through `cargo extbuild run --`. diff --git a/crates/storage_indexeddb/src/workspace/address.rs b/crates/storage_indexeddb/src/workspace/address.rs @@ -9,6 +9,8 @@ pub(super) const PREPARED: u8 = 1; pub(super) const PLAN: u8 = 2; pub(super) const CLAIM: u8 = 3; pub(super) const EVIDENCE: u8 = 4; +pub(super) const INSTALLATION: u8 = 5; +pub(super) const PUBLICATION: u8 = 6; fn prefix_bytes(operation: OperationId) -> [u8; 16] { let digest = Sha256::new() @@ -44,6 +46,8 @@ pub(super) fn fields(key: RecordKey) -> Result<(u8, u8, u8), OperationError> { PLAN => recipient != 0 || part > 24, CLAIM => recipient > 1 || part != 0, EVIDENCE => recipient > 1 || part > 4, + INSTALLATION => recipient != 0 || part != 0, + PUBLICATION => recipient > 1 || part != 0, // Later reserved families remain unsupported until their actual // implementations and proving cohort land. Never ignore them. _ => true, diff --git a/crates/storage_indexeddb/src/workspace/installation.rs b/crates/storage_indexeddb/src/workspace/installation.rs @@ -0,0 +1,317 @@ +//! Actual exactly-once chat installation and append-only recipient work. +mod codec; +use super::journal::{OperationChange, Records as PreparationRecords, storage_error}; +use super::{ + BrowserWorkspace, Mutation, State, WorkspaceError, address, crypto, owned, retained::Graph, +}; +use crate::ReadSnapshot; +use radroots_domain::{CommandDigest, OperationId, TransactionId}; +use radroots_secrets::context::{ + EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId, +}; +use radroots_storage::{ + command::{ + BoundSigningPlan, ChatInstallation, CommitAttempt, InstallationOutcome, + InstallationRequest, OperationError, OperationSnapshot, PublicationWork, + }, + workspace::{AttachmentProof, WorkspaceBinding}, +}; +use sha2::{Digest, Sha256}; + +fn context( + state: &State, + bound: &BoundSigningPlan, + recipient: Option<u8>, +) -> Result<EnvelopeContext, OperationError> { + let mut hash = Sha256::new() + .chain_update(b"radroots.browser.local_outbox.installation.context.v2\0") + .chain_update(state.selected.workspace_id().as_bytes()) + .chain_update(bound.prepared().identity().operation_id().as_bytes()) + .chain_update(bound.plan().digest()); + let schema = if let Some(index) = recipient { + let seal = bound + .plan() + .seals() + .get(index as usize) + .ok_or(OperationError::RecoveryRequired)?; + hash.update([1, index]); + hash.update(seal.recipient().as_bytes()); + "radroots.browser.workspace.publication.v2" + } else { + hash.update([0]); + "radroots.browser.workspace.message.v2" + }; + let subject = hash + .finalize() + .iter() + .map(|b| format!("{b:02x}")) + .collect::<String>(); + Ok(EnvelopeContext::new( + EnvelopePurpose::parse("radroots.browser.workspace.installation") + .map_err(|_| OperationError::InvalidCommand)?, + EnvelopeSubject::parse("workspace_installation", subject) + .map_err(|_| OperationError::InvalidCommand)?, + PayloadSchemaId::parse(schema).map_err(|_| OperationError::InvalidCommand)?, + )) +} +pub(super) struct Records { + message: Option<ChatInstallation>, + work: Vec<PublicationWork>, +} +impl Records { + async fn read( + state: &State, + view: &ReadSnapshot, + graph: &Graph, + operation: OperationId, + ) -> Result<Self, OperationError> { + let message = if let Some(raw) = state + .read_view_key(view, address::key(operation, address::INSTALLATION, 0, 0)) + .await? + { + let bound = graph.bound().ok_or(OperationError::RecoveryRequired)?; + let clear = crypto::open_bound( + state.provider.as_ref(), + &state.reference, + context(state, bound, None)?, + &raw, + ) + .await?; + Some(clear.expose_secret(|raw| codec::decode_message(raw, graph))?) + } else { + None + }; + let mut work = Vec::with_capacity(2); + if let Some(bound) = graph.bound() { + for (index, seal) in bound.plan().seals().iter().enumerate() { + if let Some(raw) = state + .read_view_key( + view, + address::key(operation, address::PUBLICATION, index as u8, 0), + ) + .await? + { + let installed = message.ok_or(OperationError::RecoveryRequired)?; + let clear = crypto::open_bound( + state.provider.as_ref(), + &state.reference, + context(state, bound, Some(index as u8))?, + &raw, + ) + .await?; + work.push(clear.expose_secret(|raw| { + codec::decode_work(raw, graph, installed, seal.recipient()) + })?); + } + } + } + if let Some(message) = message + && !work.iter().any(|value| value.evidence() == message.basis()) + { + return Err(OperationError::RecoveryRequired); + } + Ok(Self { message, work }) + } +} +impl State { + /// A missing claim must not conceal installation/publication descendants. + /// The complete witnessed prefix still fences all facts at actual commit. + pub(super) async fn check_claim_absence( + &self, + view: &ReadSnapshot, + operation: OperationId, + digest: CommandDigest, + t0: &PreparationRecords, + ) -> Result<(), OperationError> { + let graph = Graph::read(self, view, operation, Some(digest), t0).await?; + Records::read(self, view, &graph, operation).await?; + Ok(()) + } +} +impl BrowserWorkspace { + /// Installs the original logical message once and appends work for each + /// actual obtained recipient. This performs no signing or delivery. + pub async fn install_transition_and_outbox( + &self, + request: InstallationRequest, + proof: AttachmentProof, + ) -> Result<InstallationOutcome, OperationError> { + let fallback = request.identity(); + 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 operation = request.operation_id(); + let view = state.read_view(operation).await?; + let t0 = state.operation_records(&view, operation).await?; + let graph = Graph::read( + &state, + &view, + operation, + Some(request.command_digest()), + &t0, + ) + .await?; + let bound = graph.bound().ok_or(OperationError::RecoveryRequired)?; + radroots_storage::command::protected::same_binding( + bound.prepared().request().binding(), + request.binding(), + )?; + if bound.plan().digest() != request.plan_digest() { + return Err(OperationError::IdempotencyConflict); + } + let records = Records::read(&state, &view, &graph, operation).await?; + let missing = graph + .obtained() + .filter(|evidence| { + !records + .work + .iter() + .any(|value| value.evidence().recipient() == evidence.recipient()) + }) + .collect::<Vec<_>>(); + if records.message.is_none() && missing.is_empty() { + return Err(OperationError::InvalidEvidence); + } + let fresh = records.message.is_none() || !missing.is_empty(); + let transaction = if fresh { + TransactionId::from_bytes(*crypto::random::<32>()?) + } else { + records + .message + .ok_or(OperationError::RecoveryRequired)? + .transaction_id() + }; + let installed = if let Some(value) = records.message { + value + } else { + ChatInstallation::from_committed_store( + bound, + *missing.first().ok_or(OperationError::InvalidEvidence)?, + transaction, + access.binding.observed_at(), + )? + }; + let mut extra = Vec::with_capacity(3); + if records.message.is_none() { + let raw = codec::message(bound, installed); + let protected = crypto::seal_bound( + state.provider.as_ref(), + &state.reference, + context(&state, bound, None)?, + &raw, + ) + .await?; + extra.push( + Mutation::new( + address::key(operation, address::INSTALLATION, 0, 0), + None, + Some(protected), + ) + .map_err(storage_error)?, + ); + } + for evidence in missing { + let index = bound + .plan() + .seals() + .iter() + .position(|seal| seal.recipient() == evidence.recipient()) + .ok_or(OperationError::RecoveryRequired)? as u8; + let value = PublicationWork::from_committed_store( + bound, + installed, + evidence, + transaction, + access.binding.observed_at(), + )?; + let raw = codec::work(installed, value); + let protected = crypto::seal_bound( + state.provider.as_ref(), + &state.reference, + context(&state, bound, Some(index))?, + &raw, + ) + .await?; + extra.push( + Mutation::new( + address::key(operation, address::PUBLICATION, index, 0), + None, + Some(protected), + ) + .map_err(storage_error)?, + ); + } + let anchor = CommitAttempt::new( + installed.workspace_id(), + operation, + installed.command_digest(), + Some(transaction), + ); + match state + .check_operation( + access, + operation, + OperationChange { + before: t0, + after: None, + window: None, + extra, + }, + view, + ) + .await + { + Ok(()) => Ok(InstallationOutcome::Committed(Box::new(installed))), + Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => { + state.stop(); + Ok(InstallationOutcome::Unknown(anchor)) + } + Err(error) => Err(error), + } + }) + .await; + match result { + Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => { + self.state.stop(); + Ok(InstallationOutcome::Unknown(fallback)) + } + other => other, + } + } + /// Confirms the original coherent T0/T1/S/T2 graph. Querying never dispatches + /// a signer or implies a missing delivery acknowledgement. + pub async fn operation_snapshot( + &self, + binding: WorkspaceBinding, + operation: OperationId, + digest: Option<CommandDigest>, + proof: AttachmentProof, + ) -> Result<Option<OperationSnapshot>, OperationError> { + let work = self.state.admit()?; + let state = self.state.clone(); + owned(work, async move { + let access = state.operation_access(&binding, proof).await?; + let observed = access.binding.observed_at(); + let view = state.read_view(operation).await?; + let t0 = state.operation_records(&view, operation).await?; + let graph = Graph::read(&state, &view, operation, digest, &t0).await?; + if let Some(prepared) = graph.prepared() { + radroots_storage::command::protected::same_binding( + prepared.request().binding(), + &binding, + )?; + } + let records = Records::read(&state, &view, &graph, operation).await?; + let snapshot = graph + .into_snapshot(observed)? + .map(|snapshot| snapshot.with_installation(records.message, records.work)) + .transpose()?; + state + .check_operation(access, operation, OperationChange::observe(t0), view) + .await?; + Ok(snapshot) + }) + .await + } +} diff --git a/crates/storage_indexeddb/src/workspace/installation/codec.rs b/crates/storage_indexeddb/src/workspace/installation/codec.rs @@ -0,0 +1,144 @@ +//! Closed host-private v2 metadata. Bodies stay in the original command. +use super::super::retained::Graph; +use radroots_domain::{PublicKey, TransactionId, UnixSeconds}; +use radroots_storage::command::{ + BoundSigningPlan, ChatInstallation, EvidenceReceipt, OperationError, PublicationWork, +}; +use zeroize::Zeroizing; + +const LENGTH: usize = 4 + 6 * 32 + 8 + 8 * 32 + 8; +const TRANSACTION: usize = 4 + 5 * 32; +const TIME: usize = 4 + 6 * 32; +const RECIPIENT: usize = TIME + 8 + 3 * 32; +const MESSAGE: &[u8; 4] = b"RRM2"; +const WORK: &[u8; 4] = b"RRW2"; +const _: () = assert!(LENGTH <= 16 * 1024); + +fn encode( + magic: &[u8; 4], + fields: [&[u8; 32]; 6], + time: UnixSeconds, + receipt: EvidenceReceipt, +) -> Zeroizing<Vec<u8>> { + let mut raw = Zeroizing::new(Vec::with_capacity(LENGTH)); + raw.extend_from_slice(magic); + for field in fields { + raw.extend_from_slice(field); + } + raw.extend_from_slice(&time.get().to_be_bytes()); + for field in [ + receipt.workspace_id().as_bytes(), + receipt.operation_id().as_bytes(), + receipt.command_digest().as_bytes(), + receipt.recipient().as_bytes(), + receipt.attempt_id().as_bytes(), + receipt.event_id().as_bytes(), + receipt.digest(), + receipt.transaction_id().as_bytes(), + ] { + raw.extend_from_slice(field); + } + raw.extend_from_slice( + &receipt + .observed_at_unix_ms() + .map_or(0, |time| time.get()) + .to_be_bytes(), + ); + raw +} +fn selectors( + raw: &[u8], + magic: &[u8; 4], +) -> Result<(TransactionId, UnixSeconds, PublicKey), OperationError> { + if raw.len() != LENGTH || &raw[..4] != magic { + return Err(OperationError::RecoveryRequired); + } + let transaction = TransactionId::from_bytes( + raw[TRANSACTION..TRANSACTION + 32] + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ); + let time = UnixSeconds::new(u64::from_be_bytes( + raw[TIME..TIME + 8] + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + )) + .map_err(|_| OperationError::RecoveryRequired)?; + let recipient = PublicKey::from_bytes( + raw[RECIPIENT..RECIPIENT + 32] + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ) + .map_err(|_| OperationError::RecoveryRequired)?; + Ok((transaction, time, recipient)) +} +pub(super) fn message(bound: &BoundSigningPlan, value: ChatInstallation) -> Zeroizing<Vec<u8>> { + encode( + MESSAGE, + [ + value.plan_digest(), + value.message_id().as_bytes(), + bound.prepared().request().command().thread_id().as_bytes(), + value.preparation_transaction_id().as_bytes(), + value.plan_transaction_id().as_bytes(), + value.transaction_id().as_bytes(), + ], + value.installed_at(), + value.basis(), + ) +} +pub(super) fn decode_message( + raw: &[u8], + graph: &Graph, +) -> Result<ChatInstallation, OperationError> { + let (transaction, time, recipient) = selectors(raw, MESSAGE)?; + let bound = graph.bound().ok_or(OperationError::RecoveryRequired)?; + let report = ChatInstallation::from_committed_store( + bound, + graph.receipt(recipient)?, + transaction, + time, + )?; + if message(bound, report).as_slice() != raw { + return Err(OperationError::RecoveryRequired); + } + Ok(report) +} +pub(super) fn work(installed: ChatInstallation, value: PublicationWork) -> Zeroizing<Vec<u8>> { + encode( + WORK, + [ + value.plan_digest(), + installed.message_id().as_bytes(), + value.installation_transaction_id().as_bytes(), + installed.preparation_transaction_id().as_bytes(), + installed.plan_transaction_id().as_bytes(), + value.transaction_id().as_bytes(), + ], + value.queued_at(), + value.evidence(), + ) +} +pub(super) fn decode_work( + raw: &[u8], + graph: &Graph, + installed: ChatInstallation, + expected: PublicKey, +) -> Result<PublicationWork, OperationError> { + let (transaction, time, recipient) = selectors(raw, WORK)?; + if recipient != expected { + return Err(OperationError::RecoveryRequired); + } + let bound = graph.bound().ok_or(OperationError::RecoveryRequired)?; + let report = PublicationWork::from_committed_store( + bound, + installed, + graph.receipt(recipient)?, + transaction, + time, + )?; + if work(installed, report).as_slice() != raw { + return Err(OperationError::RecoveryRequired); + } + Ok(report) +} diff --git a/crates/storage_indexeddb/src/workspace/issuance.rs b/crates/storage_indexeddb/src/workspace/issuance.rs @@ -21,7 +21,7 @@ use radroots_storage::{ use sha2::{Digest, Sha256}; use zeroize::Zeroizing; -enum Claim { +pub(super) enum Claim { Absent(BoundSigningPlan, u8), Present(SigningAttempt), } @@ -97,37 +97,12 @@ impl State { digest: CommandDigest, t0: &Records, ) -> Result<Option<BoundSigningPlan>, OperationError> { - let Some(prepared) = self.preparation(operation, t0).await? else { - if !view.is_empty() { - return Err(OperationError::RecoveryRequired); - } - return Ok(None); - }; - if prepared.request().binding().input() != &self.selected - || prepared.request().command().context().actor().participant() - != self.selected.participant() - { - return Err(OperationError::Unauthorized); + match super::retained::header(self, view, operation, Some(digest), t0).await? { + Some(radroots_storage::command::RetainedOperation::Planned(bound)) => Ok(Some(*bound)), + _ => Ok(None), } - protected::check_digest( - &prepared, - prepared.request().command().context().actor(), - Some(digest), - )?; - let records = self.plan_records(view, operation).await?; - let Some((manifest, plan)) = self.retained_plan(&prepared, &records).await? else { - self.absent_plans(view, operation).await?; - return Ok(None); - }; - for key in view.keys() { - let (kind, recipient, _) = address::fields(key)?; - if kind >= address::CLAIM && recipient as usize >= plan.seals().len() { - return Err(OperationError::RecoveryRequired); - } - } - manifest.bind(prepared, plan).map(Some) } - async fn claim( + pub(super) async fn claim( &self, view: &ReadSnapshot, bound: BoundSigningPlan, @@ -150,7 +125,7 @@ impl State { let attempt = clear.expose_secret(|raw| ClaimRecord::decode(raw, bound, recipient))?; Ok(Claim::Present(attempt)) } - async fn evidence( + pub(super) async fn evidence( &self, view: &ReadSnapshot, attempt: &SigningAttempt, @@ -182,8 +157,7 @@ impl State { .await?; let manifest = raw.expose_secret(|raw| EvidenceManifest::decode(raw, attempt))?; let mut clear = Zeroizing::new(Vec::with_capacity(manifest.byte_count())); - for part in 1..=4 { - let bytes = &records[part]; + for (part, bytes) in records.iter().enumerate().skip(1) { if part > manifest.part_count() { if bytes.is_some() { return Err(OperationError::RecoveryRequired); @@ -303,6 +277,9 @@ impl BrowserWorkspace { { Claim::Present(attempt) => (attempt, false, Vec::new()), Claim::Absent(bound, index) => { + state + .check_claim_absence(&view, operation, request.command_digest(), &t0) + .await?; let now = access.binding.observed_at(); if now < bound.bound_at() { return Err(WorkspaceError::Unavailable.into()); @@ -392,7 +369,17 @@ impl BrowserWorkspace { .await? { Claim::Present(attempt) => Some(attempt), - Claim::Absent(_, _) => None, + Claim::Absent(_, _) => { + state + .check_claim_absence( + &view, + operation, + request.command_digest(), + &t0, + ) + .await?; + None + } } } else { None @@ -409,11 +396,13 @@ impl BrowserWorkspace { } /// Appends already obtained exact output to an actual original claim. /// No current clock or grant revocation can discard that retained fact. - pub async fn capture_signed_seal( + /// Borrowed original input remains caller-owned through error or lost wait; + /// an accepted driver retains only its bounded protected-work copy. + pub async fn capture_evidence( &self, input: AttachmentInput, - proof: AttachmentProof, - supplied: SealEvidence, + proof: &AttachmentProof, + supplied: &SealEvidence, ) -> Result<EvidenceCaptureOutcome, OperationError> { let fallback = CommitAttempt::new( supplied.workspace_id(), @@ -423,6 +412,8 @@ impl BrowserWorkspace { ); let work = self.state.admit()?; let state = self.state.clone(); + let proof = proof.with_secret(|raw| AttachmentProof::from_protected_input(raw))?; + let supplied = supplied.retained_copy(); let result = owned(work, async move { let (grant, protected) = state.capture_grant(&input, &proof).await?; if supplied.workspace_id() != state.selected.workspace_id() { @@ -509,7 +500,7 @@ impl BrowserWorkspace { } } /// Reads original verified output under current access; no issuance occurs. - pub async fn captured_seal( + pub async fn obtained_evidence( &self, request: ClaimAttemptRequest, proof: AttachmentProof, @@ -534,18 +525,39 @@ impl BrowserWorkspace { .claim(&view, bound, request.recipient(), index) .await? { - Claim::Present(attempt) => state - .evidence(&view, &attempt, index) - .await? - .map(|(evidence, receipt)| { - CapturedSeal::from_committed_store( - attempt, - evidence, - receipt.transaction_id(), + Claim::Present(attempt) => { + let obtained = state.evidence(&view, &attempt, index).await?; + if obtained.is_none() { + state + .check_claim_absence( + &view, + operation, + request.command_digest(), + &t0, + ) + .await?; + } + obtained + .map(|(evidence, receipt)| { + CapturedSeal::from_committed_store( + attempt, + evidence, + receipt.transaction_id(), + ) + }) + .transpose()? + } + Claim::Absent(_, _) => { + state + .check_claim_absence( + &view, + operation, + request.command_digest(), + &t0, ) - }) - .transpose()?, - Claim::Absent(_, _) => None, + .await?; + None + } } } else { None diff --git a/crates/storage_indexeddb/src/workspace/mod.rs b/crates/storage_indexeddb/src/workspace/mod.rs @@ -3,10 +3,12 @@ //! requires its independently retained selection and protected proof. mod address; mod crypto; +mod installation; mod issuance; mod journal; mod lease; mod plans; +mod retained; use super::{Batch, Database, Error, Mutation, Namespace, OpenMode, RecordKey}; use futures::{channel::oneshot, lock::Mutex}; @@ -259,10 +261,10 @@ 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(); - } + if self.0.jobs.get() == 0 + && let Some(waker) = self.0.drain.borrow_mut().take() + { + waker.wake(); } } } diff --git a/crates/storage_indexeddb/src/workspace/retained.rs b/crates/storage_indexeddb/src/workspace/retained.rs @@ -0,0 +1,151 @@ +//! Authenticated bounded T0/T1/S data; mutation authority remains in the host. +use super::{State, address, issuance::Claim, journal::Records}; +use crate::ReadSnapshot; +use radroots_domain::{CommandDigest, EnvelopeEventId, OperationId, PublicKey, UnixSeconds}; +use radroots_storage::command::{ + BoundSigningPlan, ClaimSnapshot, EvidenceReceipt, OperationError, OperationSnapshot, + RecipientSnapshot, RetainedOperation, protected, +}; + +pub(super) async fn header( + state: &State, + view: &ReadSnapshot, + operation: OperationId, + digest: Option<CommandDigest>, + t0: &Records, +) -> Result<Option<RetainedOperation>, OperationError> { + let Some(prepared) = state.preparation(operation, t0).await? else { + if !view.is_empty() { + return Err(OperationError::RecoveryRequired); + } + return Ok(None); + }; + if prepared.request().binding().input() != &state.selected + || prepared.request().command().context().actor().participant() + != state.selected.participant() + { + return Err(OperationError::Unauthorized); + } + protected::check_digest( + &prepared, + prepared.request().command().context().actor(), + digest, + )?; + let records = state.plan_records(view, operation).await?; + let Some((manifest, plan)) = state.retained_plan(&prepared, &records).await? else { + state.absent_plans(view, operation).await?; + return Ok(Some(RetainedOperation::Prepared(prepared))); + }; + for key in view.keys() { + let (kind, recipient, _) = address::fields(key)?; + if kind >= address::CLAIM && recipient as usize >= plan.seals().len() { + return Err(OperationError::RecoveryRequired); + } + } + Ok(Some(RetainedOperation::Planned(Box::new( + manifest.bind(prepared, plan)?, + )))) +} + +pub(super) struct Graph { + retained: Option<RetainedOperation>, + recipients: Vec<RecipientSnapshot>, +} +impl Graph { + pub(super) async fn read( + state: &State, + view: &ReadSnapshot, + operation: OperationId, + digest: Option<CommandDigest>, + t0: &Records, + ) -> Result<Self, OperationError> { + let retained = header(state, view, operation, digest, t0).await?; + let mut recipients = Vec::with_capacity(2); + let retained = match retained { + Some(RetainedOperation::Planned(bound)) => { + let mut bound = *bound; + let keys = bound + .plan() + .seals() + .iter() + .map(|seal| seal.recipient()) + .collect::<Vec<_>>(); + for (index, recipient) in keys.into_iter().enumerate() { + let expected = + EnvelopeEventId::from_bytes(bound.plan().seals()[index].event_id()); + match state.claim(view, bound, recipient, index as u8).await? { + Claim::Absent(returned, _) => { + recipients.push(RecipientSnapshot::from_store_report( + recipient, + Some(expected), + None, + None, + )); + bound = returned; + } + Claim::Present(attempt) => { + let claim = ClaimSnapshot::from_store_report(&attempt); + // Verify one bounded exact seal at a time; retaining a + // receipt does not duplicate private plan/raw bodies. + let obtained = state + .evidence(view, &attempt, index as u8) + .await? + .map(|(_, receipt)| receipt); + recipients.push(RecipientSnapshot::from_store_report( + recipient, + Some(expected), + Some(claim), + obtained, + )); + bound = attempt.into_bound_plan(); + } + } + } + Some(RetainedOperation::Planned(Box::new(bound))) + } + Some(RetainedOperation::Prepared(prepared)) => { + let command = prepared.request().command(); + let mut keys = vec![command.context().actor().participant(), command.peer()]; + keys.sort_unstable(); + keys.dedup(); + for recipient in keys { + recipients.push(RecipientSnapshot::from_store_report( + recipient, None, None, None, + )); + } + Some(RetainedOperation::Prepared(prepared)) + } + None => None, + }; + Ok(Self { + retained, + recipients, + }) + } + pub(super) fn bound(&self) -> Option<&BoundSigningPlan> { + self.retained + .as_ref() + .and_then(RetainedOperation::bound_plan) + } + pub(super) fn prepared(&self) -> Option<&radroots_storage::command::PreparedOperation> { + self.retained.as_ref().map(RetainedOperation::prepared) + } + pub(super) fn receipt(&self, recipient: PublicKey) -> Result<EvidenceReceipt, OperationError> { + self.recipients + .iter() + .find(|value| value.recipient() == recipient) + .and_then(|value| value.obtained()) + .ok_or(OperationError::RecoveryRequired) + } + pub(super) fn obtained(&self) -> impl Iterator<Item = EvidenceReceipt> + '_ { + self.recipients.iter().filter_map(|value| value.obtained()) + } + pub(super) fn into_snapshot( + self, + observed: UnixSeconds, + ) -> Result<Option<OperationSnapshot>, OperationError> { + self.retained + .map(|source| OperationSnapshot::from_store_report(source, self.recipients, observed)) + .transpose() + } +} diff --git a/crates/storage_indexeddb/tests/browser/run.mjs b/crates/storage_indexeddb/tests/browser/run.mjs @@ -31,6 +31,7 @@ const server = createServer(async (req,res) => { 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==='plan_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 plan=Array.from(await owner.plan_query(180));await owner.close();self.postMessage({plan});return;} if(event.data?.kind==='issuance_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 claim=Array.from(await owner.attempt(190,0)),seal=Array.from(await owner.captured(190,0));await owner.close();self.postMessage({claim,seal});return;} + if(event.data?.kind==='installation_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 state=JSON.parse(await owner.snapshot(200));await owner.close();self.postMessage({state});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)});}}; @@ -42,7 +43,7 @@ const server = createServer(async (req,res) => { }); await new Promise(resolve => server.listen(0,'127.0.0.1',resolve)); let browser; -const deadline=setTimeout(()=>{void browser?.close();},90000); +const deadline=setTimeout(()=>{void browser?.close();},180000); deadline.unref(); try { browser = await playwright[engine].launch({headless:true}); @@ -566,7 +567,86 @@ try { await changeWorkspace({namespace:copiedNamespace},store=>legacyRows.keys.forEach((key,i)=>store.put(legacyRows.values[i],key))); const copiedV1Rows=await workspaceBytes({namespace:copiedNamespace});await rejects(()=>openPlanReceipt(legacyReceipt),'recovery_required');sameRows(await workspaceBytes({namespace:copiedNamespace}),copiedV1Rows);sameRows(await workspaceBytes(legacyReceipt),legacyRows); passed('actual immutable v1 runtime and v2 refuse cross-version opening and copied-grant reinterpretation while preserving prior bytes'); + const hex=bytes=>Array.from(bytes,b=>b.toString(16).padStart(2,'0')).join(''); + const snapshotOf=async(owner,n)=>JSON.parse(await owner.snapshot(n)); + const {owner:installOwner,receipt:installReceipt}=await setupIssuance(200); + const beforeInstallation=await workspaceBytes(installReceipt),plannedState=await snapshotOf(installOwner,200); + same(plannedState.installation,null);same(plannedState.publications,[]);same(plannedState.message,null); + await rejects(()=>installOwner.install(200),'invalid_evidence');sameRows(await workspaceBytes(installReceipt),beforeInstallation); + const peerInstallSeal=await installOwner.obtain(200,1,true),peerInstallCapture=Array.from(await installOwner.capture(peerInstallSeal)); + const originalInstallation=JSON.parse(await installOwner.install(200)),partialInstallation=await snapshotOf(installOwner,200); + same(originalInstallation.basis_capture,hex(peerInstallCapture.slice(0,32)));same(partialInstallation.installation,originalInstallation);same(partialInstallation.publications.length,1); + same(partialInstallation.claims[0].claim,null);same(partialInstallation.message.id,originalInstallation.message);same(partialInstallation.message.text,'\u0001'.repeat(3000));same(partialInstallation.message.created_at,1000);same(partialInstallation.deliveries,0);same(partialInstallation.observations,0); + if(partialInstallation.checkpoint===plannedState.checkpoint)throw Error('T2 did not advance the actual original progress digest'); + passed('actual T2 requires obtained output and installs one original message plus independent peer publication work'); + installOwner.set_time(1100);const selfInstallSeal=await installOwner.obtain(200,0,false),selfInstallCapture=Array.from(await installOwner.capture(selfInstallSeal)); + const obtainedBeforeAppend=await snapshotOf(installOwner,200);same(obtainedBeforeAppend.publications.length,1);same(obtainedBeforeAppend.installation,originalInstallation); + installOwner.set_time(1600);same(JSON.parse(await installOwner.install(200)),originalInstallation); + const installedState=await snapshotOf(installOwner,200);same(installedState.publications.length,2);same(installedState.message,partialInstallation.message);same(installedState.installation,originalInstallation); + const oldPeerWork=installedState.publications.find(work=>work.capture===hex(peerInstallCapture.slice(0,32))),newSelfWork=installedState.publications.find(work=>work.capture===hex(selfInstallCapture.slice(0,32))); + same(oldPeerWork.transaction,originalInstallation.transaction);same(newSelfWork.installation,originalInstallation.transaction);same(newSelfWork.at,1600);if(newSelfWork.transaction===originalInstallation.transaction)throw Error('later recipient append invented the original installation transaction'); + try{Crypto.prototype.getRandomValues=()=>{throw Error('exact T2 replay acquired new entropy');};same(JSON.parse(await installOwner.install(200)),originalInstallation);same(await snapshotOf(installOwner,200),installedState);} + finally{Crypto.prototype.getRandomValues=originalRandom;} + await installOwner.close(); + passed('first self claim remains legal after peer installation and late recipient append preserves original message, basis and transaction'); + const {owner:lateInstallOwner,receipt:lateInstallReceipt}=await setupIssuance(201),lateInstallSeal=await lateInstallOwner.obtain(201,0,false);await lateInstallOwner.capture(lateInstallSeal);lateInstallOwner.set_time(1600); + const lateInstallation=JSON.parse(await lateInstallOwner.install(201));same(lateInstallation.at,1600);same((await snapshotOf(lateInstallOwner,201)).message.created_at,1000);await lateInstallOwner.close(); + const lateInstallReopen=await openPlanReceipt(lateInstallReceipt);same((await snapshotOf(lateInstallReopen,201)).installation,lateInstallation);await lateInstallReopen.close(); + passed('first installation of retained obtained evidence succeeds after original issuance expiry and reopens unchanged'); + const {owner:cancelInstallOwner,receipt:cancelInstallReceipt}=await setupIssuance(202),cancelInstallSeal=await cancelInstallOwner.obtain(202,0,true);await cancelInstallOwner.capture(cancelInstallSeal); + const message202=await recordKey(202,5),beforeInstallAbort=await workspaceBytes(cancelInstallReceipt);let actualMessageWrite=false; + try{IDBObjectStore.prototype.put=function(...args){const r=actualPlanPut.apply(this,args);if(this.transaction.db.name===cancelInstallReceipt.namespace&&JSON.stringify(keyBytes(args[1]))===JSON.stringify(keyBytes(message202)))r.addEventListener('success',()=>{actualMessageWrite=true;this.transaction.abort();},{once:true});return r;};await rejects(()=>cancelInstallOwner.install(202),'storage_failure');} + finally{IDBObjectStore.prototype.put=actualPlanPut;} + same(actualMessageWrite,true);sameRows(await workspaceBytes(cancelInstallReceipt),beforeInstallAbort);same((await snapshotOf(cancelInstallOwner,202)).installation,null); + await cancelInstallOwner.abandon_install(202);same(cancelInstallOwner.abandon_auths(1),0);cancelInstallOwner.abandon_close();await cancelInstallOwner.close(); + const installAfterCancel=await openPlanReceipt(cancelInstallReceipt);same((await snapshotOf(installAfterCancel,202)).publications.length,1);await installAfterCancel.close(); + passed('actual message-write abort acknowledges no installation; an unobserved retry remains owned through cancelled close'); + for(const mode of ['bad_clock','expired_grant']){ + const n=mode==='bad_clock'?205:206,{owner,receipt}=await setupIssuance(n),seal=await owner.obtain(n,0,false);await owner.capture(seal);const before=await workspaceBytes(receipt); + await rejects(()=>mode==='bad_clock'?owner.install_bad_clock(n):owner.install_expired_grant(n),mode==='bad_clock'?'workspace_unavailable':'grant_expired');await owner.close();sameRows(await workspaceBytes(receipt),before); + const current=await openPlanReceipt(receipt);same((await snapshotOf(current,n)).installation,null);await current.close(); + } + passed('T2 active callbacks refuse clock rollback and grant expiry after wrapping without changing obtained facts'); + const stableInstallation=await workspaceBytes(installReceipt),message200=await recordKey(200,5),work200Self=await recordKey(200,6,0),work200Peer=await recordKey(200,6,1); + const installationValue=key=>stableInstallation.values[stableInstallation.keys.findIndex(k=>JSON.stringify(keyBytes(k))===JSON.stringify(keyBytes(key)))]; + for(const mode of ['missing_message','missing_basis_work','tampered_message','swapped_work','complete_s_loss','obtained_s_loss']){ + await changeWorkspace(installReceipt,store=>{ + if(mode==='missing_message')store.delete(message200); + if(mode==='missing_basis_work')store.delete(work200Peer); + if(mode==='tampered_message'){const raw=new Uint8Array(installationValue(message200));raw[raw.length-1]^=1;store.put(raw,message200);} + if(mode==='swapped_work')store.put(installationValue(work200Self),work200Peer); + if(mode==='complete_s_loss')stableInstallation.keys.filter(k=>[3,4].includes(keyBytes(k)[16])).forEach(key=>store.delete(key)); + if(mode==='obtained_s_loss')stableInstallation.keys.filter(k=>keyBytes(k)[16]===4).forEach(key=>store.delete(key)); + }); + const damaged=await workspaceBytes(installReceipt);let current=await openPlanReceipt(installReceipt);await rejects(()=>current.snapshot(200),'recovery_required');await current.close(); + current=await openPlanReceipt(installReceipt);await rejects(()=>current.install(200),'recovery_required');await current.close(); + if(mode==='complete_s_loss'){ + current=await openPlanReceipt(installReceipt);await rejects(()=>current.claim(200,0),'recovery_required');await current.close(); + current=await openPlanReceipt(installReceipt);await rejects(()=>current.attempt(200,0),'recovery_required');await current.close(); + current=await openPlanReceipt(installReceipt);await rejects(()=>current.captured(200,0),'recovery_required');await current.close(); + } + if(mode==='obtained_s_loss'){ + current=await openPlanReceipt(installReceipt);await rejects(()=>current.captured(200,0),'recovery_required');await current.close(); + } + sameRows(await workspaceBytes(installReceipt),damaged);await changeWorkspace(installReceipt,store=>{store.clear();stableInstallation.keys.forEach((key,i)=>store.put(stableInstallation.values[i],key));}); + } + passed('missing, damaged, foreign-recipient and orphan T2 state refuses query, replacement and reissuance with exact bytes preserved'); + const {owner:unknownInstallOwner,receipt:unknownInstallReceipt}=await setupIssuance(203),unknownInstallSeal=await unknownInstallOwner.obtain(203,0,false);await unknownInstallOwner.capture(unknownInstallSeal); + const unchangedT0Part=await operationKey(203,1);let unknownInstallation; + try{unknownInstallation=Array.from(await unknownInstallOwner.install_unknown(203,()=>injectAsyncError(unknownInstallReceipt.namespace,unchangedT0Part)));} + finally{IDBObjectStore.prototype.put=actualPlanPut;IDBTransaction.prototype.abort=actualAbort;} + same(unknownInstallation.length,96);same(unknownInstallation.slice(0,32),new Array(32).fill(203));await unknownInstallOwner.close(); + const afterUnknownInstall=await openPlanReceipt(unknownInstallReceipt),unknownInstalledState=await snapshotOf(afterUnknownInstall,203);same(unknownInstalledState.installation.transaction,hex(unknownInstallation.slice(64)));same(unknownInstalledState.publications.length,1);await afterUnknownInstall.close(); + passed('actual uncertain T2 completion retains its original transaction and reconciles the installed message after reopen'); + const {owner:partialInstallOwner,receipt:partialInstallReceipt}=await setupIssuance(204),partialInstallSeal=await partialInstallOwner.obtain(204,0,false);await partialInstallOwner.capture(partialInstallSeal); + const failedPublication=await recordKey(204,6,0),partialT0Part=await operationKey(204,1);let partialInstallAnchor; + try{partialInstallAnchor=Array.from(await partialInstallOwner.install_unknown(204,()=>injectAsyncError(partialInstallReceipt.namespace,failedPublication,partialT0Part)));} + finally{IDBObjectStore.prototype.put=actualPlanPut;IDBTransaction.prototype.abort=actualAbort;} + same(partialInstallAnchor.length,96);await partialInstallOwner.close();const partialInstallRows=await workspaceBytes(partialInstallReceipt);let partialInstallReopen=await openPlanReceipt(partialInstallReceipt); + await rejects(()=>partialInstallReopen.snapshot(204),'recovery_required');await partialInstallReopen.close();partialInstallReopen=await openPlanReceipt(partialInstallReceipt);await rejects(()=>partialInstallReopen.install(204),'recovery_required');await partialInstallReopen.close();sameRows(await workspaceBytes(partialInstallReceipt),partialInstallRows); + passed('partial actual T2 completion preserves original uncertainty and refuses orphan message repair or replacement'); 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:'installation_query',...installReceipt}),{state:installedState});passed('actual worker and fresh WASM reopen the original installation and both publication links'); same(await workCall({kind:'issuance_query',...signingReceipt}),{claim:originalClaim,seal:originalSeal});passed('actual worker and fresh WASM reopen the original protected claim and captured signature'); same(await workCall({kind:'plan_query',...planReceipt}),{plan:originalPlan});passed('actual worker reopens and confirms the original protected complete T1'); same(await workCall({kind:'journal_query',...journalReceipt}),{preparation:originalPreparation});passed('actual worker reopens and queries the original protected preparation'); @@ -608,7 +688,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,journal:{...journalReceipt,preparation:originalPreparation},plan:{...planReceipt,originalPlan},issuance:{...signingReceipt,originalClaim,originalSeal}}; + return {tests,events:events.reduce((all,event)=>(all[event]=(all[event]??0)+1,all),{}),persistent:{fingerprint,encoded},workspace:workspaceReceipt,journal:{...journalReceipt,preparation:originalPreparation},plan:{...planReceipt,originalPlan},issuance:{...signingReceipt,originalClaim,originalSeal},installation:{...installReceipt,installedState}}; } finally {IDBDatabase.prototype.transaction=nativeTransaction;} }); await page.reload(); @@ -626,6 +706,7 @@ try { assert.deepEqual(preparationRestart,result.journal.preparation);result.tests.push('original protected operation survives actual page and WASM restart');delete result.journal; const planRestart=await page.evaluate(async r=>{const {default:init,WorkspaceFixture}=await import('./fixture.js');await init();const owner=await WorkspaceFixture.open(r.n,new Uint8Array(r.fingerprint),new Uint8Array(r.selection),new Uint8Array(r.proof));const plan=Array.from(await owner.plan_query(180));await owner.close();return plan;},result.plan);assert.deepEqual(planRestart,result.plan.originalPlan);result.tests.push('complete original protected T1 survives actual page and WASM restart');delete result.plan; delete result.persistent; + const installationRestart=await page.evaluate(async r=>{const {default:init,WorkspaceFixture}=await import('./fixture.js');await init();const owner=await WorkspaceFixture.open(r.n,new Uint8Array(r.fingerprint),new Uint8Array(r.selection),new Uint8Array(r.proof));const state=JSON.parse(await owner.snapshot(200));await owner.close();return state;},result.installation);assert.deepEqual(installationRestart,result.installation.installedState);result.tests.push('original installation and per-recipient work survive actual page and WASM restart');delete result.installation; const issuanceRestart=await page.evaluate(async r=>{const {default:init,WorkspaceFixture}=await import('./fixture.js');await init();const owner=await WorkspaceFixture.open(r.n,new Uint8Array(r.fingerprint),new Uint8Array(r.selection),new Uint8Array(r.proof));const claim=Array.from(await owner.attempt(190,0)),seal=Array.from(await owner.captured(190,0));await owner.close();return {claim,seal};},result.issuance);assert.deepEqual(issuanceRestart,{claim:result.issuance.originalClaim,seal:result.issuance.originalSeal});result.tests.push('original claim and captured signature survive actual page and WASM restart');delete result.issuance; 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,4 +1,5 @@ //! Synthetic isolated host-effect fixture, never a production custody API. +mod installation; mod issuance; mod plans; use futures::FutureExt; diff --git a/crates/storage_indexeddb/tests/browser/src/workspace/installation.rs b/crates/storage_indexeddb/tests/browser/src/workspace/installation.rs @@ -0,0 +1,124 @@ +//! Actual T2 and coherent original-state projections for the isolated fixture. +use super::{WorkspaceFixture, copied}; +use futures::FutureExt; +use radroots_storage::command::{ + ChatInstallation, InstallationOutcome, InstallationRequest, OperationSnapshot, +}; +use serde_json::{Value, json}; +use wasm_bindgen::prelude::*; + +fn installation(value: ChatInstallation) -> Value { + json!({"transaction":value.transaction_id().to_string(),"message":value.message_id().to_string(),"at":value.installed_at().get(),"basis_capture":value.basis().transaction_id().to_string(),"basis_recipient":value.basis().recipient().to_string()}) +} +fn snapshot(value: &OperationSnapshot) -> Value { + json!({ + "checkpoint":value.checkpoint_digest().to_string(), + "preparation":value.prepared().transaction_id().to_string(), + "plan":value.bound_plan().map(|bound|bound.transaction_id().to_string()), + "installation":value.installation().map(installation), + "publications":value.publications().iter().map(|work|json!({"recipient":work.evidence().recipient().to_string(),"transaction":work.transaction_id().to_string(),"capture":work.evidence().transaction_id().to_string(),"installation":work.installation_transaction_id().to_string(),"at":work.queued_at().get()})).collect::<Vec<_>>(), + "claims":value.recipients().iter().map(|recipient|json!({"recipient":recipient.recipient().to_string(),"claim":recipient.claim().map(|claim|claim.attempt_id().to_string()),"capture":recipient.obtained().map(|capture|capture.transaction_id().to_string())})).collect::<Vec<_>>(), + "message":value.installed_message().map(|message|json!({"id":message.id().to_string(),"peer":message.peer().to_string(),"text":message.text(),"created_at":message.created_at().get()})), + "deliveries":value.delivery_attempts().len(),"observations":value.delivery_observations().len(), + }) +} +impl WorkspaceFixture { + async fn installation_request(&self, n: u8) -> Result<InstallationRequest, JsValue> { + let request = self.request(n, false).await?; + let bound = self + .owner + .signing_plan( + request.binding().clone(), + request.command().context().operation_id(), + request.command().digest(), + copied(&self.proof), + ) + .await + .map_err(|e| JsValue::from_str(e.code()))? + .ok_or(JsValue::from_str("missing_plan"))?; + Ok(InstallationRequest::new( + request.binding().clone(), + request.command().context().operation_id(), + request.command().digest(), + *bound.plan().digest(), + )) + } + async fn install_mode(&self, n: u8, after: Option<u64>) -> Result<String, JsValue> { + let request = self.installation_request(n).await?; + self.clock.after.set(after); + match self + .owner + .install_transition_and_outbox(request, copied(&self.proof)) + .await + .map_err(|e| JsValue::from_str(e.code()))? + { + InstallationOutcome::Committed(value) => Ok(installation(*value).to_string()), + InstallationOutcome::Unknown(_) => Err(JsValue::from_str("commit_unknown")), + } + } +} +#[wasm_bindgen] +impl WorkspaceFixture { + pub async fn install(&self, n: u8) -> Result<String, JsValue> { + self.install_mode(n, None).await + } + pub async fn install_bad_clock(&self, n: u8) -> Result<String, JsValue> { + self.install_mode(n, Some(90)).await + } + pub async fn install_expired_grant(&self, n: u8) -> Result<String, JsValue> { + self.install_mode(n, Some(2000)).await + } + pub async fn install_unknown(&self, n: u8, hook: js_sys::Function) -> Result<Vec<u8>, JsValue> { + let request = self.installation_request(n).await?; + let operation = request.operation_id(); + let digest = request.command_digest(); + hook.call0(&JsValue::NULL)?; + match self + .owner + .install_transition_and_outbox(request, copied(&self.proof)) + .await + .map_err(|e| JsValue::from_str(e.code()))? + { + InstallationOutcome::Unknown(anchor) => { + assert_eq!(anchor.operation_id(), operation); + assert_eq!(anchor.command_digest(), digest); + let mut raw = operation.as_bytes().to_vec(); + raw.extend_from_slice(digest.as_bytes()); + raw.extend_from_slice(anchor.transaction_id().unwrap().as_bytes()); + Ok(raw) + } + _ => Err(JsValue::from_str("unexpected_known_installation")), + } + } + pub async fn abandon_install(&self, n: u8) -> Result<(), JsValue> { + let request = self.installation_request(n).await?; + if self + .owner + .install_transition_and_outbox(request, copied(&self.proof)) + .now_or_never() + .is_some() + { + return Err(JsValue::from_str("unexpected_immediate_installation")); + } + Ok(()) + } + pub async fn snapshot(&self, n: u8) -> Result<String, JsValue> { + let request = self.request(n, false).await?; + self.owner + .operation_snapshot( + request.binding().clone(), + request.command().context().operation_id(), + Some(request.command().digest()), + copied(&self.proof), + ) + .await + .map(|value| { + value + .as_ref() + .map(snapshot) + .unwrap_or(Value::Null) + .to_string() + }) + .map_err(|e| JsValue::from_str(e.code())) + } +} diff --git a/crates/storage_indexeddb/tests/browser/src/workspace/issuance.rs b/crates/storage_indexeddb/tests/browser/src/workspace/issuance.rs @@ -131,7 +131,7 @@ impl WorkspaceFixture { original.attempt.seal().recipient(), ); self.owner - .captured_seal(request, copied(&self.proof)) + .obtained_evidence(request, copied(&self.proof)) .await .map(|value| value.map(|v| receipt(v.receipt())).unwrap_or_default()) .map_err(|e| JsValue::from_str(e.code())) @@ -227,7 +227,7 @@ impl WorkspaceFixture { let alternate = signed_output(&original.attempt, None)?; assert_ne!(alternate.raw_json(), original.value.raw_json()); self.owner - .capture_signed_seal(self.input.clone(), copied(&self.proof), alternate) + .capture_evidence(self.input.clone(), &self.proof, &alternate) .await .map(|_| ()) .map_err(|e| JsValue::from_str(e.code())) @@ -241,7 +241,7 @@ impl WorkspaceFixture { .unwrap(); match self .owner - .capture_signed_seal(self.input.clone(), copied(&self.proof), evidence) + .capture_evidence(self.input.clone(), &self.proof, &evidence) .await .map_err(|e| JsValue::from_str(e.code()))? { @@ -252,11 +252,7 @@ impl WorkspaceFixture { pub async fn capture(&self, original: &ObtainedSeal) -> Result<Vec<u8>, JsValue> { match self .owner - .capture_signed_seal( - self.input.clone(), - copied(&self.proof), - original.value.retained_copy(), - ) + .capture_evidence(self.input.clone(), &self.proof, &original.value) .await .map_err(|e| JsValue::from_str(e.code()))? { @@ -267,11 +263,7 @@ impl WorkspaceFixture { pub async fn capture_unknown(&self, original: &ObtainedSeal) -> Result<Vec<u8>, JsValue> { match self .owner - .capture_signed_seal( - self.input.clone(), - copied(&self.proof), - original.value.retained_copy(), - ) + .capture_evidence(self.input.clone(), &self.proof, &original.value) .await .map_err(|e| JsValue::from_str(e.code()))? { @@ -289,7 +281,7 @@ impl WorkspaceFixture { pub async fn captured(&self, n: u8, index: u8) -> Result<Vec<u8>, JsValue> { let request = self.claim_request(n, index).await?; self.owner - .captured_seal(request, copied(&self.proof)) + .obtained_evidence(request, copied(&self.proof)) .await .map(|value| { value @@ -301,11 +293,7 @@ impl WorkspaceFixture { pub fn abandon_capture(&self, original: &ObtainedSeal) -> Result<(), JsValue> { if self .owner - .capture_signed_seal( - self.input.clone(), - copied(&self.proof), - original.value.retained_copy(), - ) + .capture_evidence(self.input.clone(), &self.proof, &original.value) .now_or_never() .is_some() { diff --git a/crates/storage_sqlite/src/workspace/issuance.rs b/crates/storage_sqlite/src/workspace/issuance.rs @@ -5,6 +5,7 @@ use super::{ admission::{Journal, recheck, same_binding}, attempt, evidence, operation, plan, record::GrantRecord, + snapshot::RetainedFacts, worker, }; use radroots_domain::{CommandDigest, OperationId, PublicKey, SigningAttemptId, TransactionId}; @@ -82,6 +83,21 @@ impl Journal<'_> { self.crypto, ) .await?; + let absence = if existing.is_none() { + Some( + RetainedFacts::read( + self.connection, + self.selected, + request.binding(), + request.operation_id(), + Some(request.command_digest()), + self.crypto, + ) + .await?, + ) + } else { + None + }; let (snapshot, protected, fresh) = if let Some((id, transaction, time, protected)) = existing { @@ -144,6 +160,11 @@ impl Journal<'_> { ) .await?; if fresh { + absence + .as_ref() + .ok_or(OperationError::RecoveryRequired)? + .unchanged(&mut transaction, self.selected, request.operation_id()) + .await?; if now.observed_at() < snapshot.claimed_at() { return Err(WorkspaceError::Unavailable.into()); } @@ -235,6 +256,21 @@ impl Journal<'_> { } else { None }; + let absence = if retained.is_none() { + Some( + RetainedFacts::read( + self.connection, + self.selected, + request.binding(), + request.operation_id(), + Some(request.command_digest()), + self.crypto, + ) + .await?, + ) + } else { + None + }; let mut transaction = self .connection .begin_with("BEGIN IMMEDIATE") @@ -267,6 +303,11 @@ impl Journal<'_> { .await?; attempt::unchanged(&mut transaction, snapshot, protected).await?; } else { + absence + .as_ref() + .ok_or(OperationError::RecoveryRequired)? + .unchanged(&mut transaction, self.selected, request.operation_id()) + .await?; absent_claim( &mut transaction, self.selected, @@ -476,6 +517,21 @@ impl Journal<'_> { } else { None }; + let absence = if retained.as_ref().is_none_or(|value| value.4.is_none()) { + Some( + RetainedFacts::read( + self.connection, + self.selected, + request.binding(), + request.operation_id(), + Some(request.command_digest()), + self.crypto, + ) + .await?, + ) + } else { + None + }; let mut transaction = self .connection .begin_with("BEGIN IMMEDIATE") @@ -493,6 +549,11 @@ impl Journal<'_> { self.clock, ) .await?; + if let Some(absence) = &absence { + absence + .unchanged(&mut transaction, self.selected, request.operation_id()) + .await?; + } if let Some((snapshot, protected, operation, plan, captured)) = &retained { operation::unchanged( &mut transaction, diff --git a/crates/storage_sqlite/src/workspace/snapshot.rs b/crates/storage_sqlite/src/workspace/snapshot.rs @@ -207,6 +207,85 @@ impl RetainedGraph { } } } +/// Complete authenticated retained facts, read outside a transaction and +/// compared together inside it. Absence of an earlier phase is not safe to +/// report or replace while any later phase still depends on that history. +pub(super) struct RetainedFacts { + graph: RetainedGraph, + records: Records, + deliveries: DeliveryGraph, + observations: Observations, +} +impl RetainedFacts { + pub(super) async fn read( + connection: &mut SqliteConnection, + selected: &AttachmentInput, + binding: &WorkspaceBinding, + operation: OperationId, + digest: Option<CommandDigest>, + crypto: &WorkspaceCrypto, + ) -> Result<Self, OperationError> { + let graph = + RetainedGraph::read(connection, selected, binding, operation, digest, crypto).await?; + let records = Records::read(connection, selected, operation, &graph, crypto).await?; + let deliveries = + DeliveryGraph::read(connection, selected, operation, &graph, &records, crypto).await?; + let observations = + Observations::read(connection, &deliveries, selected, operation, crypto).await?; + Ok(Self { + graph, + records, + deliveries, + observations, + }) + } + pub(super) async fn unchanged( + &self, + connection: &mut SqliteConnection, + selected: &AttachmentInput, + operation: OperationId, + ) -> Result<(), OperationError> { + self.graph + .unchanged(connection, selected, operation) + .await?; + self.records + .unchanged(connection, selected, operation) + .await?; + self.deliveries + .unchanged(connection, selected, operation) + .await?; + self.observations + .unchanged(connection, selected, operation) + .await + } + fn into_snapshot( + self, + observed: UnixSeconds, + ) -> Result<Option<OperationSnapshot>, OperationError> { + self.graph + .into_snapshot(observed)? + .map(|snapshot| { + snapshot + .with_installation( + self.records.message.map(|value| value.report), + self.records + .work + .into_iter() + .map(|value| value.report) + .collect(), + )? + .with_delivery( + self.deliveries + .attempts + .iter() + .map(DeliveryAttemptSummary::from_attempt) + .collect(), + self.observations.reports, + ) + }) + .transpose() + } +} impl Journal<'_> { pub(super) async fn query_snapshot( &mut self, @@ -216,7 +295,7 @@ impl Journal<'_> { proof: AttachmentProof, ) -> Result<Option<OperationSnapshot>, OperationError> { let (record, grant, _) = self.access(&binding, &proof).await?; - let graph = RetainedGraph::read( + let facts = RetainedFacts::read( self.connection, self.selected, &binding, @@ -225,31 +304,6 @@ impl Journal<'_> { self.crypto, ) .await?; - let records = Records::read( - self.connection, - self.selected, - operation_id, - &graph, - self.crypto, - ) - .await?; - let deliveries = DeliveryGraph::read( - self.connection, - self.selected, - operation_id, - &graph, - &records, - self.crypto, - ) - .await?; - let observations = Observations::read( - self.connection, - &deliveries, - self.selected, - operation_id, - self.crypto, - ) - .await?; // Provider and signature verification work precedes the transaction. let mut transaction = self .connection @@ -268,16 +322,7 @@ impl Journal<'_> { self.clock, ) .await?; - graph - .unchanged(&mut transaction, self.selected, operation_id) - .await?; - records - .unchanged(&mut transaction, self.selected, operation_id) - .await?; - deliveries - .unchanged(&mut transaction, self.selected, operation_id) - .await?; - observations + facts .unchanged(&mut transaction, self.selected, operation_id) .await?; Ok::<_, OperationError>(observed.observed_at()) @@ -287,24 +332,7 @@ impl Journal<'_> { *self.uncertain = true; return Err(OperationError::RecoveryRequired); } - graph - .into_snapshot(checked?)? - .map(|snapshot| { - snapshot - .with_installation( - records.message.map(|value| value.report), - records.work.into_iter().map(|value| value.report).collect(), - )? - .with_delivery( - deliveries - .attempts - .iter() - .map(DeliveryAttemptSummary::from_attempt) - .collect(), - observations.reports, - ) - }) - .transpose() + facts.into_snapshot(checked?) } } async fn graph_counts( diff --git a/crates/storage_sqlite/src/workspace/tests/issuance_records.rs b/crates/storage_sqlite/src/workspace/tests/issuance_records.rs @@ -872,3 +872,111 @@ async fn actual_capture_turn_refuses_uncertainty_foreign_scope_and_fabricated_cl assert_eq!(retained.0.raw_json(), issued.evidence.raw_json()); database.close().await.unwrap(); } + +async fn installed_descendant_case(mode: u8) { + use radroots_storage::command::{InstallationOutcome, InstallationRequest}; + let issued = Issued::new().await; + let store = NativeWorkspace::open_existing( + &issued.path, + issued.selected.clone(), + issued.fixture.crypto(), + Arc::new(FixedClock(100)), + ) + .await + .unwrap(); + let binding = store + .authenticate(issued.selected.clone(), &issued.proof) + .await + .unwrap(); + let original = issued.attempt.bound_plan().prepared().identity(); + let plan = *issued.attempt.bound_plan().plan().digest(); + let copy = || { + issued + .proof + .with_secret(|raw| AttachmentProof::from_protected_input(raw).unwrap()) + }; + assert!(matches!( + store + .install_transition_and_outbox( + InstallationRequest::new( + binding.clone(), + original.operation_id(), + original.command_digest(), + plan + ), + copy() + ) + .await + .unwrap(), + InstallationOutcome::Committed(_) + )); + let mut database = issued.database().await; + for statement in [ + "DELETE FROM seal_evidence_parts", + "DELETE FROM seal_evidence", + "DELETE FROM signing_attempts", + ] { + if mode == 3 && statement == "DELETE FROM signing_attempts" { + continue; + } + sqlx::query(statement).execute(&mut database).await.unwrap(); + } + let messages: i64 = sqlx::query_scalar("SELECT count(*) FROM chat_messages") + .fetch_one(&mut database) + .await + .unwrap(); + let work: i64 = sqlx::query_scalar("SELECT count(*) FROM chat_publication_work") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!((messages, work), (1, 1)); + database.close().await.unwrap(); + let request = ClaimAttemptRequest::new( + binding, + original.operation_id(), + original.command_digest(), + plan, + participant(), + ); + let outcome = if mode == 0 { + match store.claim_attempt(request, copy()).await { + Ok(ClaimAttemptOutcome::Claimed(_)) => "claimed", + Ok(ClaimAttemptOutcome::Retained(_)) => "retained", + Ok(ClaimAttemptOutcome::Unknown(_)) => "unknown", + Err(error) => error.code(), + } + } else if mode == 1 { + match store.signing_attempt(request, copy()).await { + Ok(Some(_)) => "found", + Ok(None) => "absent", + Err(error) => error.code(), + } + } else { + match store.obtained_evidence(request, copy()).await { + Ok(Some(_)) => "found", + Ok(None) => "absent", + Err(error) => error.code(), + } + }; + store.close().await.unwrap(); + assert_eq!( + outcome, "recovery_required", + "retained T2 descendants must refuse false absence or a new claim after complete S loss" + ); +} +#[tokio::test] +async fn installed_descendants_prevent_fresh_claim_after_complete_s_loss() { + installed_descendant_case(0).await; +} +#[tokio::test] +async fn installed_descendants_prevent_false_claim_absence_after_complete_s_loss() { + installed_descendant_case(1).await; +} +#[tokio::test] +async fn installed_descendants_prevent_false_obtained_absence_after_complete_s_loss() { + installed_descendant_case(2).await; +} +#[tokio::test] +async fn installed_descendants_prevent_false_obtained_absence_with_retained_claim() { + installed_descendant_case(3).await; +}