lib

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

commit c12a2516efdea5a389a374ca09dadd512a892223
parent c4a406e256ab30d18c8bc790f6cfab6055044627
Author: triesap <tyson@radroots.org>
Date:   Tue, 20 Oct 2026 08:59:32 +0000

storage: Preserve explicit local seller outbox authority

- Separate fresh seller enrollment and exact outbox scope from stock authority
- Retain scope in authentication, attachment revalidation and prepared records
- Recover original buyer preparations without replacing retained identities or bytes
- Verify real native and browser workflows, generated APIs and contract guards

Diffstat:
Mcontracts/api_baselines/radroots_storage.txt | 7++++++-
Mcontracts/api_baselines/radroots_storage_sqlite.txt | 1+
Mcontracts/architecture/decisions/shared_sdk_compiler_preparation.v1.json | 2+-
Mcontracts/architecture/decisions/shared_sdk_refactor.v1.json | 11+++++++++++
Mcrates/execution/src/workspace.rs | 1+
Mcrates/execution/tests/workspace.rs | 5+++++
Mcrates/storage/README.md | 10+++++++++-
Mcrates/storage/src/command/protected.rs | 86++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mcrates/storage/src/workspace.rs | 31++++++++++++++++++++++++++++++-
Mcrates/storage/src/workspace/local_outbox.rs | 93++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
Mcrates/storage/tests/command.rs | 1+
Acrates/storage/tests/local_outbox.rs | 146+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage/tests/workspace.rs | 18++++++++++++++++++
Mcrates/storage_indexeddb/src/workspace/mod.rs | 4++--
Acrates/storage_indexeddb/tests/browser/seller.mjs | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_indexeddb/tests/browser/src/workspace.rs | 35++++++++++++++++++++++++++++++-----
Mcrates/storage_sqlite/src/workspace/mod.rs | 5+++--
Mcrates/storage_sqlite/src/workspace/tests/mod.rs | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/tests/operation_records.rs | 41++++++++++++++++++++++++++++++++++++++++-
Mcrates/storage_sqlite/tests/workspace_admission.rs | 6++++++
Mtools/xtask/src/architecture/decision_package.rs | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtools/xtask/src/compiler_preparation.rs | 2+-
22 files changed, 729 insertions(+), 42 deletions(-)

diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -2224,6 +2224,7 @@ pub fn radroots_storage::workspace::local_outbox::LocalOutboxConfig::enroll(self pub fn radroots_storage::workspace::local_outbox::LocalOutboxConfig::validate_at(&self, radroots_domain::context::UnixSeconds) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> impl radroots_storage::workspace::local_outbox::LocalOutboxConfig pub fn radroots_storage::workspace::local_outbox::LocalOutboxConfig::new(radroots_identity::key::PublicKey, radroots_identity::key::PublicKey, impl core::convert::AsRef<str>, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage::workspace::local_outbox::LocalOutboxConfig::seller(radroots_identity::key::PublicKey, radroots_identity::key::PublicKey, impl core::convert::AsRef<str>, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> impl core::fmt::Debug for radroots_storage::workspace::local_outbox::LocalOutboxConfig pub fn radroots_storage::workspace::local_outbox::LocalOutboxConfig::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage::workspace::local_outbox::LocalOutboxGrant @@ -2240,6 +2241,9 @@ pub const radroots_storage::workspace::local_outbox::GRANT_BYTES_MAX: usize pub const radroots_storage::workspace::local_outbox::GRANT_ENVELOPE_PURPOSE: &str pub const radroots_storage::workspace::local_outbox::GRANT_PAYLOAD_SCHEMA: &str pub fn radroots_storage::workspace::local_outbox::grant_envelope_subject(radroots_domain::identifier::WorkspaceId, radroots_domain::identifier::GrantId) -> alloc::string::String +pub enum radroots_storage::workspace::LocalOutboxScope +pub radroots_storage::workspace::LocalOutboxScope::NewBuyerOutbox +pub radroots_storage::workspace::LocalOutboxScope::NewSellerOutbox #[non_exhaustive] pub enum radroots_storage::workspace::WorkspaceError pub radroots_storage::workspace::WorkspaceError::Capacity pub radroots_storage::workspace::WorkspaceError::Closed @@ -2288,11 +2292,12 @@ pub struct radroots_storage::workspace::WorkspaceBinding impl radroots_storage::workspace::WorkspaceBinding pub const fn radroots_storage::workspace::WorkspaceBinding::actor(&self) -> radroots_domain::context::ActorRef pub const fn radroots_storage::workspace::WorkspaceBinding::expires_at(&self) -> radroots_domain::context::UnixSeconds -pub fn radroots_storage::workspace::WorkspaceBinding::from_authenticated_host(radroots_storage::workspace::AttachmentInput, radroots_domain::context::ActorRef, impl core::convert::Into<alloc::string::String>, radroots_domain::context::Sequence, radroots_domain::context::UnixSeconds, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage::workspace::WorkspaceBinding::from_authenticated_host(radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::LocalOutboxScope, radroots_domain::context::ActorRef, impl core::convert::Into<alloc::string::String>, radroots_domain::context::Sequence, radroots_domain::context::UnixSeconds, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> pub const fn radroots_storage::workspace::WorkspaceBinding::grant_revision(&self) -> radroots_domain::context::Sequence pub const fn radroots_storage::workspace::WorkspaceBinding::input(&self) -> &radroots_storage::workspace::AttachmentInput pub const fn radroots_storage::workspace::WorkspaceBinding::observed_at(&self) -> radroots_domain::context::UnixSeconds pub fn radroots_storage::workspace::WorkspaceBinding::principal_id(&self) -> &str +pub const fn radroots_storage::workspace::WorkspaceBinding::scope(&self) -> radroots_storage::workspace::LocalOutboxScope impl core::fmt::Debug for radroots_storage::workspace::WorkspaceBinding pub fn radroots_storage::workspace::WorkspaceBinding::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub trait radroots_storage::workspace::WorkspaceClock: radroots_transport::host::HostBound diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -363,6 +363,7 @@ pub mod radroots_storage_sqlite::workspace pub use radroots_storage_sqlite::workspace::AttachmentInput pub use radroots_storage_sqlite::workspace::AttachmentProof pub use radroots_storage_sqlite::workspace::LocalOutboxConfig +pub use radroots_storage_sqlite::workspace::LocalOutboxScope pub use radroots_storage_sqlite::workspace::WorkspaceBinding pub use radroots_storage_sqlite::workspace::WorkspaceClock pub use radroots_storage_sqlite::workspace::WorkspaceError diff --git a/contracts/architecture/decisions/shared_sdk_compiler_preparation.v1.json b/contracts/architecture/decisions/shared_sdk_compiler_preparation.v1.json @@ -8,7 +8,7 @@ "source_inputs": [ { "path": "contracts/architecture/decisions/shared_sdk_refactor.v1.json", - "sha256": "7937dc9ee4aca42f015d3bba5b23e2b5e7cffe461589518bd6eef6305892931e" + "sha256": "d434039e9199bd35bf51886ee3bb46f88a764b80f1bce9317381bf6fcf91d5f0" }, { "path": "contracts/architecture/decisions/services_hardening_source_lock.v4.json", diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json @@ -57,6 +57,17 @@ "payment_implementation_in_scope": false, "seller_owner_executor_optional_to_single_device": true }, + "local_outbox_authority": { + "scopes": ["new_buyer_outbox", "new_seller_outbox"], + "seller_enrollment_explicit": true, + "scope_retained_in_authenticated_binding_and_preparation": true, + "legacy_preparation_v2_scope": "new_buyer_outbox", + "scope_separates_route_genesis_and_credential_commitments": true, + "coverage": "partial", + "stock_authority": false, + "organization_or_delegation_authority": false, + "existing_order_or_history_recovery": false + }, "provenance": { "app_behavior_implementation": "independent_reimplementation", "retain_source_provenance": true, diff --git a/crates/execution/src/workspace.rs b/crates/execution/src/workspace.rs @@ -48,6 +48,7 @@ impl Attached { return Err(WorkspaceError::Closed); } if current.input() != self.binding.input() + || current.scope() != self.binding.scope() || current.actor() != self.binding.actor() || current.principal_id() != self.binding.principal_id() || current.grant_revision() != self.binding.grant_revision() diff --git a/crates/execution/tests/workspace.rs b/crates/execution/tests/workspace.rs @@ -81,6 +81,11 @@ fn binding(change: u8, observed: u64) -> WorkspaceBinding { let input = input(if change == 1 { 9 } else { 5 }); WorkspaceBinding::from_authenticated_host( input.clone(), + if change == 2 { + radroots_storage::workspace::LocalOutboxScope::NewSellerOutbox + } else { + radroots_storage::workspace::LocalOutboxScope::NewBuyerOutbox + }, ActorRef::new( key(), if change == 2 { diff --git a/crates/storage/README.md b/crates/storage/README.md @@ -78,8 +78,13 @@ pure value imports do not install an executor, spawn hidden workers, read a clock, generate identities, or perform implicit retries. -The opt-in `protected_outbox` feature supplies the pure local buyer-outbox +The opt-in `protected_outbox` feature supplies pure local buyer/seller-outbox enrollment and validated protected-grant codec at `workspace::local_outbox`. +`LocalOutboxConfig::new` selects a fresh buyer outbox; `seller` explicitly +selects a fresh seller public-authoring/communication outbox. Authenticated +bindings retain that exact scope. Neither scope grants firm stock, delegation, +organization access or recovery of old obligations. Scope separates route, +genesis and credential commitments; changing an actor cannot upgrade a grant. Concrete native/browser hosts share these rules and exact envelope context. The codec's Serde wire stays private; decoding enforces the 16 KiB limit and validates current scope. Enrollment takes qualified host identities and proof @@ -91,6 +96,9 @@ Prepared codec and pure binding/commitment checks. The complete codec is bounded to 64 KiB; a concrete host must split it to meet any smaller private-record budget, protect each record and atomically retain the full set. Decoding is a historical observation and supplies no current grant, actual commit or issuance. +New preparations retain scope explicitly in version 3. Historical version 2 +preparations remain readable only with their original buyer-outbox authority; +no actor descriptor can infer a seller grant during recovery. `BackupSource::settle_backup_writes` waits for earlier owner writes, including work whose caller was cancelled. The host excludes new writes before settling diff --git a/crates/storage/src/command/protected.rs b/crates/storage/src/command/protected.rs @@ -1,7 +1,7 @@ //! Bounded protected Prepared representation and pure scope checks shared by //! concrete transaction hosts. Decoding supplies no current access or commit. use super::{AdmissionRequest, OperationError, PreparedOperation}; -use crate::workspace::{AttachmentInput, WorkspaceBinding}; +use crate::workspace::{AttachmentInput, LocalOutboxScope, WorkspaceBinding}; use radroots_domain::{ CommandDigest, IssuanceWindow, OperationId, Sequence, TransactionId, UnixSeconds, }; @@ -18,6 +18,7 @@ pub const PREPARED_BYTES_MAX: usize = 65_536; struct Encoded<'a> { version: u8, selection: &'a AttachmentInput, + scope: LocalOutboxScope, principal: &'a str, grant_revision: Sequence, grant_expires_at: UnixSeconds, @@ -33,6 +34,8 @@ struct Encoded<'a> { struct Decoded<'a> { version: u8, selection: AttachmentInput, + #[serde(default, deserialize_with = "present_scope")] + scope: Option<LocalOutboxScope>, principal: String, grant_revision: Sequence, grant_expires_at: UnixSeconds, @@ -45,6 +48,12 @@ struct Decoded<'a> { command: &'a serde_json::value::RawValue, } +fn present_scope<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result<Option<LocalOutboxScope>, D::Error> { + LocalOutboxScope::deserialize(deserializer).map(Some) +} + /// Encodes the original immutable preparation before encryption. A host must /// independently commit it and enforce its smaller private record limit. pub fn encode( @@ -54,8 +63,9 @@ pub fn encode( ) -> Result<Zeroizing<Vec<u8>>, OperationError> { let binding = request.binding(); let encoded = Encoded { - version: 2, + version: 3, selection: binding.input(), + scope: binding.scope(), principal: binding.principal_id(), grant_revision: binding.grant_revision(), grant_expires_at: binding.expires_at(), @@ -87,7 +97,14 @@ pub fn decode( } let decoded: Decoded<'_> = serde_json::from_slice(bytes).map_err(|_| OperationError::RecoveryRequired)?; - if decoded.version != 2 || decoded.revision.get() != 1 { + let scope = match (decoded.version, decoded.scope) { + // The historical profile could only enroll buyer outboxes. It must + // never infer seller authority from a substituted retained actor. + (2, None) => LocalOutboxScope::NewBuyerOutbox, + (3, Some(scope)) => scope, + _ => return Err(OperationError::RecoveryRequired), + }; + if decoded.revision.get() != 1 { return Err(OperationError::RecoveryRequired); } let command_context: radroots_domain::CommandContextData = { @@ -101,16 +118,19 @@ pub fn decode( }; let binding = WorkspaceBinding::from_authenticated_host( decoded.selection, + scope, command_context.actor(), decoded.principal, decoded.grant_revision, decoded.grant_expires_at, decoded.captured_observed_at, - )?; + ) + .map_err(|_| OperationError::RecoveryRequired)?; if binding.input() != selected { return Err(OperationError::RecoveryRequired); } - let request = AdmissionRequest::from_protected_wire(binding, decoded.command.get().as_bytes())?; + let request = AdmissionRequest::from_protected_wire(binding, decoded.command.get().as_bytes()) + .map_err(|_| OperationError::RecoveryRequired)?; let context = request.command().context(); if context.workspace_id() != selected.workspace_id() || context.operation_id() != operation_id { return Err(OperationError::RecoveryRequired); @@ -146,6 +166,7 @@ pub fn same_binding( current: &WorkspaceBinding, ) -> Result<(), OperationError> { if captured.input() != current.input() + || captured.scope() != current.scope() || captured.actor() != current.actor() || captured.principal_id() != current.principal_id() || captured.grant_revision() != current.grant_revision() @@ -201,6 +222,60 @@ mod tests { AdmissionRequest::from_protected_wire(binding, &wire).unwrap() } #[test] + fn retained_scope_is_explicit_and_legacy_preparation_never_infers_seller_authority() { + let request = request(); + let operation = request.command().context().operation_id(); + let bytes = encode( + &request, + TransactionId::from_bytes([7; 32]), + IssuanceWindow::capture( + UnixSeconds::new(100).unwrap(), + UnixSeconds::new(150).unwrap(), + ) + .unwrap(), + ) + .unwrap(); + let original: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(original["version"], 3); + assert_eq!(original["scope"], "new_buyer_outbox"); + let read = |wire: &serde_json::Value| { + decode( + &serde_json::to_vec(wire).unwrap(), + request.binding().input(), + operation, + ) + }; + let mut legacy = original.clone(); + legacy["version"] = json!(2); + assert!(read(&legacy).is_err()); + legacy.as_object_mut().unwrap().remove("scope"); + assert_eq!( + read(&legacy).unwrap().request().binding().scope(), + LocalOutboxScope::NewBuyerOutbox + ); + legacy["command"]["context"]["actor"]["role"] = json!("seller"); + assert!(read(&legacy).is_err()); + for version in [2, 3] { + let mut null = original.clone(); + null["version"] = json!(version); + null["scope"] = serde_json::Value::Null; + assert!(read(&null).is_err()); + } + let mut missing = original.clone(); + missing.as_object_mut().unwrap().remove("scope"); + assert!(read(&missing).is_err()); + let mut mismatched = original.clone(); + mismatched["scope"] = json!("new_seller_outbox"); + assert!(read(&mismatched).is_err()); + mismatched["command"]["context"]["actor"]["role"] = json!("seller"); + let decoded = read(&mismatched).unwrap(); + assert_eq!( + decoded.request().binding().scope(), + LocalOutboxScope::NewSellerOutbox + ); + assert!(same_binding(request.binding(), decoded.request().binding()).is_err()); + } + #[test] fn original_preparation_round_trip_and_scope_are_checked_without_current_authority() { let request = request(); let operation = request.command().context().operation_id(); @@ -278,6 +353,7 @@ mod tests { let binding = request.binding(); let other = WorkspaceBinding::from_authenticated_host( binding.input().clone(), + binding.scope(), binding.actor(), "foreign-principal", binding.grant_revision(), diff --git a/crates/storage/src/workspace.rs b/crates/storage/src/workspace.rs @@ -208,11 +208,32 @@ impl<'de> serde::Deserialize<'de> for AttachmentInput { } } +/// The bounded authority of a fresh local outbox. Neither scope grants stock, +/// organization, delegation, restored history or remote executor authority. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] +pub enum LocalOutboxScope { + /// New buyer inquiry and request outbox; no existing order history. + NewBuyerOutbox, + /// New seller public authoring and private communication outbox; no stock. + NewSellerOutbox, +} +impl LocalOutboxScope { + pub(crate) const fn actor_role(self) -> radroots_domain::ActorRole { + match self { + Self::NewBuyerOutbox => radroots_domain::ActorRole::Buyer, + Self::NewSellerOutbox => radroots_domain::ActorRole::Seller, + } + } +} + /// A native/remote adapter's authenticated grant observation. It does not /// replace transaction-time checks and contains no bearer credential. #[derive(Clone, Eq, PartialEq)] pub struct WorkspaceBinding { input: AttachmentInput, + scope: LocalOutboxScope, actor: ActorRef, principal_id: Box<str>, grant_revision: Sequence, @@ -225,6 +246,7 @@ impl WorkspaceBinding { /// constructor does not turn public metadata into an authenticated context. pub fn from_authenticated_host( input: AttachmentInput, + scope: LocalOutboxScope, actor: ActorRef, principal_id: impl Into<String>, grant_revision: Sequence, @@ -232,7 +254,9 @@ impl WorkspaceBinding { observed_at: UnixSeconds, ) -> Result<Self, WorkspaceError> { let principal_id = principal_id.into(); - if actor.participant() != input.participant() + if actor.role() != scope.actor_role() + || actor.organization().is_some() + || actor.participant() != input.participant() || actor.grant_id() != Some(input.grant_id()) || principal_id.is_empty() || principal_id.len() > 128 @@ -246,6 +270,7 @@ impl WorkspaceBinding { } Ok(Self { input, + scope, actor, principal_id: principal_id.into_boxed_str(), grant_revision, @@ -257,6 +282,10 @@ impl WorkspaceBinding { pub const fn input(&self) -> &AttachmentInput { &self.input } + /// Returns the authenticated outbox authority; signing custody adds none. + pub const fn scope(&self) -> LocalOutboxScope { + self.scope + } /// Returns actor data from the persisted authenticated grant. pub const fn actor(&self) -> ActorRef { self.actor diff --git a/crates/storage/src/workspace/local_outbox.rs b/crates/storage/src/workspace/local_outbox.rs @@ -1,9 +1,9 @@ //! Shared pure enrollment and protected grant rules for concrete local hosts. //! No database, runtime, signer or provider is acquired here. -use super::{AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceError}; +use super::{AttachmentInput, AttachmentProof, LocalOutboxScope, WorkspaceBinding, WorkspaceError}; use radroots_domain::{ - ActorRef, ActorRole, AuthorityRef, CheckpointDigest, CheckpointRef, Coverage, ExecutorId, - Generation, GrantId, PublicKey, RouteDigest, Sequence, UnixSeconds, WorkspaceId, + ActorRef, AuthorityRef, CheckpointDigest, CheckpointRef, Coverage, ExecutorId, Generation, + GrantId, PublicKey, RouteDigest, Sequence, UnixSeconds, WorkspaceId, }; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -19,16 +19,18 @@ pub fn grant_envelope_subject(workspace: WorkspaceId, grant: GrantId) -> String format!("{workspace}{grant}") } /// Explicit local enrollment inputs, supplied by a trusted host interaction. -/// Creation is limited to an unrelated new buyer outbox, never seller stock. +/// Creation is limited to an unrelated new outbox, never seller stock. pub struct LocalOutboxConfig { + scope: LocalOutboxScope, participant: PublicKey, endpoint_identity: PublicKey, principal: String, expires_at: UnixSeconds, } impl LocalOutboxConfig { - /// Captures the participant, local application identity, device audit label - /// and positive expiry. This performs no authentication or filesystem work. + /// Selects a fresh buyer outbox with participant, local application identity, + /// device audit label and positive expiry. This performs no authentication + /// or filesystem work. Use `seller` for explicit fresh seller enrollment. pub fn new( participant: PublicKey, endpoint_identity: PublicKey, @@ -44,12 +46,25 @@ impl LocalOutboxConfig { return Err(WorkspaceError::InvalidInput); } Ok(Self { + scope: LocalOutboxScope::NewBuyerOutbox, participant, endpoint_identity, principal: principal.to_owned(), expires_at, }) } + /// Explicitly selects a fresh seller public-authoring/communication outbox. + /// This cannot upgrade a buyer grant or recover stock and old obligations. + pub fn seller( + participant: PublicKey, + endpoint_identity: PublicKey, + principal: impl AsRef<str>, + expires_at: UnixSeconds, + ) -> Result<Self, WorkspaceError> { + let mut config = Self::new(participant, endpoint_identity, principal, expires_at)?; + config.scope = LocalOutboxScope::NewSellerOutbox; + Ok(config) + } } impl std::fmt::Debug for LocalOutboxConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -85,14 +100,14 @@ impl LocalOutboxConfig { ); let endpoint = format!("local://workspace/{workspace}"); let mut route = Sha256::new(); - route.update(b"radroots.local_buyer_outbox.route.v1\0"); + route.update(self.scope.route_domain()); route.update(workspace.as_bytes()); route.update(executor.as_bytes()); route.update(self.endpoint_identity.as_bytes()); route.update(endpoint.as_bytes()); let route = RouteDigest::from_bytes(route.finalize().into()); let mut checkpoint = Sha256::new(); - checkpoint.update(b"radroots.local_buyer_outbox.genesis.v1\0"); + checkpoint.update(self.scope.genesis_domain()); checkpoint.update(workspace.as_bytes()); checkpoint.update(executor.as_bytes()); checkpoint.update(grant.as_bytes()); @@ -115,9 +130,10 @@ impl LocalOutboxConfig { checkpoint, route, )?; - let actor = ActorRef::new(self.participant, ActorRole::Buyer, None, Some(grant)); - let record = LocalOutboxGrant::new( + let actor = ActorRef::new(self.participant, self.scope.actor_role(), None, Some(grant)); + let record = LocalOutboxGrant::with_scope( input.clone(), + self.scope, actor, self.principal, self.expires_at, @@ -136,7 +152,7 @@ pub struct LocalOutboxGrant { #[serde(deny_unknown_fields)] struct GrantWire { version: u8, - scope: Scope, + scope: LocalOutboxScope, input: AttachmentInput, actor: ActorRef, principal: String, @@ -145,11 +161,6 @@ struct GrantWire { revoked: bool, verifier: [u8; 32], } -#[derive(Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -enum Scope { - NewBuyerOutbox, -} impl Drop for LocalOutboxGrant { fn drop(&mut self) { self.wire.verifier.zeroize(); @@ -163,11 +174,28 @@ impl LocalOutboxGrant { expires_at: UnixSeconds, proof: &AttachmentProof, ) -> Result<Self, WorkspaceError> { - let verifier = verifier(&input, proof); + Self::with_scope( + input, + LocalOutboxScope::NewBuyerOutbox, + actor, + principal, + expires_at, + proof, + ) + } + fn with_scope( + input: AttachmentInput, + scope: LocalOutboxScope, + actor: ActorRef, + principal: String, + expires_at: UnixSeconds, + proof: &AttachmentProof, + ) -> Result<Self, WorkspaceError> { + let verifier = verifier(&input, scope, proof); let record = Self { wire: GrantWire { version: 1, - scope: Scope::NewBuyerOutbox, + scope, input, actor, principal, @@ -204,7 +232,7 @@ impl LocalOutboxGrant { } fn validate(&self) -> Result<(), WorkspaceError> { if self.wire.version != 1 - || self.wire.actor.role() != ActorRole::Buyer + || self.wire.actor.role() != self.wire.scope.actor_role() || self.wire.actor.organization().is_some() || self.wire.actor.participant() != self.wire.input.participant() || self.wire.actor.grant_id() != Some(self.wire.input.grant_id()) @@ -237,6 +265,7 @@ impl LocalOutboxGrant { self.validate()?; WorkspaceBinding::from_authenticated_host( self.wire.input.clone(), + self.wire.scope, self.wire.actor, self.wire.principal.clone(), self.wire.revision, @@ -253,7 +282,7 @@ impl LocalOutboxGrant { proof: &AttachmentProof, ) -> Result<(), WorkspaceError> { // Check the complete secret commitment before projecting detailed state. - let observed = Zeroizing::new(verifier(&self.wire.input, proof)); + let observed = Zeroizing::new(verifier(&self.wire.input, self.wire.scope, proof)); if !bool::from(observed.as_ref().ct_eq(&self.wire.verifier)) { return Err(WorkspaceError::Unauthorized); } @@ -284,9 +313,29 @@ impl LocalOutboxGrant { Ok(()) } } -fn verifier(input: &AttachmentInput, proof: &AttachmentProof) -> [u8; 32] { +impl LocalOutboxScope { + fn route_domain(self) -> &'static [u8] { + match self { + Self::NewBuyerOutbox => b"radroots.local_buyer_outbox.route.v1\0", + Self::NewSellerOutbox => b"radroots.local_seller_outbox.route.v1\0", + } + } + fn genesis_domain(self) -> &'static [u8] { + match self { + Self::NewBuyerOutbox => b"radroots.local_buyer_outbox.genesis.v1\0", + Self::NewSellerOutbox => b"radroots.local_seller_outbox.genesis.v1\0", + } + } + fn credential_domain(self) -> &'static [u8] { + match self { + Self::NewBuyerOutbox => b"radroots.local_buyer_outbox.credential.v1\0", + Self::NewSellerOutbox => b"radroots.local_seller_outbox.credential.v1\0", + } + } +} +fn verifier(input: &AttachmentInput, scope: LocalOutboxScope, proof: &AttachmentProof) -> [u8; 32] { let mut digest = Sha256::new(); - digest.update(b"radroots.local_buyer_outbox.credential.v1\0"); + digest.update(scope.credential_domain()); digest.update(input.workspace_id().as_bytes()); digest.update(input.grant_id().as_bytes()); proof.with_secret(|secret| digest.update(secret)); diff --git a/crates/storage/tests/command.rs b/crates/storage/tests/command.rs @@ -34,6 +34,7 @@ fn binding() -> WorkspaceBinding { .unwrap(); WorkspaceBinding::from_authenticated_host( input, + radroots_storage::workspace::LocalOutboxScope::NewBuyerOutbox, ActorRef::new(key, ActorRole::Buyer, None, Some(grant)), "device", Sequence::new(1).unwrap(), diff --git a/crates/storage/tests/local_outbox.rs b/crates/storage/tests/local_outbox.rs @@ -0,0 +1,146 @@ +#![cfg(feature = "protected_outbox")] +use radroots_domain::{ + ActorRef, ActorRole, ExecutorId, GrantId, PublicKey, UnixSeconds, WorkspaceId, +}; +use radroots_storage::workspace::{ + AttachmentProof, LocalOutboxScope, WorkspaceError, + local_outbox::{LocalOutboxConfig, LocalOutboxGrant}, +}; + +fn key() -> PublicKey { + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() +} +fn enrolled( + seller: bool, +) -> ( + radroots_storage::workspace::AttachmentInput, + AttachmentProof, + LocalOutboxGrant, +) { + let constructor = if seller { + LocalOutboxConfig::seller + } else { + LocalOutboxConfig::new + }; + constructor( + key(), + key(), + "synthetic-device", + UnixSeconds::new(200).unwrap(), + ) + .unwrap() + .enroll( + UnixSeconds::new(100).unwrap(), + WorkspaceId::from_bytes([1; 32]), + ExecutorId::from_bytes([2; 32]), + GrantId::from_bytes([3; 32]), + AttachmentProof::from_protected_input(&[7; 32]).unwrap(), + ) + .unwrap() +} + +#[test] +fn enrollment_separates_scope_routes_genesis_and_credential_commitments() { + let (buyer, _, buyer_grant) = enrolled(false); + let (seller, _, seller_grant) = enrolled(true); + assert_ne!(buyer.route_digest(), seller.route_digest()); + assert_ne!(buyer.checkpoint(), seller.checkpoint()); + let buyer: serde_json::Value = serde_json::from_slice(&buyer_grant.encode().unwrap()).unwrap(); + let seller: serde_json::Value = + serde_json::from_slice(&seller_grant.encode().unwrap()).unwrap(); + assert_eq!(buyer["scope"], "new_buyer_outbox"); + assert_eq!(seller["scope"], "new_seller_outbox"); + assert_ne!(buyer["verifier"], seller["verifier"]); +} + +#[test] +fn both_scopes_retain_protected_access_expiry_revocation_and_exact_role() { + for (seller, scope, role) in [ + (false, LocalOutboxScope::NewBuyerOutbox, ActorRole::Buyer), + (true, LocalOutboxScope::NewSellerOutbox, ActorRole::Seller), + ] { + let (input, proof, grant) = enrolled(seller); + let mut grant = LocalOutboxGrant::decode(&grant.encode().unwrap()).unwrap(); + let bound = grant + .authenticate(&input, &proof, UnixSeconds::new(100).unwrap()) + .unwrap(); + assert_eq!(bound.scope(), scope); + assert_eq!(bound.actor().role(), role); + assert_eq!(bound.actor().organization(), None); + assert_eq!( + bound.input().checkpoint().coverage(), + radroots_domain::Coverage::Partial + ); + let wrong = AttachmentProof::from_protected_input(&[8; 32]).unwrap(); + assert_eq!( + grant + .authenticate(&input, &wrong, UnixSeconds::new(100).unwrap()) + .unwrap_err(), + WorkspaceError::Unauthorized + ); + assert_eq!( + grant + .authenticate(&input, &proof, UnixSeconds::new(0).unwrap()) + .unwrap_err(), + WorkspaceError::Unavailable + ); + assert_eq!( + grant + .authenticate(&input, &proof, UnixSeconds::new(200).unwrap()) + .unwrap_err(), + WorkspaceError::GrantExpired + ); + grant.revoke().unwrap(); + let grant = LocalOutboxGrant::decode(&grant.encode().unwrap()).unwrap(); + assert_eq!( + grant + .authenticate(&input, &proof, UnixSeconds::new(100).unwrap()) + .unwrap_err(), + WorkspaceError::GrantRevoked + ); + // Capture is limited to the original credential and never renews access. + grant.authenticate_retained_capture(&input, &proof).unwrap(); + } +} + +#[test] +fn changing_scope_and_role_cannot_upgrade_an_existing_protected_credential() { + for seller in [false, true] { + let (input, proof, grant) = enrolled(seller); + let original: serde_json::Value = serde_json::from_slice(&grant.encode().unwrap()).unwrap(); + let mut changed = original.clone(); + changed["actor"]["role"] = serde_json::json!(if seller { "buyer" } else { "seller" }); + assert!(matches!( + LocalOutboxGrant::decode(&serde_json::to_vec(&changed).unwrap()), + Err(WorkspaceError::RecoveryRequired) + )); + changed["scope"] = serde_json::json!(if seller { + "new_buyer_outbox" + } else { + "new_seller_outbox" + }); + let changed = LocalOutboxGrant::decode(&serde_json::to_vec(&changed).unwrap()).unwrap(); + assert_eq!( + changed + .authenticate(&input, &proof, UnixSeconds::new(100).unwrap()) + .unwrap_err(), + WorkspaceError::Unauthorized + ); + for scope in ["seller_stock", "remote_executor", "organization", "unknown"] { + let mut changed = original.clone(); + changed["scope"] = serde_json::json!(scope); + assert!(LocalOutboxGrant::decode(&serde_json::to_vec(&changed).unwrap()).is_err()); + } + // The original buyer constructor never accepts a seller actor. + assert!( + LocalOutboxGrant::new( + input.clone(), + ActorRef::new(key(), ActorRole::Seller, None, Some(input.grant_id())), + "device".into(), + UnixSeconds::new(200).unwrap(), + &proof + ) + .is_err() + ); + } +} diff --git a/crates/storage/tests/workspace.rs b/crates/storage/tests/workspace.rs @@ -83,6 +83,7 @@ fn host_observations_validate_internal_binding_without_authenticating_metadata() let binding = |actor, principal: &str, revision, expiry, observed| { WorkspaceBinding::from_authenticated_host( input(), + radroots_storage::workspace::LocalOutboxScope::NewBuyerOutbox, actor, principal, Sequence::new(revision).unwrap(), @@ -92,6 +93,10 @@ fn host_observations_validate_internal_binding_without_authenticating_metadata() }; let observed = binding(actor(), "device", 1, 200, 100).unwrap(); assert_eq!(observed.input(), &input()); + assert_eq!( + observed.scope(), + radroots_storage::workspace::LocalOutboxScope::NewBuyerOutbox + ); assert_eq!(observed.actor(), actor()); assert_eq!(observed.principal_id(), "device"); assert_eq!(observed.grant_revision().get(), 1); @@ -120,6 +125,19 @@ fn host_observations_validate_internal_binding_without_authenticating_metadata() PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5") .unwrap(); for invalid in [ + ActorRef::new(key(), ActorRole::Seller, None, Some(input().grant_id())), + ActorRef::new( + key(), + ActorRole::Coordinator, + None, + Some(input().grant_id()), + ), + ActorRef::new( + key(), + ActorRole::Buyer, + Some(key()), + Some(input().grant_id()), + ), ActorRef::new(other_key, ActorRole::Buyer, None, Some(input().grant_id())), ActorRef::new(key(), ActorRole::Buyer, None, None), ActorRef::new( diff --git a/crates/storage_indexeddb/src/workspace/mod.rs b/crates/storage_indexeddb/src/workspace/mod.rs @@ -1,5 +1,5 @@ //! Authenticated browser local outboxes, independent of participant signing. -//! Creation establishes a fresh unrelated buyer outbox only. Existing state +//! Creation establishes a fresh unrelated buyer or explicitly selected seller outbox. Existing state //! requires its independently retained selection and protected proof. mod address; mod crypto; @@ -348,7 +348,7 @@ pub struct BrowserWorkspace { state: Rc<State>, } impl BrowserWorkspace { - /// Enrolls only a new unrelated buyer outbox and returns its independently + /// Enrolls only a new unrelated buyer or seller outbox and returns its independently /// retained selection/proof after the protected grant actually commits. pub async fn initialize_local_outbox( config: LocalOutboxConfig, diff --git a/crates/storage_indexeddb/tests/browser/seller.mjs b/crates/storage_indexeddb/tests/browser/seller.mjs @@ -0,0 +1,97 @@ +import assert from 'node:assert/strict'; +import {createServer} from 'node:http'; +import {readFile} from 'node:fs/promises'; +import {createRequire} from 'node:module'; +import {resolve, sep} from 'node:path'; + +const [moduleRoot, packageDir, engine, previousPackageDir] = process.argv.slice(2); +assert(moduleRoot && packageDir && previousPackageDir && ['chromium','firefox','webkit'].includes(engine)); +const playwright = createRequire(resolve(moduleRoot,'package.json'))('playwright'); +const root = resolve(packageDir), previousRoot = resolve(previousPackageDir); +async function workflow({WorkspaceFixture}, previous) { + const tests = []; + const check = (condition) => { if (!condition) throw Error('seller scope assertion'); }; + const refuses = async (action, code) => { + try { await action(); } catch (error) { + if (String(error) !== code) throw Error('expected ' + code + ', received ' + String(error)); + return; + } + throw Error('expected ' + code); + }; + const old = await previous.WorkspaceFixture.create(244); + const oldFingerprint = old.fingerprint(), oldSelection = old.selection(), oldProof = old.proof(); + const original = Array.from(await old.admit(243, false)); + await old.close(); + const current = await WorkspaceFixture.open(244, oldFingerprint, oldSelection, oldProof); + check(!await current.is_seller()); + check(JSON.stringify(Array.from(await current.query(243))) === JSON.stringify(original)); + check(JSON.stringify(Array.from(await current.admit(243, false))) === JSON.stringify(original)); + await current.close(); + tests.push('original published buyer preparation reopens and replays without replacement'); + const seller = await WorkspaceFixture.create_seller(245); + check(await seller.is_seller()); + check(await seller.authenticate() === 1); + await refuses(() => seller.wrong_proof(), 'unauthorized'); + tests.push('explicit protected seller scope and exact credential'); + const fingerprint = seller.fingerprint(), selection = seller.selection(), proof = seller.proof(); + const preparation = Array.from(await seller.admit(244, false)); + await seller.close(); + const reopened = await WorkspaceFixture.open(245, fingerprint, selection, proof); + check(await reopened.is_seller()); + check(JSON.stringify(Array.from(await reopened.query(244))) === JSON.stringify(preparation)); + tests.push('actual protected close/reopen retains seller scope and original preparation'); + reopened.set_time(2000); + await refuses(() => reopened.authenticate(), 'grant_expired'); + reopened.set_time(1000); + await reopened.revoke(); + await reopened.close(); + await refuses(() => WorkspaceFixture.open(245, fingerprint, selection, proof), 'grant_revoked'); + const capture = await WorkspaceFixture.open_capture(245, fingerprint, selection, proof); + await refuses(() => capture.authenticate(), 'unauthorized'); + await capture.close(); + tests.push('expiry and persisted revocation refuse normal reopen and access'); + const buyer = await WorkspaceFixture.create(246); + check(!await buyer.is_seller()); + check(await buyer.authenticate() === 1); + await buyer.close(); + tests.push('independent buyer enrollment retains buyer scope'); + return tests; +} +const source = `import init, * as fixture from '/fixture.js'; import previousInit, * as previous from '/before/fixture.js'; +const run = ${workflow.toString()}; +self.onmessage = async () => { try { await init(); await previousInit(); self.postMessage({tests:await run(fixture, previous)}); } +catch(error) { self.postMessage({error:String(error)}); } };`; +const server = createServer(async (req,res) => { + try { + const name = new URL(req.url,'http://localhost').pathname; + if (name === '/') { res.setHeader('content-type','text/html'); res.end('<!doctype html><title>Protected seller outbox</title>'); return; } + if (name === '/worker.mjs') { res.setHeader('content-type','text/javascript'); res.end(source); return; } + const selectedRoot = name.startsWith('/before/') ? previousRoot : root; + const path = resolve(selectedRoot, '.' + (name.startsWith('/before/') ? name.slice(7) : name)); + assert(path.startsWith(selectedRoot + sep)); + res.setHeader('content-type',path.endsWith('.wasm')?'application/wasm':'text/javascript'); + res.end(await readFile(path)); + } catch { res.writeHead(404); res.end(); } +}); +await new Promise(done => server.listen(0,'127.0.0.1',done)); +const browser = await playwright[engine].launch({headless:true}); +const watchdog = setTimeout(() => { void browser.close(); },180_000); +watchdog.unref(); +const results = []; +try { + for (const contextName of ['page','worker']) { + const context = await browser.newContext(); + try { + const page = await context.newPage(); + page.setDefaultTimeout(60_000); + await page.goto(`http://127.0.0.1:${server.address().port}`); + const tests = contextName === 'page' + ? await page.evaluate(async code => { const fixture = await import('/fixture.js'); await fixture.default(); const previous = await import('/before/fixture.js'); await previous.default(); return await (0,eval)(`(${code})`)(fixture,previous); },workflow.toString()) + : await page.evaluate(() => new Promise((done,fail) => { const worker = new Worker('/worker.mjs',{type:'module'}); const timer = setTimeout(() => { worker.terminate(); fail(Error('worker timeout')); },60_000); worker.onmessage = event => { clearTimeout(timer); worker.terminate(); event.data.error ? fail(Error(event.data.error)) : done(event.data.tests); }; worker.onerror = error => { clearTimeout(timer); worker.terminate(); fail(Error(error.message)); }; worker.postMessage({run:true}); })); + assert.equal(tests.length,5); + results.push({context:contextName,tests}); + console.error(JSON.stringify({engine,context:contextName,passed:tests.length})); + } finally { await context.close(); } + } + console.log(JSON.stringify({engine,version:browser.version(),results})); +} finally { clearTimeout(watchdog); await browser.close(); await new Promise(done => server.close(done)); } diff --git a/crates/storage_indexeddb/tests/browser/src/workspace.rs b/crates/storage_indexeddb/tests/browser/src/workspace.rs @@ -213,10 +213,13 @@ impl WorkspaceFixture { }) } pub async fn create(n: u8) -> Result<Self, JsValue> { - Self::initialize(n, false).await + Self::initialize(n, false, false).await + } + pub async fn create_seller(n: u8) -> Result<Self, JsValue> { + Self::initialize(n, false, true).await } pub async fn create_expiring(n: u8) -> Result<(), JsValue> { - let owner = Self::initialize(n, true).await?; + let owner = Self::initialize(n, true, false).await?; owner.close().await } pub async fn open( @@ -262,13 +265,30 @@ impl WorkspaceFixture { .authenticate(self.input.clone(), copied(&self.proof)) .await .map_err(fail)?; - assert_eq!(bound.actor().role(), ActorRole::Buyer); + assert_eq!( + bound.actor().role(), + match bound.scope() { + radroots_storage::workspace::LocalOutboxScope::NewBuyerOutbox => ActorRole::Buyer, + radroots_storage::workspace::LocalOutboxScope::NewSellerOutbox => ActorRole::Seller, + } + ); assert_eq!(bound.actor().organization(), None); assert_eq!(bound.input(), &self.input); assert_eq!(bound.actor().grant_id(), Some(self.input.grant_id())); assert_eq!(bound.input().checkpoint().coverage(), Coverage::Partial); Ok(bound.grant_revision().get() as u32) } + pub async fn is_seller(&self) -> Result<bool, JsValue> { + let bound = self + .owner + .authenticate(self.input.clone(), copied(&self.proof)) + .await + .map_err(fail)?; + Ok( + bound.scope() == radroots_storage::workspace::LocalOutboxScope::NewSellerOutbox + && bound.actor().role() == ActorRole::Seller, + ) + } pub async fn wrong_proof(&self) -> Result<(), JsValue> { self.owner .authenticate( @@ -438,7 +458,7 @@ impl WorkspaceFixture { AdmissionRequest::from_protected_wire(binding, &wire) .map_err(|e| JsValue::from_str(e.code())) } - async fn initialize(n: u8, expire: bool) -> Result<Self, JsValue> { + async fn initialize(n: u8, expire: bool, seller: bool) -> Result<Self, JsValue> { let provider = Rc::new( BrowserProvider::create(key_namespace(n), reference()) .await @@ -448,7 +468,12 @@ impl WorkspaceFixture { if expire { clock.after.set(Some(2000)); } - let config = LocalOutboxConfig::new( + let constructor = if seller { + LocalOutboxConfig::seller + } else { + LocalOutboxConfig::new + }; + let config = constructor( participant(), participant(), "synthetic-browser", diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs @@ -1,4 +1,4 @@ -//! Explicit protected local buyer-outbox attachment. +//! Explicit protected local buyer/seller-outbox attachment. //! //! This host cannot acquire seller stock authority, attach a remote endpoint, //! continue an existing order or restore state from a participant key. Its @@ -25,7 +25,8 @@ mod tests; pub use crypto::WorkspaceCrypto; pub use radroots_storage::workspace::{ - AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceError, + AttachmentInput, AttachmentProof, LocalOutboxScope, WorkspaceBinding, WorkspaceClock, + WorkspaceError, }; use radroots_domain::{ExecutorId, GrantId, PublicKey, WorkspaceId}; diff --git a/crates/storage_sqlite/src/workspace/tests/mod.rs b/crates/storage_sqlite/src/workspace/tests/mod.rs @@ -314,6 +314,115 @@ impl WorkspaceClock for FixedClock { } } #[tokio::test] +async fn seller_scope_survives_protected_close_reopen_without_stock_or_buyer_upgrade() { + let fixture = CryptoFixture::new(); + let path = fixture + ._temp + .path() + .canonicalize() + .unwrap() + .join("seller-outbox"); + let (owner, input, proof) = NativeWorkspace::initialize_local_outbox( + &path, + LocalOutboxConfig::seller( + participant(), + participant(), + "seller-device", + UnixSeconds::new(200).unwrap(), + ) + .unwrap(), + fixture.crypto(), + Arc::new(FixedClock(100)), + ) + .await + .unwrap(); + let binding = owner.authenticate(input.clone(), &proof).await.unwrap(); + assert_eq!(binding.scope(), LocalOutboxScope::NewSellerOutbox); + assert_eq!(binding.actor().role(), ActorRole::Seller); + assert_eq!(binding.actor().organization(), None); + assert_eq!(input.checkpoint().coverage(), Coverage::Partial); + owner.close().await.unwrap(); + let reopened = NativeWorkspace::open_existing( + &path, + input.clone(), + fixture.crypto(), + Arc::new(FixedClock(100)), + ) + .await + .unwrap(); + assert_eq!( + reopened.authenticate(input.clone(), &proof).await.unwrap(), + binding + ); + let wrong = AttachmentProof::from_protected_input(&[0xEF; 32]).unwrap(); + assert_eq!( + reopened + .authenticate(input.clone(), &wrong) + .await + .unwrap_err(), + WorkspaceError::Unauthorized + ); + reopened.close().await.unwrap(); + let expired = NativeWorkspace::open_existing( + &path, + input.clone(), + fixture.crypto(), + Arc::new(FixedClock(200)), + ) + .await + .unwrap(); + assert_eq!( + expired + .authenticate(input.clone(), &proof) + .await + .unwrap_err(), + WorkspaceError::GrantExpired + ); + expired.close().await.unwrap(); + let reopened = NativeWorkspace::open_existing( + &path, + input.clone(), + fixture.crypto(), + Arc::new(FixedClock(100)), + ) + .await + .unwrap(); + reopened.revoke(input.clone(), &proof).await.unwrap(); + reopened.close().await.unwrap(); + let revoked = NativeWorkspace::open_existing( + &path, + input.clone(), + fixture.crypto(), + Arc::new(FixedClock(100)), + ) + .await + .unwrap(); + assert_eq!( + revoked + .authenticate(input.clone(), &proof) + .await + .unwrap_err(), + WorkspaceError::GrantRevoked + ); + revoked.close().await.unwrap(); + assert!(matches!( + NativeWorkspace::initialize_local_outbox( + &path, + LocalOutboxConfig::new( + participant(), + participant(), + "buyer", + UnixSeconds::new(200).unwrap() + ) + .unwrap(), + fixture.crypto(), + Arc::new(FixedClock(100)), + ) + .await, + Err(WorkspaceError::NamespaceUnavailable) + )); +} +#[tokio::test] async fn enrollment_requires_bounded_principal_current_time_and_usable_key() { for principal in [String::new(), "x".repeat(129), "bad\nlabel".into()] { assert!(matches!( diff --git a/crates/storage_sqlite/src/workspace/tests/operation_records.rs b/crates/storage_sqlite/src/workspace/tests/operation_records.rs @@ -71,8 +71,47 @@ async fn protected_operation_read_refuses_each_inconsistent_payload_and_sql_proj .await .unwrap(); let value: Value = opened.expose_secret(|bytes| serde_json::from_slice(bytes).unwrap()); + assert_eq!(value["version"], 3); + assert_eq!(value["scope"], "new_buyer_outbox"); + // Existing buyer preparations predate explicit scope. Reading one must + // retain its original identity and bytes, never rewrite it as a new grant. + let mut legacy = value.clone(); + legacy["version"] = json!(2); + legacy.as_object_mut().unwrap().remove("scope"); + let legacy = crypto + .seal_operation( + selected.workspace_id(), + operation_id, + &serde_json::to_vec(&legacy).unwrap(), + ) + .await + .unwrap(); + sqlx::query("UPDATE operations SET protected=?") + .bind(&legacy) + .execute(&mut database) + .await + .unwrap(); + let (recovered, legacy_retained) = + operation::read(&mut database, &selected, operation_id, &crypto) + .await + .unwrap() + .unwrap(); + assert_eq!(recovered.identity(), retained.identity()); + assert_eq!( + recovered.request().binding().scope(), + radroots_storage::workspace::LocalOutboxScope::NewBuyerOutbox + ); + assert_eq!(legacy_retained, legacy); + assert_eq!( + sqlx::query_scalar::<_, Vec<u8>>("SELECT protected FROM operations") + .fetch_one(&mut database) + .await + .unwrap(), + legacy + ); for (pointer, replacement) in [ - ("/version", json!(3)), + ("/version", json!(4)), + ("/scope", json!("new_seller_outbox")), ("/prepared_at", json!("0")), ("/prepared_at", json!("99")), ("/first_issue_not_after", json!("100")), diff --git a/crates/storage_sqlite/tests/workspace_admission.rs b/crates/storage_sqlite/tests/workspace_admission.rs @@ -615,6 +615,7 @@ async fn unqualified_history_and_approval_descriptors_never_become_admitted_comm )); let other = WorkspaceBinding::from_authenticated_host( binding.input().clone(), + binding.scope(), binding.actor(), "substituted-device", binding.grant_revision(), @@ -652,6 +653,11 @@ async fn unqualified_history_and_approval_descriptors_never_become_admitted_comm ] { let substituted = WorkspaceBinding::from_authenticated_host( binding.input().clone(), + if actor.role() == radroots_domain::ActorRole::Seller { + radroots_storage::workspace::LocalOutboxScope::NewSellerOutbox + } else { + binding.scope() + }, actor, binding.principal_id(), revision, diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -23,6 +23,7 @@ struct Policy { deferred_application_migrations: Vec<String>, retained_capability_families: Vec<String>, independence: Independence, + local_outbox_authority: LocalOutboxAuthority, provenance: Provenance, targets: Targets, portability: Portability, @@ -77,6 +78,20 @@ struct Independence { #[derive(Deserialize)] #[serde(deny_unknown_fields)] +struct LocalOutboxAuthority { + scopes: Vec<String>, + seller_enrollment_explicit: bool, + scope_retained_in_authenticated_binding_and_preparation: bool, + legacy_preparation_v2_scope: String, + scope_separates_route_genesis_and_credential_commitments: bool, + coverage: String, + stock_authority: bool, + organization_or_delegation_authority: bool, + existing_order_or_history_recovery: bool, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] struct Provenance { app_behavior_implementation: String, retain_source_provenance: bool, @@ -224,6 +239,19 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { "prospective identity or publication authority drift", )?; validate_ownership(&p)?; + let local = &p.local_outbox_authority; + require( + exact_set(&local.scopes, &["new_buyer_outbox", "new_seller_outbox"]) + && local.seller_enrollment_explicit + && local.scope_retained_in_authenticated_binding_and_preparation + && local.legacy_preparation_v2_scope == "new_buyer_outbox" + && local.scope_separates_route_genesis_and_credential_commitments + && local.coverage == "partial" + && !local.stock_authority + && !local.organization_or_delegation_authority + && !local.existing_order_or_history_recovery, + "local outbox authority drift", + )?; validate_targets(&p.targets, &p.portability)?; validate_packages(&p.packages)?; validate_values(&p.values, &p.limits)?; @@ -695,6 +723,38 @@ mod tests { } #[test] + fn local_outboxes_cannot_upgrade_legacy_buyer_or_claim_stock_and_restored_history() { + for (field, bad) in [ + ("scopes", json!(["new_buyer_outbox", "seller_stock"])), + ( + "scopes", + json!(["new_buyer_outbox", "new_buyer_outbox", "new_seller_outbox"]), + ), + ("seller_enrollment_explicit", json!(false)), + ( + "scope_retained_in_authenticated_binding_and_preparation", + json!(false), + ), + ("legacy_preparation_v2_scope", json!("new_seller_outbox")), + ( + "scope_separates_route_genesis_and_credential_commitments", + json!(false), + ), + ("coverage", json!("satisfied")), + ("stock_authority", json!(true)), + ("organization_or_delegation_authority", json!(true)), + ("existing_order_or_history_recovery", json!(true)), + ] { + assert!( + validate_bytes(&changed(&format!("/local_outbox_authority/{field}"), bad)).is_err(), + "{field}" + ); + } + let mut unknown: Value = serde_json::from_str(SOURCE).unwrap(); + unknown["local_outbox_authority"]["unknown"] = json!(true); + assert!(validate_bytes(&serde_json::to_vec(&unknown).unwrap()).is_err()); + } + #[test] fn signing_unknown_and_receipt_cannot_become_spend_authority() { for (field, bad) in [ ("fresh_same_key_cache_can_allocate", true), diff --git a/tools/xtask/src/compiler_preparation.rs b/tools/xtask/src/compiler_preparation.rs @@ -12,7 +12,7 @@ const MAX_CONTRACT_BYTES: usize = 65_536; const BOUND_INPUTS: [(&str, &str); 3] = [ ( "contracts/architecture/decisions/shared_sdk_refactor.v1.json", - "7937dc9ee4aca42f015d3bba5b23e2b5e7cffe461589518bd6eef6305892931e", + "d434039e9199bd35bf51886ee3bb46f88a764b80f1bce9317381bf6fcf91d5f0", ), ( "contracts/architecture/decisions/services_hardening_source_lock.v4.json",