lib

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

commit dbb74f8cbfc30aa6e3cb063fe4427a264efac543
parent c7da8dbcc9224f5d582b4a217dc301f2708afc6d
Author: triesap <tyson@radroots.org>
Date:   Mon, 19 Oct 2026 19:52:11 +0000

storage: Preserve browser signing claims and obtained output

- Share closed v1 metadata codecs while preserving native records
- Add browser S capture with retained proof and bounded read snapshots
- Refuse damaged state and retain original uncertain transactions
- Verify real browsers, native regressions, APIs and owning gates

Diffstat:
Mcontracts/api_baselines/radroots_storage.txt | 18++++++++++++++++++
Mcontracts/api_baselines/radroots_storage_indexeddb.wasm32_workspace.txt | 27+++++++++++++++++++++++++--
Acontracts/architecture/decisions/browser_workspace.v2.json | 177+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage/src/command/issuance.rs | 4++--
Mcrates/storage/src/command/protected.rs | 1+
Acrates/storage/src/command/protected/issuance.rs | 219+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_indexeddb/Cargo.toml | 2+-
Mcrates/storage_indexeddb/README.md | 35+++++++++++++++++++++++++++++++----
Mcrates/storage_indexeddb/src/browser.rs | 144+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Acrates/storage_indexeddb/src/browser/snapshot.rs | 347+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_indexeddb/src/lib.rs | 3+++
Acrates/storage_indexeddb/src/workspace/address.rs | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_indexeddb/src/workspace/crypto.rs | 10+++++-----
Acrates/storage_indexeddb/src/workspace/issuance.rs | 563+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_indexeddb/src/workspace/journal.rs | 132+++++++++++++++++++++++++++++++++++++++++++------------------------------------
Mcrates/storage_indexeddb/src/workspace/mod.rs | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mcrates/storage_indexeddb/src/workspace/plans.rs | 69+++++++++++++++++++++++++++++++++++++++++++++------------------------
Mcrates/storage_indexeddb/tests/browser/run.mjs | 185+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mcrates/storage_indexeddb/tests/browser/src/lib.rs | 4+++-
Acrates/storage_indexeddb/tests/browser/src/snapshot.rs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_indexeddb/tests/browser/src/workspace.rs | 111+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
Acrates/storage_indexeddb/tests/browser/src/workspace/issuance.rs | 316+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_indexeddb/tests/browser/src/workspace/plans.rs | 7++-----
Mcrates/storage_sqlite/src/workspace/attempt.rs | 89++++++++-----------------------------------------------------------------------
Mcrates/storage_sqlite/src/workspace/evidence.rs | 88+++++++++++--------------------------------------------------------------------
Mcrates/storage_sqlite/src/workspace/tests/issuance_records.rs | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
26 files changed, 2611 insertions(+), 349 deletions(-)

diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -759,6 +759,24 @@ pub fn radroots_storage::memory::MemoryStorage::verify_backup(&self, radroots_st pub mod radroots_storage::command pub use radroots_storage::command::ChatSigningPlan pub mod radroots_storage::command::protected +pub mod radroots_storage::command::protected::issuance +pub struct radroots_storage::command::protected::issuance::ClaimRecord(_) +impl radroots_storage::command::protected::issuance::ClaimRecord +pub fn radroots_storage::command::protected::issuance::ClaimRecord::capture(&radroots_storage::command::SigningAttempt) -> Self +pub fn radroots_storage::command::protected::issuance::ClaimRecord::decode(&[u8], radroots_storage::command::BoundSigningPlan, radroots_identity::key::PublicKey) -> core::result::Result<radroots_storage::command::SigningAttempt, radroots_storage::command::OperationError> +pub fn radroots_storage::command::protected::issuance::ClaimRecord::encode(&self) -> core::result::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>, radroots_storage::command::OperationError> +pub struct radroots_storage::command::protected::issuance::EvidenceManifest(_) +impl radroots_storage::command::protected::issuance::EvidenceManifest +pub const fn radroots_storage::command::protected::issuance::EvidenceManifest::attempt_id(&self) -> radroots_domain::identifier::SigningAttemptId +pub const fn radroots_storage::command::protected::issuance::EvidenceManifest::byte_count(&self) -> usize +pub fn radroots_storage::command::protected::issuance::EvidenceManifest::capture(&radroots_storage::command::SigningAttempt, &radroots_storage::command::SealEvidence, radroots_domain::identifier::TransactionId) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub fn radroots_storage::command::protected::issuance::EvidenceManifest::decode(&[u8], &radroots_storage::command::SigningAttempt) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub fn radroots_storage::command::protected::issuance::EvidenceManifest::encode(&self) -> core::result::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>, radroots_storage::command::OperationError> +pub const fn radroots_storage::command::protected::issuance::EvidenceManifest::event_id(&self) -> radroots_domain::identifier::EnvelopeEventId +pub const fn radroots_storage::command::protected::issuance::EvidenceManifest::evidence_digest(&self) -> &[u8; 32] +pub const fn radroots_storage::command::protected::issuance::EvidenceManifest::part_count(&self) -> usize +pub const fn radroots_storage::command::protected::issuance::EvidenceManifest::transaction_id(&self) -> radroots_domain::identifier::TransactionId +pub fn radroots_storage::command::protected::issuance::EvidenceManifest::verify(&self, &radroots_storage::command::SigningAttempt, &str) -> core::result::Result<radroots_storage::command::SealEvidence, radroots_storage::command::OperationError> pub mod radroots_storage::command::protected::plan pub struct radroots_storage::command::protected::plan::PlanManifest(_) impl radroots_storage::command::protected::plan::PlanManifest diff --git a/contracts/api_baselines/radroots_storage_indexeddb.wasm32_workspace.txt b/contracts/api_baselines/radroots_storage_indexeddb.wasm32_workspace.txt @@ -4,14 +4,20 @@ 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> +pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::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::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::query_signing_intents(&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> +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::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::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> pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::initialize_local_outbox(radroots_storage::workspace::local_outbox::LocalOutboxConfig, alloc::rc::Rc<dyn radroots_secrets::provider::SecretProvider>, radroots_secrets::id::SecretRef, radroots_secrets::provider::AccessPolicy, alloc::rc::Rc<dyn radroots_storage::workspace::WorkspaceClock>) -> core::result::Result<(Self, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof), radroots_storage::workspace::WorkspaceError> pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::open_existing(radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof, alloc::rc::Rc<dyn radroots_secrets::provider::SecretProvider>, radroots_secrets::id::SecretRef, radroots_secrets::provider::AccessPolicy, alloc::rc::Rc<dyn radroots_storage::workspace::WorkspaceClock>) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> +pub async fn radroots_storage_indexeddb::workspace::BrowserWorkspace::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 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 @@ -57,6 +63,9 @@ pub async fn radroots_storage_indexeddb::Database::compare_exchange(&self, radro pub async fn radroots_storage_indexeddb::Database::compare_exchange_checked(&self, radroots_storage_indexeddb::Batch, impl core::ops::function::Fn() -> bool + 'static) -> core::result::Result<radroots_storage_indexeddb::Commit, radroots_storage_indexeddb::Error> pub async fn radroots_storage_indexeddb::Database::get(&self, radroots_storage_indexeddb::RecordKey) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, radroots_storage_indexeddb::Error> pub async fn radroots_storage_indexeddb::Database::open(radroots_storage_indexeddb::Namespace, radroots_storage_indexeddb::OpenMode) -> core::result::Result<Self, radroots_storage_indexeddb::Error> +impl radroots_storage_indexeddb::Database +pub async fn radroots_storage_indexeddb::Database::compare_exchange_snapshot_checked(&self, radroots_storage_indexeddb::Batch, radroots_storage_indexeddb::ReadSnapshot, impl core::ops::function::Fn() -> bool + 'static) -> core::result::Result<radroots_storage_indexeddb::Commit, radroots_storage_indexeddb::Error> +pub async fn radroots_storage_indexeddb::Database::read_snapshot(&self, radroots_storage_indexeddb::RecordPrefix) -> core::result::Result<radroots_storage_indexeddb::ReadSnapshot, radroots_storage_indexeddb::Error> pub struct radroots_storage_indexeddb::Mutation impl radroots_storage_indexeddb::Mutation pub fn radroots_storage_indexeddb::Mutation::new(radroots_storage_indexeddb::RecordKey, core::option::Option<alloc::vec::Vec<u8>>, core::option::Option<alloc::vec::Vec<u8>>) -> core::result::Result<Self, radroots_storage_indexeddb::Error> @@ -66,10 +75,24 @@ pub struct radroots_storage_indexeddb::Namespace(_) impl radroots_storage_indexeddb::Namespace pub fn radroots_storage_indexeddb::Namespace::name(self) -> alloc::string::String pub const fn radroots_storage_indexeddb::Namespace::new(radroots_storage::event::SourceGeneration) -> Self +pub struct radroots_storage_indexeddb::ReadSnapshot +impl radroots_storage_indexeddb::ReadSnapshot +pub fn radroots_storage_indexeddb::ReadSnapshot::contains(&self, radroots_storage_indexeddb::RecordKey) -> bool +pub fn radroots_storage_indexeddb::ReadSnapshot::is_empty(&self) -> bool +pub fn radroots_storage_indexeddb::ReadSnapshot::keys(&self) -> impl core::iter::traits::iterator::Iterator<Item = radroots_storage_indexeddb::RecordKey> + '_ +pub fn radroots_storage_indexeddb::ReadSnapshot::len(&self) -> usize +pub fn radroots_storage_indexeddb::ReadSnapshot::verify(&self, radroots_storage_indexeddb::RecordKey, core::option::Option<&[u8]>) -> core::result::Result<(), radroots_storage_indexeddb::Error> +impl core::fmt::Debug for radroots_storage_indexeddb::ReadSnapshot +pub fn radroots_storage_indexeddb::ReadSnapshot::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage_indexeddb::RecordKey(_) impl radroots_storage_indexeddb::RecordKey pub const fn radroots_storage_indexeddb::RecordKey::as_bytes(&self) -> &[u8; 32] pub const fn radroots_storage_indexeddb::RecordKey::new([u8; 32]) -> Self +pub struct radroots_storage_indexeddb::RecordPrefix(_) +impl radroots_storage_indexeddb::RecordPrefix +pub const fn radroots_storage_indexeddb::RecordPrefix::new([u8; 16]) -> Self +impl core::fmt::Debug for radroots_storage_indexeddb::RecordPrefix +pub fn radroots_storage_indexeddb::RecordPrefix::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub const radroots_storage_indexeddb::BATCH_RECORDS_MAX: usize pub const radroots_storage_indexeddb::LIVE_BYTES_MAX: usize pub const radroots_storage_indexeddb::RECORD_BYTES_MAX: usize diff --git a/contracts/architecture/decisions/browser_workspace.v2.json b/contracts/architecture/decisions/browser_workspace.v2.json @@ -0,0 +1,177 @@ +{ + "schema_version": 1, + "contract_id": "radroots.storage.browser_workspace.v2", + "state": "implemented_verified_issuance_component", + "owner": "radroots_storage_indexeddb", + "feature": "workspace", + "target": "wasm32-unknown-unknown", + "shared_policy": "radroots_storage::workspace::local_outbox", + "native_policy_consumer": "radroots_storage_sqlite::workspace", + "shared_grant_wire_private": true, + "default_import_side_effects": false, + "scope": "fresh_unrelated_buyer_outbox", + "stock_authority": false, + "participant_key_is_workspace_proof": false, + "full_operation_journal_or_client_claim": false, + "storage": { + "namespace_domain": "radroots.browser.local_outbox.namespace.v2", + "grant_key_domain": "radroots.browser.local_outbox.grant.v1", + "create_and_existing_open_separate": true, + "existing_requires_selection_and_protected_proof": true, + "grant_acknowledgement": "actual_indexeddb_transaction_completion", + "missing_or_damaged_state_replacement_allowed": false, + "envelope_version": 2, + "fresh_key_and_nonce_per_grant_seal": true, + "native_context_and_wire_preserved": true, + "browser_grant_purpose": "radroots.browser.workspace.grant", + "browser_grant_payload_schema": "radroots.browser.workspace.grant.v2", + "predecessor_opening_migration_or_replacement": false + }, + "writer": { + "mechanism": "origin_scoped_web_locks", + "mode": "exclusive", + "if_available": true, + "fallback_allowed": false, + "accepted_jobs_serial": true, + "accepted_work_rust_owned": true, + "admission_and_active_write_check_lease": true, + "guard_refusal_aborts_whole_batch": true, + "close_order": [ + "stop_admission", + "drain_accepted_jobs", + "close_database", + "observe_released_lock_promise" + ], + "fresh_work_active_write_callback_rechecks_clock_and_expiry": true, + "obtained_capture_active_write_checks_retained_proof_and_lease": true + }, + "resources": { + "clear_grant_bytes_max": 16384, + "protected_grant_bytes_max": 32768, + "conservative_job_reservation_bytes": 4194304, + "live_job_bytes_max": 4194304, + "live_jobs_max_per_workspace": 1, + "setup_jobs_max_per_host_thread": 8, + "close_observers_max": 32, + "whole_browser_memory_bound_claim": false, + "setup_conservative_reservation_bytes": 524288, + "reservation_revision": "One accepted 4 MiB serial workspace job covers the complete 384 KiB T1 plan, S claims/obtained output and bounded read-set witnesses; the separate generic host reserves 2 MiB for each admitted scan. No whole-browser memory bound is claimed.", + "scoped_snapshot_records_max": 16384, + "scoped_snapshot_read_reservation_bytes": 2097152, + "atomic_mutation_records_max": 32 + }, + "qualification": { + "browsers": [ + "chromium", + "firefox", + "webkit" + ], + "main_thread_and_worker_required": true, + "actual_worker_termination_and_page_restart_required": true, + "native_workspace_and_ordinary_inquiry_regressions_required": true, + "final_phone_or_full_rcld_claim": false + }, + "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, + "absent_t0_complete_operation_prefix_compared_atomically": true + }, + "shared_plan_codec": "radroots_storage::command::protected::plan::PlanManifest", + "signing_plan_binding": { + "phase": "T1_only", + "complete_plan_clear_bytes_max": 393216, + "private_record_clear_bytes_max": 16384, + "part_count_max": 24, + "fixed_plan_slots_compared_atomically": 25, + "grant_t0_and_t1_batch_records": 31, + "batch_records_max": 32, + "original_preparation_transaction_and_window_retained": true, + "exact_retained_replay_before_fresh_deadline_or_entropy": true, + "independent_context_binds": [ + "workspace", + "operation", + "manifest_or_part_position", + "complete_plan_digest_for_parts" + ], + "unknown_completion": "retain_original_attempt_stop_admission_exact_reopen", + "missing_or_orphan_replacement_allowed": false, + "native_v1_wire_schema_and_context_preserved": true, + "participant_issuance_installation_or_delivery": false + }, + "supersedes_browser_profile": "radroots.storage.browser_workspace.v1", + "read_set": { + "owner_bound": true, + "clone_or_serialization": false, + "opaque_operation_prefix_bytes": 16, + "record_key_bytes": 32, + "witness": "ordered_key_length_sha256", + "every_decoded_record_matches_witness": true, + "same_transaction_exact_set_revalidation_before_mutations": true, + "provider_work_inside_transaction": false, + "readwrite_durability_requested_and_observed": "strict", + "physical_power_loss_guarantee_claim": false + }, + "operation_addresses": { + "prefix_domain": "radroots.browser.local_outbox.operation.prefix.v2", + "suffix": "closed_kind_recipient_position_attempt_position_part_observation_and_zero_reserved_bytes", + "reserved_families": [ + "preparation", + "plan", + "claim", + "obtained_seal", + "installation", + "publication_work", + "delivery_frame", + "delivery_observation", + "delivery_request_index" + ], + "reserved_not_yet_implemented_families": [ + "installation", + "publication_work", + "delivery_frame", + "delivery_observation", + "delivery_request_index" + ] + }, + "signing_claim": { + "phase": "S_claim", + "fresh_eligibility": "current_access_lease_clock_original_first_issue_window", + "retained_claim_authorizes_redispatch": false, + "original_attempt_transaction_intent_and_observation_preserved": true + }, + "obtained_capture": { + "phase": "S_capture", + "actual_original_claim_and_independent_proof_required": true, + "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 + }, + "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" +} diff --git a/crates/storage/src/command/issuance.rs b/crates/storage/src/command/issuance.rs @@ -199,7 +199,7 @@ impl fmt::Debug for SigningAttempt { /// Confirmed new claim, retained potential issuance, or anchored uncertainty. /// A data variant alone cannot qualify a custom adapter's commit or dispatch. pub enum ClaimAttemptOutcome { - /// Only this actual newly committed native result permits its owning + /// Only this actual newly committed store result permits its owning /// executor to proceed once after route/provider/current-access checks. Claimed(SigningAttempt), /// Never dispatch again merely because this original record was found. @@ -218,7 +218,7 @@ impl fmt::Debug for ClaimAttemptOutcome { } /// Independently authenticated exact obtained bytes, bound to reported claim -/// data but not proof of the backend's actual retained attempt. Native capture +/// data but not proof of the backend's actual retained attempt. Concrete capture /// must compare its own protected claim and plan before appending this evidence. pub struct SealEvidence { workspace_id: WorkspaceId, diff --git a/crates/storage/src/command/protected.rs b/crates/storage/src/command/protected.rs @@ -8,6 +8,7 @@ use radroots_domain::{ use serde::{Deserialize, Serialize}; use zeroize::Zeroizing; +pub mod issuance; pub mod plan; /// Maximum complete preparation, before a host splits private records. diff --git a/crates/storage/src/command/protected/issuance.rs b/crates/storage/src/command/protected/issuance.rs @@ -0,0 +1,219 @@ +//! Opaque original claim and obtained-evidence metadata for protecting hosts. +//! Decoding supplies no current access, actual commit or dispatch permission. +use super::plan::PART_BYTES; +use crate::command::{BoundSigningPlan, OperationError, SealEvidence, SigningAttempt}; +use core::num::NonZeroU64; +use radroots_domain::{ + CommandDigest, EnvelopeEventId, GrantId, OperationId, PublicKey, SigningAttemptId, + TransactionId, UnixSeconds, WorkspaceId, +}; +use serde::{Deserialize, Serialize}; +use zeroize::Zeroizing; + +#[derive(Serialize, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +struct ClaimWire { + version: u8, + workspace: WorkspaceId, + operation_id: OperationId, + command_digest: CommandDigest, + plan_digest: [u8; 32], + recipient: PublicKey, + attempt_id: SigningAttemptId, + transaction_id: TransactionId, + claimed_at: UnixSeconds, + intent_digest: [u8; 32], + deadline_unix_ms: u64, + preparation_transaction: TransactionId, + plan_transaction: TransactionId, + grant_id: GrantId, + expected_event: EnvelopeEventId, +} +impl ClaimWire { + fn new(attempt: &SigningAttempt) -> Self { + let plan = attempt.bound_plan(); + let prepared = plan.prepared(); + let identity = prepared.identity(); + Self { + version: 1, + workspace: identity.workspace_id(), + operation_id: identity.operation_id(), + command_digest: identity.command_digest(), + plan_digest: *plan.plan().digest(), + recipient: attempt.seal().recipient(), + attempt_id: attempt.attempt_id(), + transaction_id: attempt.transaction_id(), + claimed_at: attempt.claimed_at(), + intent_digest: *attempt.binding().digest(), + deadline_unix_ms: attempt.deadline_unix_ms().get(), + preparation_transaction: prepared.transaction_id(), + plan_transaction: plan.transaction_id(), + grant_id: prepared.request().binding().input().grant_id(), + expected_event: EnvelopeEventId::from_bytes(attempt.seal().event_id()), + } + } +} +/// Closed v1 claim codec. The concrete host still verifies its retained indexes +/// and acknowledges actual completion before reporting a newly claimed attempt. +pub struct ClaimRecord(ClaimWire); +impl ClaimRecord { + pub fn capture(attempt: &SigningAttempt) -> Self { + Self(ClaimWire::new(attempt)) + } + pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>, OperationError> { + encode(&self.0) + } + pub fn decode( + raw: &[u8], + bound: BoundSigningPlan, + recipient: PublicKey, + ) -> Result<SigningAttempt, OperationError> { + if raw.len() > PART_BYTES { + return Err(OperationError::RecoveryRequired); + } + let wire: ClaimWire = + serde_json::from_slice(raw).map_err(|_| OperationError::RecoveryRequired)?; + let attempt = SigningAttempt::from_committed_store( + bound, + recipient, + wire.attempt_id, + wire.transaction_id, + wire.claimed_at, + )?; + if wire != ClaimWire::new(&attempt) { + return Err(OperationError::RecoveryRequired); + } + Ok(attempt) + } +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct EvidenceWire { + version: u8, + workspace: WorkspaceId, + operation_id: OperationId, + command_digest: CommandDigest, + plan_digest: [u8; 32], + recipient: PublicKey, + attempt_id: SigningAttemptId, + claim_transaction: TransactionId, + intent_digest: [u8; 32], + event_id: EnvelopeEventId, + evidence_digest: [u8; 32], + transaction_id: TransactionId, + observed_at: Option<u64>, + byte_count: usize, + part_count: usize, +} +/// Complete authenticated obtained-seal metadata, preserving the original +/// optional observation. Each clear part remains independently bounded. +pub struct EvidenceManifest(EvidenceWire); +impl EvidenceManifest { + pub fn capture( + attempt: &SigningAttempt, + evidence: &SealEvidence, + transaction: TransactionId, + ) -> Result<Self, OperationError> { + if !evidence.matches_attempt(attempt) { + return Err(OperationError::InvalidEvidence); + } + let result = Self(EvidenceWire { + version: 1, + workspace: evidence.workspace_id(), + operation_id: evidence.operation_id(), + command_digest: evidence.command_digest(), + plan_digest: *evidence.plan_digest(), + recipient: evidence.recipient(), + attempt_id: evidence.attempt_id(), + claim_transaction: attempt.transaction_id(), + intent_digest: *evidence.intent().digest(), + event_id: evidence.event_id(), + evidence_digest: *evidence.digest(), + transaction_id: transaction, + observed_at: evidence.observed_at_unix_ms().map(NonZeroU64::get), + byte_count: evidence.raw_json().len(), + part_count: evidence.raw_json().len().div_ceil(PART_BYTES), + }); + result.validate(attempt)?; + Ok(result) + } + pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>, OperationError> { + encode(&self.0) + } + pub fn decode(raw: &[u8], attempt: &SigningAttempt) -> Result<Self, OperationError> { + if raw.len() > PART_BYTES { + return Err(OperationError::RecoveryRequired); + } + let result = + Self(serde_json::from_slice(raw).map_err(|_| OperationError::RecoveryRequired)?); + result.validate(attempt)?; + Ok(result) + } + fn validate(&self, attempt: &SigningAttempt) -> Result<(), OperationError> { + let w = &self.0; + let bound = attempt.bound_plan(); + let identity = bound.prepared().identity(); + if w.version != 1 + || w.workspace != identity.workspace_id() + || w.operation_id != identity.operation_id() + || w.command_digest != identity.command_digest() + || &w.plan_digest != bound.plan().digest() + || w.recipient != attempt.seal().recipient() + || w.attempt_id != attempt.attempt_id() + || w.claim_transaction != attempt.transaction_id() + || &w.intent_digest != attempt.binding().digest() + || w.event_id.as_bytes() != &attempt.seal().event_id() + || !(1..=65536).contains(&w.byte_count) + || !(1..=4).contains(&w.part_count) + || w.byte_count.div_ceil(PART_BYTES) != w.part_count + || w.observed_at + .is_some_and(|t| t == 0 || t > 253_402_300_799_999) + { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } + pub const fn transaction_id(&self) -> TransactionId { + self.0.transaction_id + } + pub const fn attempt_id(&self) -> SigningAttemptId { + self.0.attempt_id + } + pub const fn event_id(&self) -> EnvelopeEventId { + self.0.event_id + } + pub const fn evidence_digest(&self) -> &[u8; 32] { + &self.0.evidence_digest + } + pub const fn byte_count(&self) -> usize { + self.0.byte_count + } + pub const fn part_count(&self) -> usize { + self.0.part_count + } + pub fn verify( + &self, + attempt: &SigningAttempt, + raw: &str, + ) -> Result<SealEvidence, OperationError> { + self.validate(attempt)?; + if raw.len() != self.byte_count() { + return Err(OperationError::RecoveryRequired); + } + let evidence = + SealEvidence::verify(attempt, raw, self.0.observed_at.and_then(NonZeroU64::new)) + .map_err(|_| OperationError::RecoveryRequired)?; + if evidence.digest() != self.evidence_digest() { + return Err(OperationError::RecoveryRequired); + } + Ok(evidence) + } +} +fn encode(value: &impl Serialize) -> Result<Zeroizing<Vec<u8>>, OperationError> { + let raw = + Zeroizing::new(serde_json::to_vec(value).map_err(|_| OperationError::RecoveryRequired)?); + if raw.len() > PART_BYTES { + return Err(OperationError::RecoveryRequired); + } + Ok(raw) +} diff --git a/crates/storage_indexeddb/Cargo.toml b/crates/storage_indexeddb/Cargo.toml @@ -28,7 +28,7 @@ futures = { workspace = true } js-sys = { workspace = true } wasm-bindgen = { workspace = true } wasm-bindgen-futures = { workspace = true } -web-sys = { workspace = true, features = ["Crypto", "DomException", "DomStringList", "Event", "EventTarget", "IdbDatabase", "IdbFactory", "IdbObjectStore", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "IdbVersionChangeEvent"] } +web-sys = { workspace = true, features = ["Crypto", "DomException", "DomStringList", "Event", "EventTarget", "IdbCursor", "IdbCursorWithValue", "IdbDatabase", "IdbFactory", "IdbKeyRange", "IdbObjectStore", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "IdbVersionChangeEvent"] } [lints] workspace = true diff --git a/crates/storage_indexeddb/README.md b/crates/storage_indexeddb/README.md @@ -28,7 +28,7 @@ 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; +admission until exact reopening. Queries compare the complete witnessed operation record set; missing, orphaned or damaged parts never trigger replacement. These methods provide T0; they do not issue signatures, install messages or deliver them. @@ -43,6 +43,29 @@ or damaged state refuses, including T0 absence with retained plan records. Unknown completion retains the original attempt and stops admission. T1 stores complete captured signing data; participant issuance remains a separate phase. +The v2 owner claims original per-recipient signing attempts and appends already +obtained, verified signed seals. A retained claim authorizes no redispatch. +Each claim binds its original preparation, plan, intent, recipient, deadline and +transaction. Captured output retains its exact bytes and optional original +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. + +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 +decoded value must match its witness. The complete set is checked again in the +same real transaction as bounded mutations, detecting insertion, deletion and +replacement. Only synchronous bounded comparisons run in transaction callbacks; +providers and signing stay outside. The 32-mutation and 4 MiB live-input limits +remain unchanged. Exact-key cursor lookup distinguishes absent keys from foreign +stored `undefined` values. Readwrite transactions request and check `strict` +durability, which is a browser hint rather than a physical power-loss guarantee. +Observed asynchronous request errors remain failures even if their default abort +is prevented and the browser subsequently completes the transaction. + 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 @@ -57,8 +80,11 @@ Clear grants are bounded to 16 KiB and their protected representation to 32 KiB. `compare_exchange_checked` runs a trusted host's synchronous eligibility check in active write callbacks, after asynchronous crypto completes. Refusal aborts the whole transaction. The workspace uses it to recheck current expiry/clock -and writer ownership before grant writes. Native and browser hosts share the -same grant context; generic authenticated envelope v2 remains unchanged. +and writer ownership before grant writes. Browser workspace v2 has its own +namespace and independently expected grant context. Earlier namespaces are +preserved and refused without migration or replacement. Native grant wire and +context, shared private codecs and generic authenticated envelope v2 remain +unchanged. No JavaScript object or key handle is exposed by the workspace API. The Web Lock follows the [standard holding and released promise lifecycle](https://www.w3.org/TR/web-locks/#locks). Browser storage can be evicted; opening an absent namespace reports its absence. @@ -70,7 +96,8 @@ The standalone fixture at `tests/browser/Cargo.toml` builds the real host to WASM. Generate its web bindings with the `wasm-bindgen` version matching that fixture's lockfile, using an external output directory and the output name `fixture`. Run `tests/browser/run.mjs` with an installed Playwright package -directory, that output directory, and `chromium`, `firefox`, or `webkit`. +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 --`. diff --git a/crates/storage_indexeddb/src/browser.rs b/crates/storage_indexeddb/src/browser.rs @@ -3,7 +3,7 @@ use super::{ RecordKey, }; use futures::channel::oneshot; -use js_sys::{Reflect, Uint8Array}; +use js_sys::{ArrayBuffer, Function, Object, Reflect, Uint8Array}; use std::{ cell::{Cell, RefCell}, future::poll_fn, @@ -13,10 +13,15 @@ use std::{ use wasm_bindgen::{JsCast, JsValue, closure::Closure}; use wasm_bindgen_futures::spawn_local; use web_sys::{ - Event, IdbDatabase, IdbFactory, IdbObjectStore, IdbOpenDbRequest, IdbRequest, IdbTransaction, - IdbTransactionMode, + Event, IdbCursorWithValue, IdbDatabase, IdbFactory, IdbKeyRange, IdbObjectStore, + IdbOpenDbRequest, IdbRequest, IdbTransaction, IdbTransactionMode, }; +#[cfg(feature = "workspace")] +mod snapshot; +#[cfg(feature = "workspace")] +pub use snapshot::{ReadSnapshot, RecordPrefix}; + const STORE: &str = "records"; const WORK_MAX: usize = 32; type EventCallback = Closure<dyn FnMut(Event)>; @@ -49,6 +54,70 @@ fn bytes(value: JsValue) -> Result<Option<Vec<u8>>, Error> { Ok(Some(value.to_vec())) } +fn record_key(raw: JsValue) -> Result<RecordKey, Error> { + let view = if let Some(view) = raw.dyn_ref::<Uint8Array>() { + view.clone() + } else if raw.is_instance_of::<ArrayBuffer>() { + Uint8Array::new(&raw) + } else { + return Err(Error::CorruptRecord); + }; + if view.length() != 32 { + return Err(Error::CorruptRecord); + } + let mut value = [0; 32]; + view.copy_to(&mut value); + Ok(RecordKey::new(value)) +} +fn lookup(store: &IdbObjectStore, record: RecordKey) -> Result<IdbRequest, JsValue> { + let range = IdbKeyRange::only(&key(record))?; + store.open_cursor_with_range(range.as_ref()) +} +fn lookup_value(request: &IdbRequest, expected: RecordKey) -> Result<Option<Vec<u8>>, Error> { + let value = request.result().map_err(classify)?; + if value.is_null() { + return Ok(None); + } + let cursor = value + .dyn_into::<IdbCursorWithValue>() + .map_err(|_| Error::CorruptRecord)?; + if record_key(cursor.key().map_err(classify)?)? != expected { + return Err(Error::CorruptRecord); + } + // A cursor distinguishes absent keys from stored undefined. Undefined is + // foreign data, never permission to overwrite an allegedly missing value. + let value = bytes(cursor.value().map_err(classify)?)?.ok_or(Error::CorruptRecord)?; + Ok(Some(value)) +} + +fn write_transaction(db: &IdbDatabase) -> Result<IdbTransaction, Error> { + // The pinned web-sys options binding requires a global unstable cfg. Keep + // that compiler input unchanged and use the checked standard host method. + let options = Object::new(); + if !Reflect::set(&options, &"durability".into(), &"strict".into()).map_err(classify)? { + return Err(Error::Unavailable); + } + let method = Reflect::get(db, &"transaction".into()) + .map_err(classify)? + .dyn_into::<Function>() + .map_err(|_| Error::Unavailable)?; + let tx = method + .call3(db, &STORE.into(), &"readwrite".into(), &options) + .map_err(classify)? + .dyn_into::<IdbTransaction>() + .map_err(|_| Error::Unavailable)?; + if Reflect::get(&tx, &"durability".into()) + .map_err(classify)? + .as_string() + .as_deref() + != Some("strict") + { + let _ = tx.abort(); + return Err(Error::Unavailable); + } + Ok(tx) +} + struct State { db: IdbDatabase, closing: Cell<bool>, @@ -181,13 +250,9 @@ impl Database { let (send, observe) = oneshot::channel(); spawn_local(async move { let owner = work; - let result = match owner - .state - .db - .transaction_with_str_and_mode(STORE, IdbTransactionMode::Readwrite) - { + let result = match write_transaction(&owner.state.db) { Ok(tx) => exchange(tx, batch, guard).await, - Err(error) => Err(classify(error)), + Err(error) => Err(error), }; let _ = send.send(result); }); @@ -366,6 +431,7 @@ struct Completion { result: oneshot::Receiver<Result<(), Error>>, _complete: Closure<dyn FnMut(Event)>, _abort: Closure<dyn FnMut(Event)>, + _error: Closure<dyn FnMut(Event)>, } impl Completion { fn new(tx: IdbTransaction, failure: Rc<Cell<Option<Error>>>) -> Self { @@ -389,6 +455,7 @@ impl Completion { }; let abort = { let tx = tx.clone(); + let failure = failure.clone(); Closure::new(move |_: Event| { let error = failure.get().unwrap_or_else(|| { tx.error() @@ -406,13 +473,38 @@ impl Completion { } }) }; + let error = { + let tx = tx.clone(); + let failure = failure.clone(); + Closure::new(move |event: Event| { + let quota = event + .target() + .and_then(|target| target.dyn_into::<IdbRequest>().ok()) + .and_then(|request| request.error().ok().flatten()) + .is_some_and(|error| error.name() == "QuotaExceededError"); + // Remember asynchronous request failure even if another host + // listener prevents its default abort. Unexpected completion + // then remains unknown, never a successful partial batch. + refuse( + &tx, + &failure, + if quota { + Error::Capacity + } else { + Error::Aborted + }, + ); + }) + }; tx.set_oncomplete(Some(complete.as_ref().unchecked_ref())); tx.set_onabort(Some(abort.as_ref().unchecked_ref())); + tx.set_onerror(Some(error.as_ref().unchecked_ref())); Self { tx, result, _complete: complete, _abort: abort, + _error: error, } } async fn wait(&mut self) -> Result<(), Error> { @@ -425,6 +517,7 @@ impl Drop for Completion { fn drop(&mut self) { self.tx.set_oncomplete(None); self.tx.set_onabort(None); + self.tx.set_onerror(None); } } struct RequestHandler { @@ -448,7 +541,7 @@ async fn read(tx: IdbTransaction, record: RecordKey) -> Result<Option<Vec<u8>>, let value = Rc::new(RefCell::new(None)); let request = match tx .object_store(STORE) - .and_then(|store| store.get(&key(record))) + .and_then(|store| lookup(&store, record)) { Ok(request) => request, Err(error) => { @@ -461,12 +554,10 @@ async fn read(tx: IdbTransaction, record: RecordKey) -> Result<Option<Vec<u8>>, let request = request.clone(); let value = value.clone(); let tx = tx.clone(); - Closure::new( - move |_: Event| match request.result().map_err(classify).and_then(bytes) { - Ok(result) => *value.borrow_mut() = Some(result), - Err(error) => refuse(&tx, &failure, error), - }, - ) + Closure::new(move |_: Event| match lookup_value(&request, record) { + Ok(result) => *value.borrow_mut() = Some(result), + Err(error) => refuse(&tx, &failure, error), + }) }; request.set_onsuccess(Some(success.as_ref().unchecked_ref())); let _handler = RequestHandler { @@ -493,13 +584,26 @@ async fn exchange( return Err(Error::CommitUnknown); } }; + queue_batch(&store, &tx, batch, guard, &failure, &mut handlers); + completion.wait().await?; + Ok(Commit { records: count }) +} + +fn queue_batch( + store: &IdbObjectStore, + tx: &IdbTransaction, + batch: Batch, + guard: Option<Rc<dyn Fn() -> bool>>, + failure: &Rc<Cell<Option<Error>>>, + handlers: &mut Vec<RequestHandler>, +) { // All reads are queued in this active turn. Each callback queues its write // synchronously; any later conflict aborts every earlier write atomically. for entry in batch.entries { - let request = match store.get(&key(entry.key)) { + let request = match lookup(store, entry.key) { Ok(request) => request, Err(error) => { - refuse(&tx, &failure, classify(error)); + refuse(tx, failure, classify(error)); break; } }; @@ -528,11 +632,9 @@ async fn exchange( _success: success, }); } - completion.wait().await?; - Ok(Commit { records: count }) } fn apply(store: &IdbObjectStore, request: &IdbRequest, entry: &Mutation) -> Result<(), Error> { - let actual = bytes(request.result().map_err(classify)?)?; + let actual = lookup_value(request, entry.key)?; if actual != entry.expected { return Err(Error::Conflict); } diff --git a/crates/storage_indexeddb/src/browser/snapshot.rs b/crates/storage_indexeddb/src/browser/snapshot.rs @@ -0,0 +1,347 @@ +//! Bounded opaque read witnesses; no crypto provider runs in a transaction. +use super::{ + Batch, Commit, Completion, Database, Error, RECORD_BYTES_MAX, RecordKey, RequestHandler, STORE, + State, bytes, classify, queue_batch, record_key, refuse, write_transaction, +}; +use futures::channel::oneshot; +use js_sys::Uint8Array; +use sha2::{Digest, Sha256}; +use std::{ + cell::{Cell, RefCell}, + fmt, + mem::size_of, + rc::{Rc, Weak}, +}; +use wasm_bindgen::{JsCast, JsValue, closure::Closure}; +use wasm_bindgen_futures::spawn_local; +use web_sys::{ + Event, IdbCursorWithValue, IdbKeyRange, IdbObjectStore, IdbRequest, IdbTransaction, + IdbTransactionMode, +}; + +const ROWS_MAX: usize = 16_384; +const SCAN_RESERVATION: usize = 2 * 1024 * 1024; + +/// Opaque binary-key prefix. It carries no workspace or business permission. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct RecordPrefix([u8; 16]); +impl RecordPrefix { + pub const fn new(bytes: [u8; 16]) -> Self { + Self(bytes) + } + fn range(self) -> Result<IdbKeyRange, Error> { + let lower: JsValue = Uint8Array::from(self.0.as_slice()).into(); + let mut upper = self.0; + for i in (0..upper.len()).rev() { + if upper[i] != u8::MAX { + upper[i] += 1; + let upper: JsValue = Uint8Array::from(upper.as_slice()).into(); + return IdbKeyRange::bound_with_lower_open_and_upper_open( + &lower, &upper, false, true, + ) + .map_err(classify); + } + upper[i] = 0; + } + IdbKeyRange::lower_bound(&lower).map_err(classify) + } + fn contains(self, key: RecordKey) -> bool { + key.as_bytes()[..16] == self.0 + } +} +impl fmt::Debug for RecordPrefix { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("RecordPrefix(<redacted>)") + } +} +struct Witness { + key: RecordKey, + length: usize, + digest: [u8; 32], +} +// Vec growth, one bounded record, and callback scaffolding fit the reservation. +const _: () = assert!( + size_of::<Witness>() * ROWS_MAX * 3 / 2 + 2 * RECORD_BYTES_MAX + 4096 <= SCAN_RESERVATION +); + +/// Exact completed read set on one live connection. No serialization or clone +/// can turn it into a portable authorization token. Values are not retained. +pub struct ReadSnapshot { + owner: Weak<State>, + prefix: RecordPrefix, + rows: Vec<Witness>, +} +impl ReadSnapshot { + pub fn len(&self) -> usize { + self.rows.len() + } + pub fn is_empty(&self) -> bool { + self.rows.is_empty() + } + pub fn contains(&self, key: RecordKey) -> bool { + self.rows.binary_search_by_key(&key, |row| row.key).is_ok() + } + pub fn keys(&self) -> impl Iterator<Item = RecordKey> + '_ { + self.rows.iter().map(|row| row.key) + } + /// Binds each value decoded outside the transaction to the completed view. + pub fn verify(&self, key: RecordKey, actual: Option<&[u8]>) -> Result<(), Error> { + if !self.prefix.contains(key) { + return Err(Error::InvalidInput); + } + match (self.rows.binary_search_by_key(&key, |row| row.key), actual) { + (Err(_), None) => Ok(()), + (Ok(i), Some(raw)) => matches(&self.rows[i], raw), + _ => Err(Error::Conflict), + } + } + fn reservation(&self) -> usize { + size_of::<Self>() + self.rows.capacity() * size_of::<Witness>() + } +} +impl fmt::Debug for ReadSnapshot { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ReadSnapshot(<redacted>)") + } +} +fn matches(witness: &Witness, raw: &[u8]) -> Result<(), Error> { + if raw.len() > RECORD_BYTES_MAX { + return Err(Error::CorruptRecord); + } + if raw.len() != witness.length || <[u8; 32]>::from(Sha256::digest(raw)) != witness.digest { + return Err(Error::Conflict); + } + Ok(()) +} +fn cursor_key(cursor: &IdbCursorWithValue, prefix: RecordPrefix) -> Result<RecordKey, Error> { + let key = record_key(cursor.key().map_err(classify)?)?; + if !prefix.contains(key) { + return Err(Error::CorruptRecord); + } + Ok(key) +} +fn start_cursor(store: &IdbObjectStore, prefix: RecordPrefix) -> Result<IdbRequest, Error> { + store + .open_cursor_with_range(prefix.range()?.as_ref()) + .map_err(classify) +} +impl Database { + /// Captures bounded key/length/digest witnesses, observing real completion. + /// Accepted scanning survives loss of its observer and participates in close. + pub async fn read_snapshot(&self, prefix: RecordPrefix) -> Result<ReadSnapshot, Error> { + let work = self.state.admit(SCAN_RESERVATION)?; + let (send, observe) = oneshot::channel(); + spawn_local(async move { + let owner = work; + let result = match owner + .state + .db + .transaction_with_str_and_mode(STORE, IdbTransactionMode::Readonly) + { + Ok(tx) => scan(tx, Rc::downgrade(&owner.state), prefix).await, + Err(error) => Err(classify(error)), + }; + let _ = send.send(result); + }); + observe.await.unwrap_or(Err(Error::CommitUnknown)) + } + /// Rechecks the complete witnessed set before any batch write, in the same + /// real transaction. All cursor and mutation callbacks recheck eligibility. + pub async fn compare_exchange_snapshot_checked( + &self, + batch: Batch, + snapshot: ReadSnapshot, + guard: impl Fn() -> bool + 'static, + ) -> Result<Commit, Error> { + if !snapshot + .owner + .upgrade() + .is_some_and(|owner| Rc::ptr_eq(&owner, &self.state)) + { + return Err(Error::InvalidInput); + } + let reservation = batch + .bytes + .checked_add(snapshot.reservation()) + .ok_or(Error::Capacity)?; + let work = self.state.admit(reservation)?; + let (send, observe) = oneshot::channel(); + spawn_local(async move { + let owner = work; + let result = match write_transaction(&owner.state.db) { + Ok(tx) => checked_exchange(tx, batch, snapshot, Rc::new(guard)).await, + Err(error) => Err(error), + }; + let _ = send.send(result); + }); + observe.await.unwrap_or(Err(Error::CommitUnknown)) + } +} +async fn scan( + tx: IdbTransaction, + owner: Weak<State>, + prefix: RecordPrefix, +) -> Result<ReadSnapshot, Error> { + let failure = Rc::new(Cell::new(None)); + let mut completion = Completion::new(tx.clone(), failure.clone()); + let rows = Rc::new(RefCell::new(Vec::<Witness>::new())); + let done = Rc::new(Cell::new(false)); + let request = match tx + .object_store(STORE) + .map_err(classify) + .and_then(|store| start_cursor(&store, prefix)) + { + Ok(request) => request, + Err(error) => { + refuse(&tx, &failure, error); + completion.wait().await?; + return Err(Error::CommitUnknown); + } + }; + let success = { + let request = request.clone(); + let tx = tx.clone(); + let failure = failure.clone(); + let rows = rows.clone(); + let done = done.clone(); + Closure::new(move |_: Event| { + if failure.get().is_some() { + return; + } + let result = (|| { + let value = request.result().map_err(classify)?; + if value.is_null() { + done.set(true); + return Ok(()); + } + let cursor = value + .dyn_into::<IdbCursorWithValue>() + .map_err(|_| Error::CorruptRecord)?; + let key = cursor_key(&cursor, prefix)?; + let mut rows = rows.borrow_mut(); + if rows.len() >= ROWS_MAX { + return Err(Error::Capacity); + } + if rows.last().is_some_and(|previous| previous.key >= key) { + return Err(Error::CorruptRecord); + } + let raw = bytes(cursor.value().map_err(classify)?)?.ok_or(Error::CorruptRecord)?; + rows.push(Witness { + key, + length: raw.len(), + digest: Sha256::digest(&raw).into(), + }); + drop(rows); + cursor.continue_().map_err(classify) + })(); + if let Err(error) = result { + refuse(&tx, &failure, error); + } + }) + }; + request.set_onsuccess(Some(success.as_ref().unchecked_ref())); + let _handler = RequestHandler { + request, + _success: success, + }; + completion.wait().await?; + if !done.get() { + return Err(Error::CommitUnknown); + } + let rows = std::mem::take(&mut *rows.borrow_mut()); + Ok(ReadSnapshot { + owner, + prefix, + rows, + }) +} +async fn checked_exchange( + tx: IdbTransaction, + batch: Batch, + snapshot: ReadSnapshot, + guard: Rc<dyn Fn() -> bool>, +) -> Result<Commit, Error> { + let failure = Rc::new(Cell::new(None)); + let mut completion = Completion::new(tx.clone(), failure.clone()); + let count = batch.entries.len(); + let store = match tx.object_store(STORE) { + Ok(store) => store, + Err(error) => { + refuse(&tx, &failure, classify(error)); + completion.wait().await?; + return Err(Error::CommitUnknown); + } + }; + let request = match start_cursor(&store, snapshot.prefix) { + Ok(request) => request, + Err(error) => { + refuse(&tx, &failure, error); + completion.wait().await?; + return Err(Error::CommitUnknown); + } + }; + let handlers = Rc::new(RefCell::new(Vec::new())); + let batch = Rc::new(RefCell::new(Some(batch))); + let queued = Rc::new(Cell::new(false)); + let success = { + let request = request.clone(); + let tx = tx.clone(); + let failure = failure.clone(); + let queued = queued.clone(); + let handlers = handlers.clone(); + let guard = guard.clone(); + let mut seen = 0; + Closure::new(move |_: Event| { + if failure.get().is_some() { + return; + } + let result = (|| { + if !guard() { + return Err(Error::GuardRefused); + } + let value = request.result().map_err(classify)?; + if value.is_null() { + if seen != snapshot.rows.len() { + return Err(Error::Conflict); + } + let batch = batch.borrow_mut().take().ok_or(Error::CorruptRecord)?; + queue_batch( + &store, + &tx, + batch, + Some(guard.clone()), + &failure, + &mut handlers.borrow_mut(), + ); + queued.set(true); + return Ok(()); + } + let cursor = value + .dyn_into::<IdbCursorWithValue>() + .map_err(|_| Error::CorruptRecord)?; + let key = cursor_key(&cursor, snapshot.prefix)?; + let expected = snapshot.rows.get(seen).ok_or(Error::Conflict)?; + if key != expected.key { + return Err(Error::Conflict); + } + let raw = bytes(cursor.value().map_err(classify)?)?.ok_or(Error::CorruptRecord)?; + matches(expected, &raw)?; + seen += 1; + cursor.continue_().map_err(classify) + })(); + if let Err(error) = result { + refuse(&tx, &failure, error); + } + }) + }; + request.set_onsuccess(Some(success.as_ref().unchecked_ref())); + let _cursor = RequestHandler { + request, + _success: success, + }; + completion.wait().await?; + if !queued.get() { + return Err(Error::CommitUnknown); + } + Ok(Commit { records: count }) +} diff --git a/crates/storage_indexeddb/src/lib.rs b/crates/storage_indexeddb/src/lib.rs @@ -10,6 +10,9 @@ mod browser; pub use browser::Database; #[cfg(all(feature = "workspace", target_arch = "wasm32"))] +pub use browser::{ReadSnapshot, RecordPrefix}; + +#[cfg(all(feature = "workspace", target_arch = "wasm32"))] pub mod workspace; /// Maximum opaque record size; private codecs must enforce their lower limit. diff --git a/crates/storage_indexeddb/src/workspace/address.rs b/crates/storage_indexeddb/src/workspace/address.rs @@ -0,0 +1,88 @@ +//! Closed v2 private record positions under one opaque operation prefix. +use super::{RecordKey, State}; +use crate::{ReadSnapshot, RecordPrefix}; +use radroots_domain::OperationId; +use radroots_storage::command::OperationError; +use sha2::{Digest, Sha256}; + +pub(super) const PREPARED: u8 = 1; +pub(super) const PLAN: u8 = 2; +pub(super) const CLAIM: u8 = 3; +pub(super) const EVIDENCE: u8 = 4; + +fn prefix_bytes(operation: OperationId) -> [u8; 16] { + let digest = Sha256::new() + .chain_update(b"radroots.browser.local_outbox.operation.prefix.v2\0") + .chain_update(operation.as_bytes()) + .finalize(); + let mut bytes = [0; 16]; + bytes.copy_from_slice(&digest[..16]); + bytes +} +pub(super) fn prefix(operation: OperationId) -> RecordPrefix { + RecordPrefix::new(prefix_bytes(operation)) +} +pub(super) fn key(operation: OperationId, kind: u8, recipient: u8, part: u8) -> RecordKey { + let mut bytes = [0; 32]; + bytes[..16].copy_from_slice(&prefix_bytes(operation)); + bytes[16] = kind; + bytes[17] = recipient; + bytes[20] = part; + RecordKey::new(bytes) +} +pub(super) fn fields(key: RecordKey) -> Result<(u8, u8, u8), OperationError> { + let bytes = key.as_bytes(); + let kind = bytes[16]; + let recipient = bytes[17]; + let part = bytes[20]; + if bytes[18..20] + .iter() + .chain(bytes[21..].iter()) + .any(|b| *b != 0) + || match kind { + PREPARED => recipient != 0 || part > 4, + PLAN => recipient != 0 || part > 24, + CLAIM => recipient > 1 || part != 0, + EVIDENCE => recipient > 1 || part > 4, + // Later reserved families remain unsupported until their actual + // implementations and proving cohort land. Never ignore them. + _ => true, + } + { + return Err(OperationError::RecoveryRequired); + } + Ok((kind, recipient, part)) +} +impl State { + pub(super) async fn read_view( + &self, + operation: OperationId, + ) -> Result<ReadSnapshot, OperationError> { + let view = self + .db + .read_snapshot(prefix(operation)) + .await + .map_err(super::journal::storage_error)?; + for key in view.keys() { + fields(key)?; + } + Ok(view) + } + pub(super) async fn read_view_key( + &self, + view: &ReadSnapshot, + key: RecordKey, + ) -> Result<Option<Vec<u8>>, OperationError> { + if !view.contains(key) { + return Ok(None); + } + let value = self + .db + .get(key) + .await + .map_err(super::journal::storage_error)?; + view.verify(key, value.as_deref()) + .map_err(super::journal::storage_error)?; + Ok(value) + } +} diff --git a/crates/storage_indexeddb/src/workspace/crypto.rs b/crates/storage_indexeddb/src/workspace/crypto.rs @@ -7,9 +7,7 @@ use radroots_secrets::{ provider::SecretProvider, wrapping::SecretMaterial, }; -use radroots_storage::workspace::local_outbox::{ - GRANT_ENVELOPE_PURPOSE, GRANT_PAYLOAD_SCHEMA, grant_envelope_subject, -}; +use radroots_storage::workspace::local_outbox::grant_envelope_subject; use radroots_storage::workspace::{WorkspaceError, local_outbox::GRANT_BYTES_MAX}; use wasm_bindgen::{JsCast, JsValue}; use zeroize::Zeroizing; @@ -28,10 +26,12 @@ pub(super) fn random<const N: usize>() -> Result<Zeroizing<[u8; N]>, WorkspaceEr } fn context(workspace: WorkspaceId, grant: GrantId) -> Result<EnvelopeContext, WorkspaceError> { Ok(EnvelopeContext::new( - EnvelopePurpose::parse(GRANT_ENVELOPE_PURPOSE).map_err(|_| WorkspaceError::InvalidInput)?, + EnvelopePurpose::parse("radroots.browser.workspace.grant") + .map_err(|_| WorkspaceError::InvalidInput)?, EnvelopeSubject::parse("workspace_grant", grant_envelope_subject(workspace, grant)) .map_err(|_| WorkspaceError::InvalidInput)?, - PayloadSchemaId::parse(GRANT_PAYLOAD_SCHEMA).map_err(|_| WorkspaceError::InvalidInput)?, + PayloadSchemaId::parse("radroots.browser.workspace.grant.v2") + .map_err(|_| WorkspaceError::InvalidInput)?, )) } pub(super) async fn seal( diff --git a/crates/storage_indexeddb/src/workspace/issuance.rs b/crates/storage_indexeddb/src/workspace/issuance.rs @@ -0,0 +1,563 @@ +//! Real S claims and append-only obtained output; no signer runs under storage. +use super::journal::{OperationChange, Records, mutations, storage_error}; +use super::{BrowserWorkspace, Mutation, State, WorkspaceError, address, crypto, owned}; +use crate::ReadSnapshot; +use radroots_domain::{CommandDigest, OperationId, PublicKey, SigningAttemptId, TransactionId}; +use radroots_secrets::context::{ + EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId, +}; +use radroots_storage::{ + command::{ + BoundSigningPlan, CapturedSeal, ClaimAttemptOutcome, ClaimAttemptRequest, CommitAttempt, + EvidenceCaptureOutcome, EvidenceReceipt, OperationError, SealEvidence, SigningAttempt, + protected::{ + self, + issuance::{ClaimRecord, EvidenceManifest}, + plan::PART_BYTES, + }, + }, + workspace::{AttachmentInput, AttachmentProof}, +}; +use sha2::{Digest, Sha256}; +use zeroize::Zeroizing; + +enum Claim { + Absent(BoundSigningPlan, u8), + Present(SigningAttempt), +} +fn position(bound: &BoundSigningPlan, recipient: PublicKey) -> Option<u8> { + bound + .plan() + .seals() + .iter() + .position(|seal| seal.recipient() == recipient) + .and_then(|i| u8::try_from(i).ok()) +} +fn base(state: &State, bound: &BoundSigningPlan, index: u8) -> Result<Sha256, OperationError> { + let identity = bound.prepared().identity(); + let recipient = bound + .plan() + .seals() + .get(index as usize) + .ok_or(OperationError::InvalidCommand)? + .recipient(); + Ok(Sha256::new() + .chain_update(b"radroots.browser.local_outbox.issuance.context.v2\0") + .chain_update(state.selected.workspace_id().as_bytes()) + .chain_update(identity.operation_id().as_bytes()) + .chain_update(bound.plan().digest()) + .chain_update(recipient.as_bytes()) + .chain_update([index])) +} +fn finish(hash: Sha256, schema: &str) -> Result<EnvelopeContext, OperationError> { + let subject = hash + .finalize() + .iter() + .map(|b| format!("{b:02x}")) + .collect::<String>(); + Ok(EnvelopeContext::new( + EnvelopePurpose::parse("radroots.browser.workspace.issuance") + .map_err(|_| OperationError::InvalidCommand)?, + EnvelopeSubject::parse("workspace_issuance", subject) + .map_err(|_| OperationError::InvalidCommand)?, + PayloadSchemaId::parse(schema).map_err(|_| OperationError::InvalidCommand)?, + )) +} +fn claim_context( + state: &State, + bound: &BoundSigningPlan, + index: u8, +) -> Result<EnvelopeContext, OperationError> { + finish( + base(state, bound, index)?.chain_update(b"claim\0"), + "radroots.browser.workspace.claim.v2", + ) +} +fn evidence_context( + state: &State, + attempt: &SigningAttempt, + index: u8, + part: u8, + digest: Option<&[u8; 32]>, +) -> Result<EnvelopeContext, OperationError> { + let mut hash = base(state, attempt.bound_plan(), index)? + .chain_update(b"evidence\0") + .chain_update(attempt.attempt_id().as_bytes()) + .chain_update([part]); + if let Some(digest) = digest { + hash.update(digest); + } + finish(hash, "radroots.browser.workspace.evidence.v2") +} +impl State { + async fn bound( + &self, + view: &ReadSnapshot, + operation: OperationId, + 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); + } + 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( + &self, + view: &ReadSnapshot, + bound: BoundSigningPlan, + recipient: PublicKey, + index: u8, + ) -> Result<Claim, OperationError> { + let operation = bound.prepared().identity().operation_id(); + let key = address::key(operation, address::CLAIM, index, 0); + let Some(protected) = self.read_view_key(view, key).await? else { + if view.keys().any(|key| matches!(address::fields(key), Ok((address::EVIDENCE, found, _)) if found == index)) { return Err(OperationError::RecoveryRequired); } + return Ok(Claim::Absent(bound, index)); + }; + let clear = crypto::open_bound( + self.provider.as_ref(), + &self.reference, + claim_context(self, &bound, index)?, + &protected, + ) + .await?; + let attempt = clear.expose_secret(|raw| ClaimRecord::decode(raw, bound, recipient))?; + Ok(Claim::Present(attempt)) + } + async fn evidence( + &self, + view: &ReadSnapshot, + attempt: &SigningAttempt, + index: u8, + ) -> Result<Option<(SealEvidence, EvidenceReceipt)>, OperationError> { + let operation = attempt.bound_plan().prepared().identity().operation_id(); + let mut records = Vec::with_capacity(5); + for part in 0..=4 { + records.push( + self.read_view_key( + view, + address::key(operation, address::EVIDENCE, index, part), + ) + .await?, + ); + } + let Some(manifest) = &records[0] else { + if records.iter().any(Option::is_some) { + return Err(OperationError::RecoveryRequired); + } + return Ok(None); + }; + let raw = crypto::open_bound( + self.provider.as_ref(), + &self.reference, + evidence_context(self, attempt, index, 0, None)?, + manifest, + ) + .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]; + if part > manifest.part_count() { + if bytes.is_some() { + return Err(OperationError::RecoveryRequired); + } + continue; + } + let bytes = bytes.as_ref().ok_or(OperationError::RecoveryRequired)?; + let raw = crypto::open_bound( + self.provider.as_ref(), + &self.reference, + evidence_context( + self, + attempt, + index, + part as u8, + Some(manifest.evidence_digest()), + )?, + bytes, + ) + .await?; + let expected = (manifest.byte_count() - (part - 1) * PART_BYTES).min(PART_BYTES); + raw.expose_secret(|raw| { + if raw.len() != expected { + return Err(OperationError::RecoveryRequired); + } + clear.extend_from_slice(raw); + Ok(()) + })?; + } + let evidence = manifest.verify( + attempt, + core::str::from_utf8(&clear).map_err(|_| OperationError::RecoveryRequired)?, + )?; + let receipt = EvidenceReceipt::from_committed_store(&evidence, manifest.transaction_id()); + Ok(Some((evidence, receipt))) + } + async fn protect_evidence( + &self, + attempt: &SigningAttempt, + index: u8, + supplied: &SealEvidence, + transaction: TransactionId, + ) -> Result<Vec<Mutation>, OperationError> { + let manifest = EvidenceManifest::capture(attempt, supplied, transaction)?; + let operation = supplied.operation_id(); + let encoded = manifest.encode()?; + let protected = crypto::seal_bound( + self.provider.as_ref(), + &self.reference, + evidence_context(self, attempt, index, 0, None)?, + &encoded, + ) + .await?; + let mut changes = vec![ + Mutation::new( + address::key(operation, address::EVIDENCE, index, 0), + None, + Some(protected), + ) + .map_err(storage_error)?, + ]; + for (part, raw) in supplied + .raw_json() + .as_bytes() + .chunks(PART_BYTES) + .enumerate() + { + let part = part as u8 + 1; + let protected = crypto::seal_bound( + self.provider.as_ref(), + &self.reference, + evidence_context(self, attempt, index, part, Some(supplied.digest()))?, + raw, + ) + .await?; + changes.push( + Mutation::new( + address::key(operation, address::EVIDENCE, index, part), + None, + Some(protected), + ) + .map_err(storage_error)?, + ); + } + Ok(changes) + } +} +impl BrowserWorkspace { + /// Only an actual newly committed claim reports Claimed. Retained claims + /// are potential prior issuance and must not be dispatched again. + pub async fn claim_attempt( + &self, + request: ClaimAttemptRequest, + proof: AttachmentProof, + ) -> Result<ClaimAttemptOutcome, 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 bound = state + .bound(&view, operation, request.command_digest(), &t0) + .await? + .ok_or(OperationError::RecoveryRequired)?; + protected::same_binding(bound.prepared().request().binding(), request.binding())?; + if bound.plan().digest() != request.plan_digest() { + return Err(OperationError::IdempotencyConflict); + } + let index = + position(&bound, request.recipient()).ok_or(OperationError::InvalidCommand)?; + let (attempt, fresh, extra) = match state + .claim(&view, bound, request.recipient(), index) + .await? + { + Claim::Present(attempt) => (attempt, false, Vec::new()), + Claim::Absent(bound, index) => { + let now = access.binding.observed_at(); + if now < bound.bound_at() { + return Err(WorkspaceError::Unavailable.into()); + } + if now >= bound.prepared().issuance_window().first_issue_not_after() { + return Err(OperationError::DeadlineExceeded); + } + let attempt = SigningAttempt::from_committed_store( + bound, + request.recipient(), + SigningAttemptId::from_bytes(*crypto::random::<32>()?), + TransactionId::from_bytes(*crypto::random::<32>()?), + now, + )?; + let encoded = ClaimRecord::capture(&attempt).encode()?; + let protected = crypto::seal_bound( + state.provider.as_ref(), + &state.reference, + claim_context(&state, attempt.bound_plan(), index)?, + &encoded, + ) + .await?; + let extra = vec![ + Mutation::new( + address::key(operation, address::CLAIM, index, 0), + None, + Some(protected), + ) + .map_err(storage_error)?, + ]; + (attempt, true, extra) + } + }; + let anchor = attempt.identity(); + let change = OperationChange { + before: t0, + after: None, + window: fresh.then(|| attempt.bound_plan().prepared().issuance_window()), + extra, + }; + match state.check_operation(access, operation, change, view).await { + Ok(()) => Ok(if fresh { + ClaimAttemptOutcome::Claimed(attempt) + } else { + ClaimAttemptOutcome::Retained(attempt) + }), + Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => { + state.stop(); + Ok(ClaimAttemptOutcome::Unknown(anchor)) + } + Err(error) => Err(error), + } + }) + .await; + match result { + Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => { + self.state.stop(); + Ok(ClaimAttemptOutcome::Unknown(fallback)) + } + other => other, + } + } + /// Current-access original claim query; finding a claim authorizes no replay. + pub async fn signing_attempt( + &self, + request: ClaimAttemptRequest, + proof: AttachmentProof, + ) -> Result<Option<SigningAttempt>, OperationError> { + let work = self.state.admit()?; + let state = self.state.clone(); + 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 result = if let Some(bound) = state + .bound(&view, operation, request.command_digest(), &t0) + .await? + { + protected::same_binding(bound.prepared().request().binding(), request.binding())?; + if bound.plan().digest() != request.plan_digest() { + return Err(OperationError::IdempotencyConflict); + } + if let Some(index) = position(&bound, request.recipient()) { + match state + .claim(&view, bound, request.recipient(), index) + .await? + { + Claim::Present(attempt) => Some(attempt), + Claim::Absent(_, _) => None, + } + } else { + None + } + } else { + None + }; + state + .check_operation(access, operation, OperationChange::observe(t0), view) + .await?; + Ok(result) + }) + .await + } + /// 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( + &self, + input: AttachmentInput, + proof: AttachmentProof, + supplied: SealEvidence, + ) -> Result<EvidenceCaptureOutcome, OperationError> { + let fallback = CommitAttempt::new( + supplied.workspace_id(), + supplied.operation_id(), + supplied.command_digest(), + None, + ); + let work = self.state.admit()?; + let state = self.state.clone(); + let result = owned(work, async move { + let (grant, protected) = state.capture_grant(&input, &proof).await?; + if supplied.workspace_id() != state.selected.workspace_id() { + return Err(OperationError::InvalidEvidence); + } + let operation = supplied.operation_id(); + let view = state.read_view(operation).await?; + let t0 = state.operation_records(&view, operation).await?; + let bound = state + .bound(&view, operation, supplied.command_digest(), &t0) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let index = + position(&bound, supplied.recipient()).ok_or(OperationError::InvalidEvidence)?; + let attempt = match state + .claim(&view, bound, supplied.recipient(), index) + .await? + { + Claim::Present(attempt) => attempt, + Claim::Absent(_, _) => return Err(OperationError::RecoveryRequired), + }; + if !supplied.matches_attempt(&attempt) { + return Err(OperationError::InvalidEvidence); + } + let checked = SealEvidence::verify( + &attempt, + supplied.raw_json(), + supplied.observed_at_unix_ms(), + )?; + drop(supplied); + let (receipt, extra) = match state.evidence(&view, &attempt, index).await? { + Some((original, receipt)) => { + if original.raw_json() != checked.raw_json() + || original.digest() != checked.digest() + { + return Err(OperationError::IdempotencyConflict); + } + (receipt, Vec::new()) + } + None => { + let transaction = TransactionId::from_bytes(*crypto::random::<32>()?); + let extra = state + .protect_evidence(&attempt, index, &checked, transaction) + .await?; + ( + EvidenceReceipt::from_committed_store(&checked, transaction), + extra, + ) + } + }; + let anchor = CommitAttempt::new( + receipt.workspace_id(), + operation, + receipt.command_digest(), + Some(receipt.transaction_id()), + ); + let batch = mutations(protected, operation, t0, None, extra)?; + let active = state.active()?; + match state + .checked_batch(batch, view, move || { + if !active.get() { + return Err(WorkspaceError::Closed.into()); + } + grant.authenticate_retained_capture(&input, &proof)?; + Ok(()) + }) + .await + { + Ok(()) => Ok(EvidenceCaptureOutcome::Committed(receipt)), + Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => { + state.stop(); + Ok(EvidenceCaptureOutcome::Unknown(anchor)) + } + Err(error) => Err(error), + } + }) + .await; + match result { + Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => { + self.state.stop(); + Ok(EvidenceCaptureOutcome::Unknown(fallback)) + } + other => other, + } + } + /// Reads original verified output under current access; no issuance occurs. + pub async fn captured_seal( + &self, + request: ClaimAttemptRequest, + proof: AttachmentProof, + ) -> Result<Option<CapturedSeal>, OperationError> { + let work = self.state.admit()?; + let state = self.state.clone(); + 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 result = if let Some(bound) = state + .bound(&view, operation, request.command_digest(), &t0) + .await? + { + protected::same_binding(bound.prepared().request().binding(), request.binding())?; + if bound.plan().digest() != request.plan_digest() { + return Err(OperationError::IdempotencyConflict); + } + if let Some(index) = position(&bound, request.recipient()) { + match state + .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(), + ) + }) + .transpose()?, + Claim::Absent(_, _) => None, + } + } else { + None + } + } else { + None + }; + state + .check_operation(access, operation, OperationChange::observe(t0), view) + .await?; + Ok(result) + }) + .await + } +} diff --git a/crates/storage_indexeddb/src/workspace/journal.rs b/crates/storage_indexeddb/src/workspace/journal.rs @@ -3,6 +3,7 @@ use super::{ Batch, BrowserWorkspace, Error, Mutation, RecordKey, State, WorkspaceError, crypto, grant_key, owned, }; +use crate::ReadSnapshot; use radroots_domain::{CommandDigest, IssuanceWindow, OperationId, Sequence, TransactionId}; use radroots_secrets::context::{ EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId, @@ -40,20 +41,37 @@ impl OperationChange { } } +pub(super) fn mutations( + grant: Vec<u8>, + operation: OperationId, + before: Records, + after: Option<Records>, + extra: Vec<Mutation>, +) -> Result<Batch, OperationError> { + let mut mutations = Vec::with_capacity(SLOTS + 1 + extra.len()); + mutations + .push(Mutation::new(grant_key(), Some(grant.clone()), Some(grant)).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)?); + } + mutations.extend(extra); + Batch::new(mutations).map_err(storage_error) +} + 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()) + super::address::key(operation, super::address::PREPARED, 0, slot as u8) } + 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(b"radroots.browser.local_outbox.prepared.context.v2\0"); h.update(state.selected.workspace_id().as_bytes()); h.update(operation.as_bytes()); if let Some((index, digest)) = part { @@ -73,22 +91,19 @@ fn context( .map_err(|_| WorkspaceError::InvalidInput)?, EnvelopeSubject::parse("workspace_prepared", subject) .map_err(|_| WorkspaceError::InvalidInput)?, - PayloadSchemaId::parse("radroots.browser.workspace.prepared.v1") + PayloadSchemaId::parse("radroots.browser.workspace.prepared.v2") .map_err(|_| WorkspaceError::InvalidInput)?, )) } impl State { pub(super) async fn operation_records( &self, + view: &ReadSnapshot, 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)?; + let value = self.read_view_key(view, key(operation, slot)).await?; if value .as_ref() .is_some_and(|bytes| bytes.len() > crypto::PROTECTED_MAX) @@ -240,6 +255,7 @@ impl State { access: Access, operation: OperationId, change: OperationChange, + view: ReadSnapshot, ) -> Result<(), OperationError> { let OperationChange { before, @@ -247,54 +263,45 @@ impl State { window, extra, } = change; - let mut mutations = Vec::with_capacity(SLOTS + 1 + extra.len()); - 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)?); - } - mutations.extend(extra); - let batch = Batch::new(mutations).map_err(storage_error)?; + let batch = mutations(access.protected, operation, before, after, extra)?; let active = self.active()?; let clock = self.clock.clone(); + self.checked_batch(batch, view, move || { + 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(()) + }) + .await + } + pub(super) async fn checked_batch( + &self, + batch: Batch, + view: ReadSnapshot, + check: impl Fn() -> Result<(), OperationError> + 'static, + ) -> Result<(), OperationError> { 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 { + .compare_exchange_snapshot_checked(batch, view, move || { + if let Err(error) = check() { refused.set(Some(error)); false } else { @@ -333,9 +340,10 @@ impl BrowserWorkspace { 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 view = state.read_view(operation).await?; + let before = state.operation_records(&view, operation).await?; let extra = if before.iter().all(Option::is_none) { - state.absent_plans(operation).await? + state.absent_plans(&view, operation).await? } else { Vec::new() }; @@ -386,6 +394,7 @@ impl BrowserWorkspace { window: fresh.then(|| prepared.issuance_window()), extra, }, + view, ) .await { @@ -408,7 +417,7 @@ impl BrowserWorkspace { } /// 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( + pub async fn operation( &self, binding: WorkspaceBinding, operation: OperationId, @@ -419,16 +428,19 @@ impl BrowserWorkspace { 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 view = state.read_view(operation).await?; + let records = state.operation_records(&view, operation).await?; let result = state.preparation(operation, &records).await?; if let Some(prepared) = &result { protected::check_digest(prepared, binding.actor(), digest)?; } let mut change = OperationChange::observe(records); if result.is_none() { - change.extra = state.absent_plans(operation).await?; + change.extra = state.absent_plans(&view, operation).await?; } - state.check_operation(access, operation, change).await?; + state + .check_operation(access, operation, change, view) + .await?; Ok(result) }) .await diff --git a/crates/storage_indexeddb/src/workspace/mod.rs b/crates/storage_indexeddb/src/workspace/mod.rs @@ -1,7 +1,9 @@ //! Authenticated browser local outboxes, independent of participant signing. //! Creation establishes a fresh unrelated buyer outbox only. Existing state //! requires its independently retained selection and protected proof. +mod address; mod crypto; +mod issuance; mod journal; mod lease; mod plans; @@ -67,7 +69,7 @@ fn stored(error: Error) -> WorkspaceError { } fn namespace(input: &AttachmentInput) -> Result<Namespace, WorkspaceError> { let mut digest = Sha256::new(); - digest.update(b"radroots.browser.local_outbox.namespace.v1\0"); + digest.update(b"radroots.browser.local_outbox.namespace.v2\0"); digest.update(input.workspace_id().as_bytes()); SourceGeneration::new(digest.finalize().into()) .map(Namespace::new) @@ -129,6 +131,11 @@ fn select( .map_err(|_| WorkspaceError::Unavailable)?; Ok(()) } +#[derive(Clone, Copy, Eq, PartialEq)] +enum AccessMode { + Current, + CaptureOnly, +} struct State { // Database drops before the lease if an unobserved owner is discarded. db: Database, @@ -136,6 +143,7 @@ struct State { reference: SecretRef, selected: AttachmentInput, clock: Rc<dyn WorkspaceClock>, + mode: AccessMode, lease: RefCell<Option<lease::Lease>>, serial: Mutex<()>, jobs: Cell<usize>, @@ -210,6 +218,19 @@ impl State { input: &AttachmentInput, proof: &AttachmentProof, ) -> Result<(LocalOutboxGrant, Vec<u8>, WorkspaceBinding), WorkspaceError> { + if self.mode != AccessMode::Current { + return Err(WorkspaceError::Unauthorized); + } + let (record, protected) = self.capture_grant(input, proof).await?; + let binding = record.authenticate(input, proof, self.clock.now()?)?; + self.active()?; + Ok((record, protected, binding)) + } + async fn capture_grant( + &self, + input: &AttachmentInput, + proof: &AttachmentProof, + ) -> Result<(LocalOutboxGrant, Vec<u8>), WorkspaceError> { self.active()?; if input != &self.selected { return Err(WorkspaceError::Unauthorized); @@ -229,9 +250,9 @@ impl State { ) .await?; let record = plaintext.expose_secret(LocalOutboxGrant::decode)?; - let binding = record.authenticate(input, proof, self.clock.now()?)?; + record.authenticate_retained_capture(input, proof)?; self.active()?; - Ok((record, protected, binding)) + Ok((record, protected)) } } struct Work(Rc<State>); @@ -328,7 +349,15 @@ impl BrowserWorkspace { return Err(stored(error)); } }; - let owner = Self::assemble(db, provider, reference, input.clone(), clock, lease); + let owner = Self::assemble( + db, + provider, + reference, + input.clone(), + clock, + lease, + AccessMode::Current, + ); let initialized = async { let bytes = record.encode()?; let binding = record.authenticate(&input, &proof, now)?; @@ -378,6 +407,47 @@ impl BrowserWorkspace { policy: AccessPolicy, clock: Rc<dyn WorkspaceClock>, ) -> Result<Self, WorkspaceError> { + Self::open_mode( + input, + proof, + provider, + reference, + policy, + clock, + AccessMode::Current, + ) + .await + } + /// Opens only for appending matching already obtained output to an actual + /// original claim. This handle cannot authenticate or admit fresh work. + pub async fn open_existing_for_capture( + input: AttachmentInput, + proof: AttachmentProof, + provider: Rc<dyn SecretProvider>, + reference: SecretRef, + policy: AccessPolicy, + clock: Rc<dyn WorkspaceClock>, + ) -> Result<Self, WorkspaceError> { + Self::open_mode( + input, + proof, + provider, + reference, + policy, + clock, + AccessMode::CaptureOnly, + ) + .await + } + async fn open_mode( + input: AttachmentInput, + proof: AttachmentProof, + provider: Rc<dyn SecretProvider>, + reference: SecretRef, + policy: AccessPolicy, + clock: Rc<dyn WorkspaceClock>, + mode: AccessMode, + ) -> Result<Self, WorkspaceError> { select(provider.as_ref(), &reference, policy)?; let setup = Setup::admit()?; let (send, observe) = oneshot::channel(); @@ -393,8 +463,15 @@ impl BrowserWorkspace { return Err(stored(error)); } }; - let owner = Self::assemble(db, provider, reference, input.clone(), clock, lease); - if let Err(error) = owner.state.access(&input, &proof).await { + let owner = + Self::assemble(db, provider, reference, input.clone(), clock, lease, mode); + let authenticated = match mode { + AccessMode::Current => owner.state.access(&input, &proof).await.map(|_| ()), + AccessMode::CaptureOnly => { + owner.state.capture_grant(&input, &proof).await.map(|_| ()) + } + }; + if let Err(error) = authenticated { owner.close().await?; return Err(error); } @@ -412,6 +489,7 @@ impl BrowserWorkspace { selected: AttachmentInput, clock: Rc<dyn WorkspaceClock>, lease: lease::Lease, + mode: AccessMode, ) -> Self { Self { state: Rc::new(State { @@ -420,6 +498,7 @@ impl BrowserWorkspace { reference, selected, clock, + mode, lease: RefCell::new(Some(lease)), serial: Mutex::new(()), jobs: Cell::new(0), diff --git a/crates/storage_indexeddb/src/workspace/plans.rs b/crates/storage_indexeddb/src/workspace/plans.rs @@ -1,6 +1,7 @@ //! Actual protected T1 storage; no participant issuance or network effects. use super::journal::{OperationChange, Records, storage_error}; use super::{BrowserWorkspace, Mutation, RecordKey, State, WorkspaceError, crypto, owned}; +use crate::ReadSnapshot; use radroots_domain::{CommandDigest, OperationId, TransactionId}; use radroots_secrets::context::{ EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId, @@ -21,19 +22,16 @@ use zeroize::Zeroizing; const SLOTS: usize = PARTS_MAX + 1; fn key(operation: OperationId, slot: usize) -> RecordKey { - let mut h = Sha256::new(); - h.update(b"radroots.browser.local_outbox.plan.key.v1\0"); - h.update(operation.as_bytes()); - h.update((slot as u32).to_be_bytes()); - RecordKey::new(h.finalize().into()) + super::address::key(operation, super::address::PLAN, 0, slot as u8) } + fn context( state: &State, operation: OperationId, part: Option<(usize, CommandDigest)>, ) -> Result<EnvelopeContext, WorkspaceError> { let mut h = Sha256::new(); - h.update(b"radroots.browser.local_outbox.plan.context.v1\0"); + h.update(b"radroots.browser.local_outbox.plan.context.v2\0"); h.update(state.selected.workspace_id().as_bytes()); h.update(operation.as_bytes()); if let Some((index, digest)) = part { @@ -53,7 +51,7 @@ fn context( .map_err(|_| WorkspaceError::InvalidInput)?, EnvelopeSubject::parse("workspace_plan", subject) .map_err(|_| WorkspaceError::InvalidInput)?, - PayloadSchemaId::parse("radroots.browser.workspace.plan.v1") + PayloadSchemaId::parse("radroots.browser.workspace.plan.v2") .map_err(|_| WorkspaceError::InvalidInput)?, )) } @@ -74,14 +72,14 @@ fn comparisons( .collect() } impl State { - async fn plan_records(&self, operation: OperationId) -> Result<Records, OperationError> { + pub(super) async fn plan_records( + &self, + view: &ReadSnapshot, + 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)?; + let value = self.read_view_key(view, key(operation, slot)).await?; if value .as_ref() .is_some_and(|v| v.len() > crypto::PROTECTED_MAX) @@ -94,15 +92,23 @@ impl State { } pub(super) async fn absent_plans( &self, + view: &ReadSnapshot, operation: OperationId, ) -> Result<Vec<Mutation>, OperationError> { - let before = self.plan_records(operation).await?; - if before.iter().any(Option::is_some) { + let before = self.plan_records(view, operation).await?; + if before.iter().any(Option::is_some) + || view.keys().any(|key| { + !matches!( + super::address::fields(key), + Ok((super::address::PREPARED, _, _)) + ) + }) + { return Err(OperationError::RecoveryRequired); } comparisons(operation, before, None) } - async fn retained_plan( + pub(super) async fn retained_plan( &self, prepared: &PreparedOperation, records: &Records, @@ -208,14 +214,15 @@ impl BrowserWorkspace { let result = owned(work, async move { let access = state.operation_access(&binding, proof).await?; let operation = supplied.operation_id(); - let t0 = state.operation_records(operation).await?; + let view = state.read_view(operation).await?; + let t0 = state.operation_records(&view, operation).await?; let prepared = state .preparation(operation, &t0) .await? .ok_or(OperationError::RecoveryRequired)?; protected::check_digest(&prepared, binding.actor(), Some(supplied.command_digest()))?; protected::same_binding(prepared.request().binding(), &binding)?; - let before = state.plan_records(operation).await?; + let before = state.plan_records(&view, operation).await?; let (manifest, plan, after, fresh) = if let Some((manifest, plan)) = state.retained_plan(&prepared, &before).await? { @@ -224,6 +231,14 @@ impl BrowserWorkspace { } (manifest, plan, None, false) } else { + if view.keys().any(|key| { + !matches!( + super::address::fields(key), + Ok((super::address::PREPARED, _, _)) + ) + }) { + return Err(OperationError::RecoveryRequired); + } let window = prepared.issuance_window(); let observed = access.binding.observed_at(); if observed < window.prepared_at() { @@ -253,7 +268,7 @@ impl BrowserWorkspace { window: fresh.then(|| prepared.issuance_window()), extra: comparisons(operation, before, after)?, }; - match state.check_operation(access, operation, change).await { + match state.check_operation(access, operation, change, view).await { Ok(()) => Ok(PlanBindingOutcome::Committed( manifest.bind(prepared, plan)?, )), @@ -274,7 +289,7 @@ impl BrowserWorkspace { } } /// Authenticates and confirms the original plan without issuance or replay. - pub async fn query_signing_intents( + pub async fn signing_plan( &self, binding: WorkspaceBinding, operation: OperationId, @@ -285,16 +300,20 @@ impl BrowserWorkspace { let state = self.state.clone(); owned(work, async move { let access = state.operation_access(&binding, proof).await?; - let t0 = state.operation_records(operation).await?; + let view = state.read_view(operation).await?; + let t0 = state.operation_records(&view, operation).await?; let prepared = state.preparation(operation, &t0).await?; - let records = state.plan_records(operation).await?; + let records = state.plan_records(&view, operation).await?; let retained = if let Some(prepared) = prepared { protected::check_digest(&prepared, binding.actor(), Some(digest))?; protected::same_binding(prepared.request().binding(), &binding)?; let plan = state.retained_plan(&prepared, &records).await?; + if plan.is_none() { + state.absent_plans(&view, operation).await?; + } Some((prepared, plan)) } else { - if records.iter().any(Option::is_some) { + if !view.is_empty() { return Err(OperationError::RecoveryRequired); } None @@ -305,7 +324,9 @@ impl BrowserWorkspace { window: None, extra: comparisons(operation, records, None)?, }; - state.check_operation(access, operation, change).await?; + state + .check_operation(access, operation, change, view) + .await?; match retained { Some((prepared, Some((manifest, plan)))) => manifest.bind(prepared, plan).map(Some), _ => Ok(None), diff --git a/crates/storage_indexeddb/tests/browser/run.mjs b/crates/storage_indexeddb/tests/browser/run.mjs @@ -6,15 +6,18 @@ import { resolve, sep } from 'node:path'; // Caller supplies its installed Playwright package and an external generated // WASM directory. No dependency installation or generated bytes live here. -const [moduleRoot, packageDir, engine = 'chromium'] = process.argv.slice(2); -assert(moduleRoot && packageDir, 'usage: node run.mjs PLAYWRIGHT_PACKAGE WASM_DIRECTORY [ENGINE]'); +const [moduleRoot, packageDir, engine = 'chromium', legacyPackageDir] = process.argv.slice(2); +assert(moduleRoot && packageDir && legacyPackageDir, 'usage: node run.mjs PLAYWRIGHT_PACKAGE WASM_DIRECTORY ENGINE V1_WASM_DIRECTORY'); const playwright = createRequire(resolve(moduleRoot, 'package.json'))('playwright'); assert(['chromium','firefox','webkit'].includes(engine)); const root = resolve(packageDir); +const legacyRoot = resolve(legacyPackageDir); const server = createServer(async (req,res) => { try { - const path = resolve(root, '.' + new URL(req.url, 'http://localhost').pathname); - assert(path.startsWith(root + sep)); + const url = new URL(req.url, 'http://localhost').pathname; + const selectedRoot=url.startsWith('/v1/')?legacyRoot:root; + const path = resolve(selectedRoot, '.' + (url.startsWith('/v1/')?url.slice(3):url)); + assert(path.startsWith(selectedRoot + sep)); if (path.endsWith('/index.html')) { res.setHeader('content-type','text/html'); res.end('<!doctype html><title>IndexedDB fixture</title>'); return; } @@ -27,6 +30,7 @@ const server = createServer(async (req,res) => { 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==='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==='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)});}}; @@ -58,7 +62,7 @@ try { return tx; }; const same=(a,b)=>{if(JSON.stringify(a)!==JSON.stringify(b))throw Error('assertion mismatch');}; - const rejects=async(fn,code)=>{try{await fn();}catch(error){same(String(error),code);return;}throw Error('expected refusal');}; + const rejects=async(fn,code)=>{try{await fn();}catch(error){if(String(error)!==code)throw Error('expected '+code+', received '+String(error));return;}throw Error('expected refusal: '+code);}; const value=async(db,k)=>{const raw=await db.read(k);return raw===undefined ? undefined : Array.from(raw);}; const tests=[]; const passed=name=>{tests.push(name);console.log('PASS '+name);}; @@ -279,7 +283,10 @@ try { 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 recordKey=async(n,kind,recipient=0,part=0)=>{const prefix=new Uint8Array(await crypto.subtle.digest('SHA-256',new Uint8Array([...new TextEncoder().encode('radroots.browser.local_outbox.operation.prefix.v2\0'),...new Uint8Array(32).fill(n)])));const key=new Uint8Array(32);key.set(prefix.subarray(0,16));key[16]=kind;key[17]=recipient;key[20]=part;return key;}; + const operationKey=(n,slot)=>recordKey(n,1,0,slot); + const actualCursor=IDBObjectStore.prototype.openCursor; + const exactCursorKey=range=>{if(!range||range.lower===undefined||range.upper===undefined||range.lowerOpen||range.upperOpen)return;const lower=keyBytes(range.lower),upper=keyBytes(range.upper);if(lower.length===32&&JSON.stringify(lower)===JSON.stringify(upper))return lower;}; 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)))]; @@ -309,8 +316,10 @@ try { 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;} + const uncertainPart=keyBytes(await operationKey(70,1));let actualLatePart=false; + try{IDBObjectStore.prototype.openCursor=function(...args){const request=actualCursor.apply(this,args);if(this.transaction.db.name===uncertainReceipt.namespace&&this.transaction.mode==='readwrite'&&JSON.stringify(exactCursorKey(args[0]))===JSON.stringify(uncertainPart))request.addEventListener('success',()=>{actualLatePart=true;uncertain.set_time(1500);},{once:true});return request;};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{IDBObjectStore.prototype.openCursor=actualCursor;IDBTransaction.prototype.abort=actualAbort;} + same(actualLatePart,true); 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); @@ -330,12 +339,11 @@ try { 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);}; + IDBObjectStore.prototype.openCursor=function(...args){if(this.transaction.db.name===unknownReadReceipt.namespace&&exactCursorKey(args[0]))throw new DOMException('synthetic host read failure','InvalidStateError');return actualCursor.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;} + }));}finally{IDBObjectStore.prototype.openCursor=actualCursor;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'); @@ -365,7 +373,7 @@ try { same(Array.from(await planBox.plan_query(181)),[]);sameRows(await workspaceBytes(planReceipt),beforePlanExpiry); passed('fresh T1 expiry after actual wrapping rolls back the entire grant/T0/plan comparison batch'); planBox.set_time(1000);await planBox.admit(182,false);const abortedPlan=await planBox.new_plan(182); - const planKey=async(n,slot)=>new Uint8Array(await crypto.subtle.digest('SHA-256',new Uint8Array([...new TextEncoder().encode('radroots.browser.local_outbox.plan.key.v1\0'),...new Uint8Array(32).fill(n),0,0,0,slot]))); + const planKey=(n,slot)=>recordKey(n,2,0,slot); const abortPlanKey=await planKey(182,1),beforePlanAbort=await workspaceBytes(planReceipt);let planWriteAborted=false; const actualPlanPut=IDBObjectStore.prototype.put; try{IDBObjectStore.prototype.put=function(...args){const request=actualPlanPut.apply(this,args);if(this.transaction.db.name===planReceipt.namespace&&JSON.stringify(keyBytes(args[1]))===JSON.stringify(keyBytes(abortPlanKey))){request.addEventListener('success',()=>{planWriteAborted=true;this.transaction.abort();});}return request;};await rejects(()=>planBox.bind_plan(182,abortedPlan),'storage_failure');} @@ -397,17 +405,19 @@ try { passed('T1 orphan/missing/tampered/swapped/foreign parts and removed T0 refuse without absence, replacement or repair'); const unknownPlan=await WorkspaceFixture.create(183),unknownPlanReceipt=receiptOf(unknownPlan,183); await unknownPlan.admit(183,false);const unknownPlanWire=await unknownPlan.new_plan(183);let planUnknown; - try{IDBTransaction.prototype.abort=function(){if(this.db.name===unknownPlanReceipt.namespace)return;return actualAbort.call(this);};planUnknown=Array.from(await unknownPlan.bind_plan_unknown(183,unknownPlanWire));} - finally{IDBTransaction.prototype.abort=actualAbort;} + const latePlanPart=keyBytes(await planKey(183,1));let actualLatePlanPart=false; + try{IDBObjectStore.prototype.openCursor=function(...args){const request=actualCursor.apply(this,args);if(this.transaction.db.name===unknownPlanReceipt.namespace&&this.transaction.mode==='readwrite'&&JSON.stringify(exactCursorKey(args[0]))===JSON.stringify(latePlanPart))request.addEventListener('success',()=>{actualLatePlanPart=true;unknownPlan.set_time(1500);},{once:true});return request;};IDBTransaction.prototype.abort=function(){if(this.db.name===unknownPlanReceipt.namespace)return;return actualAbort.call(this);};planUnknown=Array.from(await unknownPlan.bind_plan_unknown(183,unknownPlanWire));} + finally{IDBObjectStore.prototype.openCursor=actualCursor;IDBTransaction.prototype.abort=actualAbort;} + same(actualLatePlanPart,true); same(planUnknown.length,64);same(planUnknown.slice(0,32),new Array(32).fill(183));await unknownPlan.close(); const unknownPlanState=await workspaceBytes(unknownPlanReceipt);const unknownPlanOpen=await openPlanReceipt(unknownPlanReceipt);await rejects(()=>unknownPlanOpen.plan_query(183),'recovery_required');await unknownPlanOpen.close();sameRows(await workspaceBytes(unknownPlanReceipt),unknownPlanState); passed('actual T1 completion despite suppressed abort retains original unknown transaction and preserves partial state'); const unknownPlanRead=await WorkspaceFixture.create(188),unknownPlanReadReceipt=receiptOf(unknownPlanRead,188); const originalReadT0=Array.from(await unknownPlanRead.admit(188,false)),readPlanWire=await unknownPlanRead.new_plan(188),beforePlanRead=await workspaceBytes(unknownPlanReadReceipt);let planReadGets=0,planReadFallback; try{planReadFallback=Array.from(await unknownPlanRead.bind_plan_read_unknown(188,readPlanWire,()=>{ - IDBObjectStore.prototype.get=function(...args){if(this.transaction.db.name===unknownPlanReadReceipt.namespace&&++planReadGets===2)throw new DOMException('synthetic retained-record read failure','InvalidStateError');return actualGet.apply(this,args);}; + IDBObjectStore.prototype.openCursor=function(...args){if(this.transaction.db.name===unknownPlanReadReceipt.namespace&&exactCursorKey(args[0])&&++planReadGets===2)throw new DOMException('synthetic retained-record read failure','InvalidStateError');return actualCursor.apply(this,args);}; IDBTransaction.prototype.abort=function(){if(this.db.name===unknownPlanReadReceipt.namespace)return;return actualAbort.call(this);}; - }));}finally{IDBObjectStore.prototype.get=actualGet;IDBTransaction.prototype.abort=actualAbort;} + }));}finally{IDBObjectStore.prototype.openCursor=actualCursor;IDBTransaction.prototype.abort=actualAbort;} same(planReadFallback.length,64);same(planReadFallback.slice(0,32),new Array(32).fill(188));await unknownPlanRead.close(); const restoredRead=await openPlanReceipt(unknownPlanReadReceipt);same(Array.from(await restoredRead.query(188)),originalReadT0);same(Array.from(await restoredRead.plan_query(188)),[]);await restoredRead.close();sameRows(await workspaceBytes(unknownPlanReadReceipt),beforePlanRead); passed('uncertain retained T1 input read preserves the original ID/digest without inventing a transaction or changing T0'); @@ -417,7 +427,147 @@ try { const restored=await openPlanReceipt(r);same(Array.from(await restored.plan_query(n)),[]);await restored.close(); } passed('backwards clock and grant expiry after T1 crypto refuse with unchanged original state'); + const setupIssuance=async n=>{const owner=await WorkspaceFixture.create(n),receipt=receiptOf(owner,n);await owner.admit(n,false);await owner.bind_plan(n,await owner.new_plan(n));return {owner,receipt};}; + const {owner:signing,receipt:signingReceipt}=await setupIssuance(190); + same(Array.from(await signing.attempt(190,0)),[]);same(Array.from(await signing.captured(190,0)),[]); + const selfSeal=await signing.obtain(190,0,false),peerSeal=await signing.obtain(190,1,true); + same(selfSeal.malformed_output_refused(),true);same(peerSeal.malformed_output_refused(),true); + const originalClaim=Array.from(selfSeal.original_claim()),peerClaim=Array.from(peerSeal.original_claim()); + same(originalClaim.length,144);same(Array.from(await signing.attempt(190,0)),originalClaim);same(Array.from(await signing.attempt(190,1)),peerClaim); + const originalSeal=Array.from(await signing.capture(selfSeal)),peerCapture=Array.from(await signing.capture(peerSeal)); + same(originalSeal.length,136);same(originalSeal.slice(32,64),Array.from(selfSeal.digest()));same(originalSeal.slice(64,96),originalClaim.slice(0,32));same(originalSeal.slice(104),originalClaim.slice(112)); + same(Number(new DataView(new Uint8Array(originalSeal).buffer).getBigUint64(96,false)),0);same(Number(new DataView(new Uint8Array(peerCapture).buffer).getBigUint64(96,false)),1000000); + same(Array.from(await signing.captured(190,0)),originalSeal);same(Array.from(await signing.captured(190,1)),peerCapture); + const signedRows=await workspaceBytes(signingReceipt);const evidenceRows=signedRows.keys.filter(k=>keyBytes(k)[16]===4);if(evidenceRows.length<6)throw Error('obtained seals did not exercise multipart evidence'); + passed('actual self/peer signatures match original claims and persist verified multipart output with exact observation uncertainty'); + signing.set_time(1600); + try{Crypto.prototype.getRandomValues=()=>{throw Error('retained S acquired new entropy');};same(Array.from(await signing.claim(190,0)),[0,...originalClaim]);same(Array.from(await signing.capture(selfSeal)),originalSeal);await rejects(()=>signing.obtain(190,0,false),'retained_no_dispatch');} + finally{Crypto.prototype.getRandomValues=originalRandom;} + signing.set_time(0);same(Array.from(await signing.capture(selfSeal)),originalSeal);same(Array.from(await signing.capture_reobserved(selfSeal)),originalSeal);signing.set_time(1000); + await rejects(()=>signing.capture_alternate(selfSeal),'idempotency_conflict');same(Array.from(await signing.captured(190,0)),originalSeal); + await signing.close();let reopenedSigning=await openPlanReceipt(signingReceipt);same(Array.from(await reopenedSigning.attempt(190,0)),originalClaim);same(Array.from(await reopenedSigning.captured(190,1)),peerCapture);await reopenedSigning.close(); + passed('late S replay and unavailable-clock capture retain original identities without fresh entropy or redispatch'); + const stableSigning=await workspaceBytes(signingReceipt),evidenceKey=await recordKey(190,4,0,1),claimKey=await recordKey(190,3,0,0),evidenceManifest=await recordKey(190,4,0,0),otherEvidence=await recordKey(190,4,1,1); + const signingValue=k=>stableSigning.values[stableSigning.keys.findIndex(x=>JSON.stringify(keyBytes(x))===JSON.stringify(keyBytes(k)))]; + for(const mode of ['missing_part','missing_evidence_manifest','tampered','tampered_claim','swapped_recipient','swapped_claim_recipient','missing_claim','missing_t0','missing_t1','unsupported_address']){ + console.log('STEP issuance_damage '+mode); + const removeT0=await operationKey(190,0),removeT1=await planKey(190,0),unsupported=await recordKey(190,9); + await changeWorkspace(signingReceipt,store=>{ + if(mode==='missing_part')store.delete(evidenceKey); + if(mode==='missing_evidence_manifest')store.delete(evidenceManifest); + if(mode==='tampered'){const v=new Uint8Array(signingValue(evidenceKey));v[v.length-1]^=1;store.put(v,evidenceKey);} + if(mode==='tampered_claim'){const v=new Uint8Array(signingValue(claimKey));v[v.length-1]^=1;store.put(v,claimKey);} + if(mode==='swapped_recipient')store.put(signingValue(otherEvidence),evidenceKey); + if(mode==='swapped_claim_recipient'){const other=stableSigning.keys.find(k=>keyBytes(k)[16]===3&&keyBytes(k)[17]===1);store.put(signingValue(other),claimKey);} + if(mode==='missing_claim')store.delete(claimKey); + if(mode==='missing_t0')store.delete(removeT0); + if(mode==='missing_t1')store.delete(removeT1); + if(mode==='unsupported_address')store.put(new Uint8Array(),unsupported); + }); + const broken=await workspaceBytes(signingReceipt);reopenedSigning=await openPlanReceipt(signingReceipt); + await rejects(()=>reopenedSigning.captured_original(selfSeal),'recovery_required');await reopenedSigning.close();reopenedSigning=await openPlanReceipt(signingReceipt); + await rejects(()=>reopenedSigning.capture(selfSeal),'recovery_required'); + if(mode==='missing_claim'){await reopenedSigning.close();reopenedSigning=await openPlanReceipt(signingReceipt);await rejects(()=>reopenedSigning.claim(190,0),'recovery_required');} + await reopenedSigning.close();sameRows(await workspaceBytes(signingReceipt),broken); + await changeWorkspace(signingReceipt,store=>{store.clear();stableSigning.keys.forEach((k,i)=>store.put(stableSigning.values[i],k));}); + } + passed('missing, damaged, foreign-recipient and orphan issuance state refuses without replacing any retained bytes'); + const {owner:revokedSigning,receipt:revokedSigningReceipt}=await setupIssuance(191),revokedSeal=await revokedSigning.obtain(191,0,false),revokedPeer=await revokedSigning.obtain(191,1,true); + await revokedSigning.revoke();revokedSigning.set_time(0);const revokedCapture=Array.from(await revokedSigning.capture(revokedSeal));await revokedSigning.close(); + await rejects(()=>openPlanReceipt(revokedSigningReceipt),'grant_revoked'); + const captureOnly=await WorkspaceFixture.open_capture(191,new Uint8Array(revokedSigningReceipt.fingerprint),new Uint8Array(revokedSigningReceipt.selection),new Uint8Array(revokedSigningReceipt.proof)); + await rejects(()=>captureOnly.authenticate(),'unauthorized');await rejects(()=>captureOnly.claim(191,0),'unauthorized'); + captureOnly.set_time(0);const revokedPeerCapture=Array.from(await captureOnly.capture(revokedPeer));same(Array.from(await captureOnly.capture(revokedSeal)),revokedCapture);same(revokedPeerCapture.slice(64,96),Array.from(revokedPeer.original_claim()).slice(0,32));await captureOnly.close(); + passed('revoked grant and unavailable clock preserve obtained output through capture-only reopen without restoring fresh authority'); + const {owner:expiredSigning,receipt:expiredSigningReceipt}=await setupIssuance(199),expiredSeal=await expiredSigning.obtain(199,0,true);expiredSigning.set_time(2000);await rejects(()=>expiredSigning.authenticate(),'grant_expired');const expiredReceipt=Array.from(await expiredSigning.capture(expiredSeal));same(expiredReceipt.slice(32,64),Array.from(expiredSeal.digest()));await expiredSigning.close(); + const afterExpiredCapture=await openPlanReceipt(expiredSigningReceipt);same(Array.from(await afterExpiredCapture.captured(199,0)),expiredReceipt);await afterExpiredCapture.close();passed('already obtained output appends after actual grant expiry and retains its original receipt after reopen'); + const {owner:unobservedSealOwner,receipt:unobservedSealReceipt}=await setupIssuance(192),unobservedSeal=await unobservedSealOwner.obtain(192,0,true); + unobservedSealOwner.abandon_capture(unobservedSeal);same(unobservedSealOwner.abandon_auths(1),0);unobservedSealOwner.abandon_close();await unobservedSealOwner.close(); + const afterUnobservedSeal=await openPlanReceipt(unobservedSealReceipt);same(Array.from(await afterUnobservedSeal.captured(192,0)).slice(32,64),Array.from(unobservedSeal.digest()));await afterUnobservedSeal.close(); + passed('unobserved obtained-output capture keeps its reservation and survives cancelled close and exact reopen'); + const {owner:freshClaimOwner,receipt:freshClaimReceipt}=await setupIssuance(197),beforeFreshClaim=await workspaceBytes(freshClaimReceipt),actualWrapKey=SubtleCrypto.prototype.wrapKey;let changedClaimClock=false; + try{SubtleCrypto.prototype.wrapKey=async function(...args){const wrapped=await actualWrapKey.apply(this,args);changedClaimClock=true;freshClaimOwner.set_time(1500);return wrapped;};await rejects(()=>freshClaimOwner.claim(197,0),'deadline_exceeded');} + finally{SubtleCrypto.prototype.wrapKey=actualWrapKey;} + same(changedClaimClock,true);freshClaimOwner.set_time(1000);same(Array.from(await freshClaimOwner.attempt(197,0)),[]);sameRows(await workspaceBytes(freshClaimReceipt),beforeFreshClaim);await freshClaimOwner.close(); + passed('fresh claim deadline crossed after actual key wrapping aborts without retaining an issuance claim'); + const {owner:abortSigning,receipt:abortSigningReceipt}=await setupIssuance(198);await rejects(()=>abortSigning.capture(selfSeal),'invalid_evidence'); + const abortClaimKey=await recordKey(198,3),beforeAbortClaim=await workspaceBytes(abortSigningReceipt);let claimWriteSucceeded=false; + try{IDBObjectStore.prototype.put=function(...args){const r=actualPlanPut.apply(this,args);if(this.transaction.db.name===abortSigningReceipt.namespace&&JSON.stringify(keyBytes(args[1]))===JSON.stringify(keyBytes(abortClaimKey)))r.addEventListener('success',()=>{claimWriteSucceeded=true;this.transaction.abort();},{once:true});return r;};await rejects(()=>abortSigning.claim(198,0),'storage_failure');} + finally{IDBObjectStore.prototype.put=actualPlanPut;} + same(claimWriteSucceeded,true);same(Array.from(await abortSigning.attempt(198,0)),[]);sameRows(await workspaceBytes(abortSigningReceipt),beforeAbortClaim); + const abortSeal=await abortSigning.obtain(198,0,false),abortEvidenceKey=await recordKey(198,4,0,1),beforeAbortCapture=await workspaceBytes(abortSigningReceipt);let sealWriteSucceeded=false; + try{IDBObjectStore.prototype.put=function(...args){const r=actualPlanPut.apply(this,args);if(this.transaction.db.name===abortSigningReceipt.namespace&&JSON.stringify(keyBytes(args[1]))===JSON.stringify(keyBytes(abortEvidenceKey)))r.addEventListener('success',()=>{sealWriteSucceeded=true;this.transaction.abort();},{once:true});return r;};await rejects(()=>abortSigning.capture(abortSeal),'storage_failure');} + finally{IDBObjectStore.prototype.put=actualPlanPut;} + same(sealWriteSucceeded,true);same(Array.from(await abortSigning.captured(198,0)),[]);sameRows(await workspaceBytes(abortSigningReceipt),beforeAbortCapture);same((await abortSigning.capture(abortSeal)).length,136);await abortSigning.close(); + passed('foreign-workspace output refuses and actual claim/capture aborts after write success acknowledge no retained fact'); + + const rawChange=async(n,change)=>{const raw=await rawOpen(n);try{await new Promise((resolve,reject)=>{const tx=raw.transaction('records','readwrite');change(tx.objectStore('records'));tx.oncomplete=resolve;tx.onabort=reject;});}finally{raw.close();}}; + const opaqueKey=n=>new Uint8Array(32).fill(n); + const snapshots=await Fixture.open(30,true);await snapshots.write(1,undefined,new Uint8Array([1])); + const originalSnapshot=await snapshots.snapshot(1);same(originalSnapshot.len(),1);same(originalSnapshot.redacted(),true);originalSnapshot.verify(1,new Uint8Array([1]));await rejects(()=>originalSnapshot.verify(1,new Uint8Array([2])),'record_conflict');await rejects(()=>originalSnapshot.verify(2,undefined),'invalid_input'); + const foreignConnection=await Fixture.open(30,false);await rejects(()=>foreignConnection.guarded_write(originalSnapshot,2,undefined,new Uint8Array([2])),'invalid_input');await foreignConnection.close();same(await value(snapshots,2),undefined); + const changedSnapshot=await snapshots.snapshot(1);await snapshots.write(1,new Uint8Array([1]),new Uint8Array([2]));await rejects(()=>snapshots.guarded_write(changedSnapshot,2,undefined,new Uint8Array([2])),'record_conflict');same(await value(snapshots,2),undefined); + const removedSnapshot=await snapshots.snapshot(1);await snapshots.write(1,new Uint8Array([2]),undefined);await rejects(()=>snapshots.guarded_write(removedSnapshot,2,undefined,new Uint8Array([2])),'record_conflict'); + const insertedSnapshot=await snapshots.snapshot(1);same(insertedSnapshot.len(),0);await snapshots.write(1,undefined,new Uint8Array([1]));await rejects(()=>snapshots.guarded_write(insertedSnapshot,2,undefined,new Uint8Array([2])),'record_conflict'); + same(await snapshots.guarded_write(await snapshots.snapshot(1),2,undefined,new Uint8Array([2])),1); + await rejects(async()=>snapshots.guarded_refusal(await snapshots.snapshot(1),3,undefined,new Uint8Array([3])),'transaction_precondition_refused');same(await value(snapshots,3),undefined); + try{IDBTransaction.prototype.abort=function(){if(this.db.name===name(30))return;return actualAbort.call(this);};await rejects(async()=>snapshots.guarded_refusal(await snapshots.snapshot(1),3,undefined,new Uint8Array([3])),'commit_unknown');} + finally{IDBTransaction.prototype.abort=actualAbort;} + same(await value(snapshots,3),undefined);passed('owner-bound read snapshots detect changed, removed and inserted records in the actual mutation transaction'); + await rawChange(30,store=>store.put(undefined,opaqueKey(4)));await rejects(()=>snapshots.read(4),'corrupt_record');await rejects(()=>snapshots.write(4,undefined,new Uint8Array([4])),'corrupt_record'); + const stillUndefined=await rawOpen(30);try{same(await new Promise((resolve,reject)=>{const tx=stillUndefined.transaction('records','readonly'),store=tx.objectStore('records');let count,stored;store.count(opaqueKey(4)).onsuccess=e=>count=e.target.result;store.get(opaqueKey(4)).onsuccess=e=>stored=e.target.result;tx.oncomplete=()=>resolve({count,stored});tx.onabort=reject;}),{count:1,stored:undefined});}finally{stillUndefined.close();} + await rejects(()=>snapshots.snapshot(4),'corrupt_record');await rawChange(30,store=>{store.delete(opaqueKey(4));store.put(new Uint8Array(65537),opaqueKey(5));});await rejects(()=>snapshots.snapshot(5),'corrupt_record'); + passed('stored undefined and oversized cursor values refuse before replacement or unbounded Rust copying'); + const bulkKey=n=>{const k=opaqueKey(17);new DataView(k.buffer).setUint32(28,n,false);return k;}; + await rawChange(30,store=>{store.delete(opaqueKey(5));for(let n=0;n<16384;n++)store.put(new Uint8Array(),bulkKey(n));}); + const fullSnapshot=await snapshots.snapshot(17);same(fullSnapshot.len(),16384);same(await snapshots.guarded_write(fullSnapshot,6,undefined,new Uint8Array([6])),1); + await rawChange(30,store=>store.put(new Uint8Array(),bulkKey(16384)));await rejects(()=>snapshots.snapshot(17),'capacity_exhausted'); + same(snapshots.abandon_snapshots(1,3),2);snapshots.abandon_close();await snapshots.close();const afterSnapshots=await Fixture.open(30,false);same(await value(afterSnapshots,6),[6]);await afterSnapshots.close(); + passed('actual 16384-record snapshot bound, excess refusal, bounded abandoned scans and cancelled close'); + const durabilityDb=await Fixture.open(32,true),tracedTransaction=IDBDatabase.prototype.transaction;let requestedDurability,observedDurability; + try{IDBDatabase.prototype.transaction=function(...args){if(this.name===name(32)&&args[1]==='readwrite'){requestedDurability=args[2]?.durability;const tx=nativeTransaction.call(this,args[0],args[1]);observedDurability=tx.durability;return tx;}return tracedTransaction.apply(this,args);};await rejects(()=>durabilityDb.write(1,undefined,new Uint8Array([1])),'indexeddb_unavailable');} + finally{IDBDatabase.prototype.transaction=tracedTransaction;} + same(requestedDurability,'strict');if(observedDurability==='strict')throw Error('durability refusal did not exercise ignored strict request');same(await value(durabilityDb,1),undefined); + try{IDBDatabase.prototype.transaction=function(...args){const tx=tracedTransaction.apply(this,args);if(this.name===name(32)&&args[1]==='readwrite'){requestedDurability=args[2]?.durability;observedDurability=tx.durability;}return tx;};same(await durabilityDb.write(1,undefined,new Uint8Array([1])),1);} + finally{IDBDatabase.prototype.transaction=tracedTransaction;} + same(requestedDurability,'strict');same(observedDurability,'strict');await durabilityDb.close();passed('owned writes request and observe strict durability and refuse an actually ignored hint'); + + const requestErrorDb=await Fixture.open(31,true);await requestErrorDb.write(1,undefined,new Uint8Array([1]));await requestErrorDb.write(2,undefined,new Uint8Array([2]));let constraintErrors=0; + const injectAsyncError=(namespace,key,redirect)=>{ + IDBObjectStore.prototype.put=function(bytes,at){if(this.transaction.db.name===namespace&&JSON.stringify(keyBytes(at))===JSON.stringify(keyBytes(key))){const request=originalAdd.call(this,bytes,redirect??at);request.addEventListener('error',event=>{constraintErrors++;event.preventDefault();});return request;}return actualPlanPut.call(this,bytes,at);}; + IDBTransaction.prototype.abort=function(){if(this.db.name===namespace)return;return actualAbort.call(this);}; + }; + try{injectAsyncError(name(31),opaqueKey(1));await rejects(()=>requestErrorDb.atomic_pair(2),'commit_unknown');} + finally{IDBObjectStore.prototype.put=actualPlanPut;IDBTransaction.prototype.abort=actualAbort;} + same(constraintErrors,1);same(await value(requestErrorDb,1),[1]);same(await value(requestErrorDb,2),[4]);await requestErrorDb.close(); + passed('real asynchronous ConstraintError with prevented abort cannot acknowledge a partial completed batch'); + const {owner:unknownClaimOwner,receipt:unknownClaimReceipt}=await setupIssuance(193),unknownClaimComparison=await operationKey(193,1);let unknownClaim; + try{unknownClaim=Array.from(await unknownClaimOwner.claim_unknown(193,0,()=>injectAsyncError(unknownClaimReceipt.namespace,unknownClaimComparison)));} + finally{IDBObjectStore.prototype.put=actualPlanPut;IDBTransaction.prototype.abort=actualAbort;} + same(unknownClaim.length,96);same(unknownClaim.slice(0,32),new Array(32).fill(193));await unknownClaimOwner.close(); + const retainedUnknownClaim=await openPlanReceipt(unknownClaimReceipt),actualUnknownClaim=Array.from(await retainedUnknownClaim.attempt(193,0));same(actualUnknownClaim.slice(32,64),unknownClaim.slice(64));same(Array.from(await retainedUnknownClaim.claim(193,0)),[0,...actualUnknownClaim]);await rejects(()=>retainedUnknownClaim.obtain(193,0,false),'retained_no_dispatch');await retainedUnknownClaim.close(); + passed('uncertain claim completion keeps the actual original transaction and prevents redispatch after reopen'); + const {owner:unknownSealOwner,receipt:unknownSealReceipt}=await setupIssuance(194),unknownSeal=await unknownSealOwner.obtain(194,0,false);let unknownSealAnchor; + try{injectAsyncError(unknownSealReceipt.namespace,await recordKey(194,4,0,1),await operationKey(194,1));unknownSealAnchor=Array.from(await unknownSealOwner.capture_unknown(unknownSeal));} + finally{IDBObjectStore.prototype.put=actualPlanPut;IDBTransaction.prototype.abort=actualAbort;} + same(unknownSealAnchor.length,96);same(unknownSealAnchor.slice(0,32),new Array(32).fill(194));await unknownSealOwner.close(); + const partialSealRows=await workspaceBytes(unknownSealReceipt);let partialSealOwner=await openPlanReceipt(unknownSealReceipt);await rejects(()=>partialSealOwner.captured_original(unknownSeal),'recovery_required');await partialSealOwner.close();partialSealOwner=await openPlanReceipt(unknownSealReceipt);await rejects(()=>partialSealOwner.capture(unknownSeal),'recovery_required');await partialSealOwner.close();sameRows(await workspaceBytes(unknownSealReceipt),partialSealRows); + passed('uncertain multipart capture retains its original attempt and preserves damaged output without replacement'); + const legacy=await import('./v1/fixture.js');await legacy.default(); + const legacyOwner=await legacy.WorkspaceFixture.create(195),legacyReceipt=receiptOf(legacyOwner,195);await legacyOwner.admit(195,false);await legacyOwner.close(); + const legacyRows=await workspaceBytes(legacyReceipt);await rejects(()=>openPlanReceipt(legacyReceipt),'namespace_unavailable');sameRows(await workspaceBytes(legacyReceipt),legacyRows); + const modernOwner=await WorkspaceFixture.create(196),modernReceipt=receiptOf(modernOwner,196);await modernOwner.close(); + await rejects(()=>legacy.WorkspaceFixture.open(196,new Uint8Array(modernReceipt.fingerprint),new Uint8Array(modernReceipt.selection),new Uint8Array(modernReceipt.proof)),'namespace_unavailable'); + const oldSelection=JSON.parse(new TextDecoder().decode(new Uint8Array(legacyReceipt.selection))),workspaceHex=oldSelection.workspace_id; + if(typeof workspaceHex!=='string'||!/^[0-9a-f]{64}$/.test(workspaceHex))throw Error('unexpected exact workspace identifier encoding'); + const id=Uint8Array.from(workspaceHex.match(/../g),h=>parseInt(h,16));const hash=new Uint8Array(await crypto.subtle.digest('SHA-256',new Uint8Array([...new TextEncoder().encode('radroots.browser.local_outbox.namespace.v2\0'),...id]))); + const copiedNamespace='radroots.indexeddb.v1.'+Array.from(hash,b=>b.toString(16).padStart(2,'0')).join(''); + const copiedV1=await new Promise((resolve,reject)=>{const r=indexedDB.open(copiedNamespace,1);r.onupgradeneeded=()=>r.result.createObjectStore('records');r.onsuccess=()=>resolve(r.result);r.onerror=reject;});copiedV1.close(); + 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 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:'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'); same(await workCall({kind:'workspace_open',...workspaceReceipt}),{error:'writer_active'}); @@ -458,7 +608,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}}; + 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}}; } finally {IDBDatabase.prototype.transaction=nativeTransaction;} }); await page.reload(); @@ -476,6 +626,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 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 { clearTimeout(deadline); diff --git a/crates/storage_indexeddb/tests/browser/src/lib.rs b/crates/storage_indexeddb/tests/browser/src/lib.rs @@ -10,7 +10,9 @@ pub use protected::protected_round_trip; mod persistent; pub use persistent::Persistent; mod workspace; -pub use workspace::WorkspaceFixture; +pub use workspace::{ObtainedSeal, WorkspaceFixture}; +mod snapshot; +pub use snapshot::Frozen; fn failure(error: Error) -> JsValue { JsValue::from_str(error.code()) diff --git a/crates/storage_indexeddb/tests/browser/src/snapshot.rs b/crates/storage_indexeddb/tests/browser/src/snapshot.rs @@ -0,0 +1,78 @@ +use super::{Fixture, batch, failure, key}; +use futures::FutureExt; +use radroots_storage_indexeddb::{Error, ReadSnapshot, RecordPrefix}; +use wasm_bindgen::prelude::*; + +#[wasm_bindgen] +pub struct Frozen { + value: ReadSnapshot, +} +#[wasm_bindgen] +impl Frozen { + pub fn len(&self) -> u32 { + self.value.len() as u32 + } + pub fn is_empty(&self) -> bool { + self.value.is_empty() + } + pub fn redacted(&self) -> bool { + format!("{:?}", self.value) == "ReadSnapshot(<redacted>)" + } + pub fn verify(&self, n: u8, actual: Option<Vec<u8>>) -> Result<(), JsValue> { + self.value + .verify(key(n), actual.as_deref()) + .map_err(failure) + } +} +#[wasm_bindgen] +impl Fixture { + pub async fn snapshot(&self, prefix: u8) -> Result<Frozen, JsValue> { + self.db + .read_snapshot(RecordPrefix::new([prefix; 16])) + .await + .map(|value| Frozen { value }) + .map_err(failure) + } + pub async fn guarded_write( + &self, + frozen: Frozen, + n: u8, + old: Option<Vec<u8>>, + new: Option<Vec<u8>>, + ) -> Result<usize, JsValue> { + self.db + .compare_exchange_snapshot_checked(batch(n, old, new)?, frozen.value, || true) + .await + .map(|commit| commit.records()) + .map_err(failure) + } + pub async fn guarded_refusal( + &self, + frozen: Frozen, + n: u8, + old: Option<Vec<u8>>, + new: Option<Vec<u8>>, + ) -> Result<(), JsValue> { + self.db + .compare_exchange_snapshot_checked(batch(n, old, new)?, frozen.value, || false) + .await + .map(|_| ()) + .map_err(failure) + } + pub fn abandon_snapshots(&self, prefix: u8, count: u32) -> Result<u32, JsValue> { + for n in 0..count { + if let Some(result) = self + .db + .read_snapshot(RecordPrefix::new([prefix; 16])) + .now_or_never() + { + return if matches!(result, Err(Error::Capacity)) { + Ok(n) + } else { + Err(JsValue::from_str("unexpected_immediate_snapshot")) + }; + } + } + Ok(count) + } +} 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. +mod issuance; mod plans; use futures::FutureExt; +pub use issuance::ObtainedSeal; use radroots_domain::{ ActorRole, CommandContextData, Coverage, OperationId, PublicKey, UnixSeconds, WorkspaceId, }; @@ -45,14 +47,12 @@ 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), } } } @@ -62,13 +62,6 @@ 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); } @@ -114,7 +107,6 @@ impl WorkspaceFixture { 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)) @@ -153,7 +145,7 @@ impl WorkspaceFixture { .map_err(fail)?; let result = self .owner - .query_operation( + .operation( binding, OperationId::from_bytes([n; 32]), None, @@ -223,39 +215,15 @@ impl WorkspaceFixture { selection: Vec<u8>, proof: Vec<u8>, ) -> Result<Self, JsValue> { - if selection.len() > 16 * 1024 { - return Err(JsValue::from_str("oversized_selection")); - } - let input: AttachmentInput = serde_json::from_slice(&selection) - .map_err(|_| JsValue::from_str("invalid_selection"))?; - let proof = AttachmentProof::from_protected_input(&proof).map_err(fail)?; - let fingerprint = fingerprint - .as_slice() - .try_into() - .map_err(|_| JsValue::from_str("invalid_fingerprint"))?; - let provider = Rc::new( - BrowserProvider::open(key_namespace(n), reference(), fingerprint) - .await - .map_err(|e| JsValue::from_str(e.code()))?, - ); - let clock = Rc::new(Clock::new()); - let owner = BrowserWorkspace::open_existing( - input.clone(), - copied(&proof), - provider.clone(), - reference(), - AccessPolicy::standard(), - clock.clone(), - ) - .await - .map_err(fail)?; - Ok(Self { - owner, - provider, - input, - proof, - clock, - }) + Self::open_fixture(n, fingerprint, selection, proof, false).await + } + pub async fn open_capture( + n: u8, + fingerprint: Vec<u8>, + selection: Vec<u8>, + proof: Vec<u8>, + ) -> Result<Self, JsValue> { + Self::open_fixture(n, fingerprint, selection, proof, true).await } pub fn selection(&self) -> Vec<u8> { serde_json::to_vec(&self.input).unwrap() @@ -268,7 +236,7 @@ impl WorkspaceFixture { } pub fn data_namespace(&self) -> String { let mut h = Sha256::new(); - h.update(b"radroots.browser.local_outbox.namespace.v1\0"); + h.update(b"radroots.browser.local_outbox.namespace.v2\0"); h.update(self.input.workspace_id().as_bytes()); Namespace::new(SourceGeneration::new(h.finalize().into()).unwrap()).name() } @@ -365,6 +333,59 @@ impl WorkspaceFixture { } } impl WorkspaceFixture { + async fn open_fixture( + n: u8, + fingerprint: Vec<u8>, + selection: Vec<u8>, + proof: Vec<u8>, + capture_only: bool, + ) -> Result<Self, JsValue> { + if selection.len() > 16 * 1024 { + return Err(JsValue::from_str("oversized_selection")); + } + let input: AttachmentInput = serde_json::from_slice(&selection) + .map_err(|_| JsValue::from_str("invalid_selection"))?; + let proof = AttachmentProof::from_protected_input(&proof).map_err(fail)?; + let fingerprint = fingerprint + .as_slice() + .try_into() + .map_err(|_| JsValue::from_str("invalid_fingerprint"))?; + let provider = Rc::new( + BrowserProvider::open(key_namespace(n), reference(), fingerprint) + .await + .map_err(|e| JsValue::from_str(e.code()))?, + ); + let clock = Rc::new(Clock::new()); + let owner = if capture_only { + BrowserWorkspace::open_existing_for_capture( + input.clone(), + copied(&proof), + provider.clone(), + reference(), + AccessPolicy::standard(), + clock.clone(), + ) + .await + } else { + BrowserWorkspace::open_existing( + input.clone(), + copied(&proof), + provider.clone(), + reference(), + AccessPolicy::standard(), + clock.clone(), + ) + .await + } + .map_err(fail)?; + Ok(Self { + owner, + provider, + input, + proof, + clock, + }) + } async fn request(&self, n: u8, changed: bool) -> Result<AdmissionRequest, JsValue> { let binding = self .owner diff --git a/crates/storage_indexeddb/tests/browser/src/workspace/issuance.rs b/crates/storage_indexeddb/tests/browser/src/workspace/issuance.rs @@ -0,0 +1,316 @@ +//! Synthetic real-signature S workflow through the actual protected host. +use super::{WorkspaceFixture, copied, plans::BrowserRng}; +use core::num::NonZeroU64; +use futures::FutureExt; +use nostr::JsonUtil; +use radroots_storage::command::{ + ClaimAttemptOutcome, ClaimAttemptRequest, EvidenceCaptureOutcome, EvidenceReceipt, + SealEvidence, SigningAttempt, +}; +use wasm_bindgen::prelude::*; + +fn summary(attempt: &SigningAttempt) -> Vec<u8> { + let mut raw = attempt.attempt_id().as_bytes().to_vec(); + raw.extend_from_slice(attempt.transaction_id().as_bytes()); + raw.extend_from_slice(attempt.binding().digest()); + raw.extend_from_slice(&attempt.claimed_at().get().to_be_bytes()); + raw.extend_from_slice(&attempt.deadline_unix_ms().get().to_be_bytes()); + raw.extend_from_slice(&attempt.seal().event_id()); + raw +} +fn receipt(value: EvidenceReceipt) -> Vec<u8> { + let mut raw = value.transaction_id().as_bytes().to_vec(); + raw.extend_from_slice(value.digest()); + raw.extend_from_slice(value.attempt_id().as_bytes()); + raw.extend_from_slice( + &value + .observed_at_unix_ms() + .map_or(0, NonZeroU64::get) + .to_be_bytes(), + ); + raw.extend_from_slice(value.event_id().as_bytes()); + raw +} +fn signed_output( + attempt: &SigningAttempt, + observed: Option<NonZeroU64>, +) -> Result<SealEvidence, JsValue> { + let fields = attempt.seal().fields(); + let context = nostr::secp256k1::Secp256k1::new(); + let mut scalar = [0; 32]; + scalar[31] = 1; + let keys = nostr::Keys::new_with_ctx(&context, nostr::SecretKey::from_slice(&scalar).unwrap()); + assert_eq!(keys.public_key().as_bytes(), fields.author.as_bytes()); + let signed = nostr::UnsignedEvent { + id: None, + pubkey: keys.public_key(), + created_at: nostr::Timestamp::from_secs(fields.created_at), + kind: nostr::Kind::Custom(u16::try_from(fields.kind).unwrap()), + tags: nostr::Tags::from_list(vec![]), + content: fields.content.to_owned(), + } + .sign_with_ctx(&context, &mut BrowserRng, &keys) + .unwrap(); + signed.verify_with_ctx(&context).unwrap(); + SealEvidence::verify(attempt, &signed.as_json(), observed) + .map_err(|e| JsValue::from_str(e.code())) +} +/// The test caller keeps its opaque original through failed/unknown capture. +#[wasm_bindgen] +pub struct ObtainedSeal { + value: SealEvidence, + attempt: SigningAttempt, +} +#[wasm_bindgen] +impl ObtainedSeal { + pub fn original_claim(&self) -> Vec<u8> { + summary(&self.attempt) + } + pub fn digest(&self) -> Vec<u8> { + self.value.digest().to_vec() + } + pub fn malformed_output_refused(&self) -> bool { + let original: serde_json::Value = serde_json::from_str(self.value.raw_json()).unwrap(); + ["sig", "pubkey", "content", "kind"] + .into_iter() + .all(|field| { + let mut wrong = original.clone(); + wrong[field] = match field { + "sig" => serde_json::json!("00".repeat(64)), + "pubkey" => serde_json::json!("00".repeat(32)), + "content" => serde_json::json!("wrong captured body"), + "kind" => serde_json::json!(14), + _ => unreachable!(), + }; + SealEvidence::verify(&self.attempt, &serde_json::to_string(&wrong).unwrap(), None) + .is_err() + }) + } +} +impl WorkspaceFixture { + async fn claim_request(&self, n: u8, index: u8) -> Result<ClaimAttemptRequest, 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"))?; + let recipient = bound + .plan() + .seals() + .get(index as usize) + .ok_or(JsValue::from_str("invalid_recipient"))? + .recipient(); + Ok(ClaimAttemptRequest::new( + request.binding().clone(), + request.command().context().operation_id(), + request.command().digest(), + *bound.plan().digest(), + recipient, + )) + } +} +#[wasm_bindgen] +impl WorkspaceFixture { + /// Queries through the actual original request even when retained T1 is + /// damaged; fixture request reconstruction must not hide the host refusal. + pub async fn captured_original(&self, original: &ObtainedSeal) -> Result<Vec<u8>, JsValue> { + let bound = original.attempt.bound_plan(); + let identity = bound.prepared().identity(); + let request = ClaimAttemptRequest::new( + bound.prepared().request().binding().clone(), + identity.operation_id(), + identity.command_digest(), + *bound.plan().digest(), + original.attempt.seal().recipient(), + ); + self.owner + .captured_seal(request, copied(&self.proof)) + .await + .map(|value| value.map(|v| receipt(v.receipt())).unwrap_or_default()) + .map_err(|e| JsValue::from_str(e.code())) + } + pub async fn claim(&self, n: u8, index: u8) -> Result<Vec<u8>, JsValue> { + let request = self.claim_request(n, index).await?; + match self + .owner + .claim_attempt(request, copied(&self.proof)) + .await + .map_err(|e| JsValue::from_str(e.code()))? + { + ClaimAttemptOutcome::Claimed(attempt) => { + let mut raw = vec![1]; + raw.extend(summary(&attempt)); + Ok(raw) + } + ClaimAttemptOutcome::Retained(attempt) => { + let mut raw = vec![0]; + raw.extend(summary(&attempt)); + Ok(raw) + } + ClaimAttemptOutcome::Unknown(_) => Err(JsValue::from_str("commit_unknown")), + } + } + pub async fn claim_unknown( + &self, + n: u8, + index: u8, + hook: js_sys::Function, + ) -> Result<Vec<u8>, JsValue> { + let request = self.claim_request(n, index).await?; + let operation = request.operation_id(); + let digest = request.command_digest(); + hook.call0(&JsValue::NULL)?; + match self + .owner + .claim_attempt(request, copied(&self.proof)) + .await + .map_err(|e| JsValue::from_str(e.code()))? + { + ClaimAttemptOutcome::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_claim")), + } + } + pub async fn attempt(&self, n: u8, index: u8) -> Result<Vec<u8>, JsValue> { + let request = self.claim_request(n, index).await?; + self.owner + .signing_attempt(request, copied(&self.proof)) + .await + .map(|value| value.as_ref().map(summary).unwrap_or_default()) + .map_err(|e| JsValue::from_str(e.code())) + } + pub async fn obtain( + &self, + n: u8, + index: u8, + known_time: bool, + ) -> Result<ObtainedSeal, JsValue> { + let request = self.claim_request(n, index).await?; + let attempt = match self + .owner + .claim_attempt(request, copied(&self.proof)) + .await + .map_err(|e| JsValue::from_str(e.code()))? + { + ClaimAttemptOutcome::Claimed(attempt) => attempt, + ClaimAttemptOutcome::Retained(_) => { + return Err(JsValue::from_str("retained_no_dispatch")); + } + ClaimAttemptOutcome::Unknown(_) => return Err(JsValue::from_str("commit_unknown")), + }; + let value = signed_output( + &attempt, + if known_time { + NonZeroU64::new(1_000_000) + } else { + None + }, + )?; + Ok(ObtainedSeal { value, attempt }) + } + /// Constructs a second valid synthetic output solely to test the store's + /// refusal to replace an original capture. It grants no claim/dispatch. + pub async fn capture_alternate(&self, original: &ObtainedSeal) -> Result<(), JsValue> { + 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) + .await + .map(|_| ()) + .map_err(|e| JsValue::from_str(e.code())) + } + pub async fn capture_reobserved(&self, original: &ObtainedSeal) -> Result<Vec<u8>, JsValue> { + let evidence = SealEvidence::verify( + &original.attempt, + original.value.raw_json(), + NonZeroU64::new(1_000_100), + ) + .unwrap(); + match self + .owner + .capture_signed_seal(self.input.clone(), copied(&self.proof), evidence) + .await + .map_err(|e| JsValue::from_str(e.code()))? + { + EvidenceCaptureOutcome::Committed(value) => Ok(receipt(value)), + EvidenceCaptureOutcome::Unknown(_) => Err(JsValue::from_str("commit_unknown")), + } + } + 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(), + ) + .await + .map_err(|e| JsValue::from_str(e.code()))? + { + EvidenceCaptureOutcome::Committed(value) => Ok(receipt(value)), + EvidenceCaptureOutcome::Unknown(_) => Err(JsValue::from_str("commit_unknown")), + } + } + 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(), + ) + .await + .map_err(|e| JsValue::from_str(e.code()))? + { + EvidenceCaptureOutcome::Unknown(anchor) => { + assert_eq!(anchor.operation_id(), original.value.operation_id()); + assert_eq!(anchor.command_digest(), original.value.command_digest()); + let mut raw = anchor.operation_id().as_bytes().to_vec(); + raw.extend_from_slice(anchor.command_digest().as_bytes()); + raw.extend_from_slice(anchor.transaction_id().unwrap().as_bytes()); + Ok(raw) + } + _ => Err(JsValue::from_str("unexpected_known_capture")), + } + } + 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)) + .await + .map(|value| { + value + .map(|value| receipt(value.receipt())) + .unwrap_or_default() + }) + .map_err(|e| JsValue::from_str(e.code())) + } + 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(), + ) + .now_or_never() + .is_some() + { + return Err(JsValue::from_str("unexpected_immediate_capture")); + } + Ok(()) + } +} diff --git a/crates/storage_indexeddb/tests/browser/src/workspace/plans.rs b/crates/storage_indexeddb/tests/browser/src/workspace/plans.rs @@ -19,7 +19,7 @@ extern "C" { fn fixture_panic(message: &str); } -struct BrowserRng; +pub(super) struct BrowserRng; impl RngCore for BrowserRng { fn next_u32(&mut self) -> u32 { let mut bytes = [0; 4]; @@ -206,7 +206,7 @@ impl WorkspaceFixture { pub async fn plan_query(&self, n: u8) -> Result<Vec<u8>, JsValue> { let request = self.request(n, false).await?; self.owner - .query_signing_intents( + .signing_plan( request.binding().clone(), request.command().context().operation_id(), request.command().digest(), @@ -225,9 +225,6 @@ impl WorkspaceFixture { if mode == 1 { self.clock.after.set(Some(1500)); } - if mode == 2 { - self.clock.countdown.set(Some((8, 1500))); - } if mode == 3 { self.clock.after.set(Some(90)); } diff --git a/crates/storage_sqlite/src/workspace/attempt.rs b/crates/storage_sqlite/src/workspace/attempt.rs @@ -3,63 +3,16 @@ use super::{ AttachmentInput, crypto::{IssuancePayload, IssuanceScope, WorkspaceCrypto}, }; -use radroots_domain::{ - CommandDigest, EnvelopeEventId, GrantId, OperationId, PublicKey, SigningAttemptId, - TransactionId, UnixSeconds, WorkspaceId, -}; +use radroots_domain::{PublicKey, SigningAttemptId, TransactionId, UnixSeconds}; +use radroots_storage::command::protected::issuance::ClaimRecord; use radroots_storage::command::{BoundSigningPlan, ClaimSnapshot, OperationError, SigningAttempt}; -use serde::{Deserialize, Serialize}; use sqlx::{Row, SqliteConnection}; -use zeroize::Zeroizing; pub(super) const TABLE: &str = "CREATE TABLE signing_attempts (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, recipient BLOB NOT NULL CHECK(length(recipient)=32), attempt_id BLOB NOT NULL CHECK(length(attempt_id)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), plan_digest BLOB NOT NULL CHECK(length(plan_digest)=32), intent_digest BLOB NOT NULL CHECK(length(intent_digest)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(workspace,operation_id,recipient), FOREIGN KEY(workspace,operation_id) REFERENCES signing_plans(workspace,operation_id)) STRICT, WITHOUT ROWID"; pub(super) const ID_INDEX: &str = "CREATE UNIQUE INDEX signing_attempt_identity ON signing_attempts(workspace,attempt_id)"; pub(super) const TX_INDEX: &str = "CREATE UNIQUE INDEX signing_attempt_transaction_identity ON signing_attempts(workspace,transaction_id)"; -#[derive(Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct Encoded { - version: u8, - workspace: WorkspaceId, - operation_id: OperationId, - command_digest: CommandDigest, - plan_digest: [u8; 32], - recipient: PublicKey, - attempt_id: SigningAttemptId, - transaction_id: TransactionId, - claimed_at: UnixSeconds, - intent_digest: [u8; 32], - deadline_unix_ms: u64, - preparation_transaction: TransactionId, - plan_transaction: TransactionId, - grant_id: GrantId, - expected_event: EnvelopeEventId, -} -impl Encoded { - fn new(attempt: &SigningAttempt) -> Self { - let plan = attempt.bound_plan(); - let prepared = plan.prepared(); - let identity = prepared.identity(); - Self { - version: 1, - workspace: identity.workspace_id(), - operation_id: identity.operation_id(), - command_digest: identity.command_digest(), - plan_digest: *plan.plan().digest(), - recipient: attempt.seal().recipient(), - attempt_id: attempt.attempt_id(), - transaction_id: attempt.transaction_id(), - claimed_at: attempt.claimed_at(), - intent_digest: *attempt.binding().digest(), - deadline_unix_ms: attempt.deadline_unix_ms().get(), - preparation_transaction: prepared.transaction_id(), - plan_transaction: plan.transaction_id(), - grant_id: prepared.request().binding().input().grant_id(), - expected_event: EnvelopeEventId::from_bytes(attempt.seal().event_id()), - } - } -} pub(super) fn scope(attempt: &SigningAttempt) -> IssuanceScope { let identity = attempt.bound_plan().prepared().identity(); IssuanceScope { @@ -74,9 +27,7 @@ pub(super) async fn protect( attempt: &SigningAttempt, crypto: &WorkspaceCrypto, ) -> Result<Vec<u8>, OperationError> { - let bytes = Zeroizing::new( - serde_json::to_vec(&Encoded::new(attempt)).map_err(|_| OperationError::InvalidCommand)?, - ); + let bytes = ClaimRecord::capture(attempt).encode()?; Ok(crypto .seal_issuance(scope(attempt), IssuancePayload::Attempt, 0, &bytes) .await?) @@ -133,42 +84,20 @@ pub(super) async fn read( let plaintext = crypto .open_issuance(issuance_scope, IssuancePayload::Attempt, 0, &protected) .await?; - let encoded: Encoded = plaintext - .expose_secret(|bytes| serde_json::from_slice(bytes)) - .map_err(|_| OperationError::RecoveryRequired)?; - if encoded.version != 1 - || encoded.workspace != selected.workspace_id() - || encoded.operation_id != original.operation_id() - || encoded.command_digest != original.command_digest() - || &encoded.plan_digest != bound.plan().digest() - || encoded.recipient != recipient - || encoded.attempt_id != id - || encoded.transaction_id != transaction - || encoded.preparation_transaction != bound.prepared().transaction_id() - || encoded.plan_transaction != bound.transaction_id() - || encoded.grant_id != bound.prepared().request().binding().input().grant_id() - { - return Err(OperationError::RecoveryRequired); - } - let attempt = SigningAttempt::from_committed_store( - bound, - recipient, - id, - transaction, - encoded.claimed_at, - )?; - if encoded.intent_digest != *attempt.binding().digest() + let attempt = plaintext.expose_secret(|raw| ClaimRecord::decode(raw, bound, recipient))?; + if attempt.attempt_id() != id + || attempt.transaction_id() != transaction || intent_digest.as_slice() != attempt.binding().digest() - || encoded.deadline_unix_ms != attempt.deadline_unix_ms().get() - || encoded.expected_event.as_bytes() != &attempt.seal().event_id() { return Err(OperationError::RecoveryRequired); } + let time = attempt.claimed_at(); Ok(( attempt.into_bound_plan(), - Some((id, transaction, encoded.claimed_at, protected)), + Some((id, transaction, time, protected)), )) } + pub(super) async fn insert( connection: &mut SqliteConnection, attempt: &SigningAttempt, diff --git a/crates/storage_sqlite/src/workspace/evidence.rs b/crates/storage_sqlite/src/workspace/evidence.rs @@ -3,13 +3,9 @@ use super::{ attempt, crypto::{IssuancePayload, IssuanceScope, PRIVATE_PAYLOAD_MAX_BYTES, WorkspaceCrypto}, }; -use core::num::NonZeroU64; -use radroots_domain::{ - CommandDigest, EnvelopeEventId, OperationId, PublicKey, SigningAttemptId, TransactionId, - WorkspaceId, -}; +use radroots_domain::TransactionId; +use radroots_storage::command::protected::issuance::EvidenceManifest; use radroots_storage::command::{EvidenceReceipt, OperationError, SealEvidence, SigningAttempt}; -use serde::{Deserialize, Serialize}; use sqlx::{Row, SqliteConnection}; use zeroize::Zeroizing; @@ -17,25 +13,6 @@ pub(super) const TABLE: &str = "CREATE TABLE seal_evidence (workspace BLOB NOT N pub(super) const PARTS: &str = "CREATE TABLE seal_evidence_parts (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, recipient BLOB NOT NULL, part INTEGER NOT NULL CHECK(part BETWEEN 1 AND 4), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(workspace,operation_id,recipient,part), FOREIGN KEY(workspace,operation_id,recipient) REFERENCES seal_evidence(workspace,operation_id,recipient)) STRICT, WITHOUT ROWID"; pub(super) const TX_INDEX: &str = "CREATE UNIQUE INDEX seal_evidence_transaction_identity ON seal_evidence(workspace,transaction_id)"; const MAX_PROTECTED_TOTAL: usize = 1024 * 1024; -#[derive(Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct Manifest { - version: u8, - workspace: WorkspaceId, - operation_id: OperationId, - command_digest: CommandDigest, - plan_digest: [u8; 32], - recipient: PublicKey, - attempt_id: SigningAttemptId, - claim_transaction: TransactionId, - intent_digest: [u8; 32], - event_id: EnvelopeEventId, - evidence_digest: [u8; 32], - transaction_id: TransactionId, - observed_at: Option<u64>, - byte_count: usize, - part_count: usize, -} pub(super) struct ProtectedEvidence { pub manifest: Vec<u8>, pub parts: Vec<Vec<u8>>, @@ -54,25 +31,8 @@ pub(super) async fn protect( let bytes = evidence.raw_json().as_bytes(); let chunks = bytes.chunks(PRIVATE_PAYLOAD_MAX_BYTES); let receipt = EvidenceReceipt::from_committed_store(evidence, transaction); - let manifest = Manifest { - version: 1, - workspace: evidence.workspace_id(), - operation_id: evidence.operation_id(), - command_digest: evidence.command_digest(), - plan_digest: *evidence.plan_digest(), - recipient: evidence.recipient(), - attempt_id: evidence.attempt_id(), - claim_transaction: attempt.transaction_id(), - intent_digest: *evidence.intent().digest(), - event_id: evidence.event_id(), - evidence_digest: *evidence.digest(), - transaction_id: transaction, - observed_at: evidence.observed_at_unix_ms().map(NonZeroU64::get), - byte_count: bytes.len(), - part_count: chunks.len(), - }; - let plaintext = - Zeroizing::new(serde_json::to_vec(&manifest).map_err(|_| OperationError::InvalidEvidence)?); + let manifest = EvidenceManifest::capture(attempt, evidence, transaction)?; + let plaintext = manifest.encode()?; let scope = attempt::scope(attempt); let manifest = crypto .seal_issuance(scope, IssuancePayload::Evidence, 0, &plaintext) @@ -137,36 +97,16 @@ pub(super) async fn read( let plaintext = crypto .open_issuance(scope, IssuancePayload::Evidence, 0, &manifest) .await?; - let decoded: Manifest = plaintext - .expose_secret(|value| serde_json::from_slice(value)) - .map_err(|_| OperationError::RecoveryRequired)?; - if decoded.version != 1 - || decoded.workspace != scope.workspace - || decoded.operation_id != scope.operation - || decoded.command_digest != attempt.bound_plan().prepared().identity().command_digest() - || decoded.plan_digest != scope.plan_digest - || decoded.recipient != scope.recipient - || decoded.attempt_id != scope.attempt - || decoded.claim_transaction != attempt.transaction_id() - || decoded.intent_digest != *attempt.binding().digest() - || decoded.event_id.as_bytes() != &attempt.seal().event_id() - || decoded.event_id.as_bytes().as_slice() != event_id - || decoded.attempt_id.as_bytes().as_slice() != attempt_id - || decoded.evidence_digest.as_slice() != digest - || decoded.transaction_id != transaction - || decoded.part_count != count as usize - || decoded.byte_count != bytes as usize + let decoded = plaintext.expose_secret(|raw| EvidenceManifest::decode(raw, attempt))?; + if decoded.event_id().as_bytes().as_slice() != event_id.as_slice() + || decoded.attempt_id().as_bytes().as_slice() != attempt_id.as_slice() + || decoded.evidence_digest().as_slice() != digest.as_slice() + || decoded.transaction_id() != transaction + || decoded.part_count() != count as usize + || decoded.byte_count() != bytes as usize { return Err(OperationError::RecoveryRequired); } - let observed = match decoded.observed_at { - None => None, - Some(value) => Some( - NonZeroU64::new(value) - .filter(|time| time.get() <= 253_402_300_799_999) - .ok_or(OperationError::RecoveryRequired)?, - ), - }; let (parts,total):(i64,i64)=sqlx::query_as("SELECT count(*),coalesce(sum(length(protected)),0) FROM seal_evidence_parts WHERE workspace=? AND operation_id=? AND recipient=?") .bind(scope.workspace.as_bytes().as_slice()).bind(scope.operation.as_bytes().as_slice()).bind(scope.recipient.as_bytes().as_slice()).fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; if parts != count || total <= 0 || total > (MAX_PROTECTED_TOTAL - manifest.len()) as i64 { @@ -208,11 +148,7 @@ pub(super) async fn read( protected_parts.push(protected); } let text = core::str::from_utf8(&raw).map_err(|_| OperationError::RecoveryRequired)?; - let evidence = SealEvidence::verify(attempt, text, observed) - .map_err(|_| OperationError::RecoveryRequired)?; - if evidence.digest() != &decoded.evidence_digest { - return Err(OperationError::RecoveryRequired); - } + let evidence = decoded.verify(attempt, text)?; let receipt = EvidenceReceipt::from_committed_store(&evidence, transaction); Ok(Some(( evidence, diff --git a/crates/storage_sqlite/src/workspace/tests/issuance_records.rs b/crates/storage_sqlite/src/workspace/tests/issuance_records.rs @@ -22,6 +22,7 @@ struct Issued { selected: AttachmentInput, attempt: SigningAttempt, evidence: SealEvidence, + proof: AttachmentProof, path: std::path::PathBuf, } @@ -275,6 +276,7 @@ impl Issued { selected, attempt, evidence, + proof, path, } } @@ -503,6 +505,46 @@ async fn authenticated_evidence_manifests_parts_and_exact_original_observations_ .unwrap(); assert_eq!(retained, protected); } + // Internally consistent authenticated metadata must still match the + // independent SQL indexes. Invalid metadata alone does not prove this. + let original_bytes = manifest["byte_count"].as_u64().unwrap(); + let same_parts = if original_bytes.is_multiple_of(16_384) { + original_bytes - 1 + } else { + original_bytes + 1 + }; + for byte_count in [same_parts, 1] { + let mut changed = manifest.clone(); + changed["byte_count"] = json!(byte_count); + changed["part_count"] = json!(byte_count.div_ceil(16_384)); + let protected = crypto + .seal_issuance( + scope, + IssuancePayload::Evidence, + 0, + &serde_json::to_vec(&changed).unwrap(), + ) + .await + .unwrap(); + sqlx::query("UPDATE seal_evidence SET protected=?") + .bind(&protected) + .execute(&mut database) + .await + .unwrap(); + assert_eq!( + evidence_store::read(&mut database, &issued.attempt, &crypto) + .await + .err() + .unwrap() + .code(), + "recovery_required" + ); + let retained: Vec<u8> = sqlx::query_scalar("SELECT protected FROM seal_evidence") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(retained, protected); + } sqlx::query("UPDATE seal_evidence SET protected=?") .bind(&original) .execute(&mut database) @@ -720,3 +762,113 @@ async fn authenticated_evidence_manifests_parts_and_exact_original_observations_ ); database.close().await.unwrap(); } + +#[tokio::test] +async fn actual_capture_turn_refuses_uncertainty_foreign_scope_and_fabricated_claim_reports() { + use crate::workspace::{admission::Journal, fs::Namespace, issuance::absent_claim}; + let issued = Issued::new().await; + let foreign = Issued::new().await; + let mut database = issued.database().await; + let crypto = issued.fixture.crypto(); + let namespace = Namespace::acquire(&issued.path, false).unwrap(); + let bound = issued.bound(&mut database).await; + let fake = SigningAttempt::from_committed_store( + bound, + participant(), + SigningAttemptId::from_bytes([77; 32]), + TransactionId::from_bytes([78; 32]), + UnixSeconds::new(100).unwrap(), + ) + .unwrap(); + let fabricated = SealEvidence::verify(&fake, issued.evidence.raw_json(), None).unwrap(); + let mut uncertain = true; + let clock = FixedClock(0); // Any accidental clock consultation must fail. + let mut journal = Journal { + connection: &mut database, + namespace: &namespace, + selected: &issued.selected, + crypto: &crypto, + clock: &clock, + uncertain: &mut uncertain, + }; + assert_eq!( + journal + .capture_access(&issued.selected, &issued.proof) + .await + .err() + .unwrap() + .code(), + "recovery_required" + ); + *journal.uncertain = false; + assert_eq!( + journal + .capture_access(&foreign.selected, &issued.proof) + .await + .err() + .unwrap() + .code(), + "unauthorized" + ); + let copy = || { + issued + .proof + .with_secret(|raw| AttachmentProof::from_protected_input(raw).unwrap()) + }; + assert_eq!( + journal + .capture_issuance( + issued.selected.clone(), + copy(), + foreign.evidence.retained_copy() + ) + .await + .err() + .unwrap() + .code(), + "invalid_evidence" + ); + assert_eq!( + journal + .capture_issuance(issued.selected.clone(), copy(), fabricated) + .await + .err() + .unwrap() + .code(), + "invalid_evidence" + ); + let retained = journal + .capture_issuance( + issued.selected.clone(), + copy(), + issued.evidence.retained_copy(), + ) + .await + .unwrap(); + assert!(matches!(retained, EvidenceCaptureOutcome::Committed(_))); + let operation = issued + .attempt + .bound_plan() + .prepared() + .identity() + .operation_id(); + assert_eq!( + absent_claim( + journal.connection, + &issued.selected, + operation, + participant() + ) + .await + .err() + .unwrap() + .code(), + "recovery_required" + ); + let retained = evidence_store::read(journal.connection, &issued.attempt, &crypto) + .await + .unwrap() + .unwrap(); + assert_eq!(retained.0.raw_json(), issued.evidence.raw_json()); + database.close().await.unwrap(); +}