commit 09c5b616052b5158947a123fef8d949849563a82 parent 3ef5f73f9b54e45df2f81b695cace0d950858b02 Author: triesap <tyson@radroots.org> Date: Sat, 24 Oct 2026 17:13:06 +0000 storage: separate workspace scope from outbox admission - Generalize the shared scope and grant types for the native executor boundary. - Preserve retained outbox wire data and refuse stock-owner claims explicitly. - Verify actual protected scope refusals in native and all three browsers. - Regenerate affected public APIs and retain seller page and worker workflows. Diffstat:
30 files changed, 534 insertions(+), 305 deletions(-)
diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -2289,33 +2289,32 @@ pub fn radroots_storage::status::StorageStatusProvider::storage_status(&self) -> impl radroots_storage::status::StorageStatusProvider for radroots_storage::memory::MemoryStorage pub fn radroots_storage::memory::MemoryStorage::storage_status(&self) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::status::StorageStatus, radroots_storage::Error>> pub mod radroots_storage::workspace +pub mod radroots_storage::workspace::grant +pub struct radroots_storage::workspace::grant::WorkspaceGrant +impl radroots_storage::workspace::grant::WorkspaceGrant +pub fn radroots_storage::workspace::grant::WorkspaceGrant::authenticate(&self, &radroots_storage::workspace::AttachmentInput, &radroots_storage::workspace::AttachmentProof, radroots_domain::context::UnixSeconds) -> core::result::Result<radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage::workspace::grant::WorkspaceGrant::authenticate_retained_capture(&self, &radroots_storage::workspace::AttachmentInput, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage::workspace::grant::WorkspaceGrant::decode(&[u8]) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage::workspace::grant::WorkspaceGrant::decode_outbox(&[u8]) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage::workspace::grant::WorkspaceGrant::encode(&self) -> core::result::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>, radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage::workspace::grant::WorkspaceGrant::new(radroots_storage::workspace::AttachmentInput, radroots_domain::context::ActorRef, alloc::string::String, radroots_domain::context::UnixSeconds, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage::workspace::grant::WorkspaceGrant::revoke(&mut self) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> +impl core::ops::drop::Drop for radroots_storage::workspace::grant::WorkspaceGrant +pub fn radroots_storage::workspace::grant::WorkspaceGrant::drop(&mut self) +pub const radroots_storage::workspace::grant::GRANT_BYTES_MAX: usize +pub const radroots_storage::workspace::grant::GRANT_ENVELOPE_PURPOSE: &str +pub const radroots_storage::workspace::grant::GRANT_PAYLOAD_SCHEMA: &str +pub fn radroots_storage::workspace::grant::grant_envelope_subject(radroots_domain::identifier::WorkspaceId, radroots_domain::identifier::GrantId) -> alloc::string::String pub mod radroots_storage::workspace::local_outbox pub struct radroots_storage::workspace::local_outbox::LocalOutboxConfig impl radroots_storage::workspace::local_outbox::LocalOutboxConfig -pub fn radroots_storage::workspace::local_outbox::LocalOutboxConfig::enroll(self, radroots_domain::context::UnixSeconds, radroots_domain::identifier::WorkspaceId, radroots_domain::identifier::ExecutorId, radroots_domain::identifier::GrantId, radroots_storage::workspace::AttachmentProof) -> core::result::Result<(radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof, radroots_storage::workspace::local_outbox::LocalOutboxGrant), radroots_storage::workspace::WorkspaceError> +pub fn radroots_storage::workspace::local_outbox::LocalOutboxConfig::enroll(self, radroots_domain::context::UnixSeconds, radroots_domain::identifier::WorkspaceId, radroots_domain::identifier::ExecutorId, radroots_domain::identifier::GrantId, radroots_storage::workspace::AttachmentProof) -> core::result::Result<(radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof, radroots_storage::workspace::grant::WorkspaceGrant), radroots_storage::workspace::WorkspaceError> pub fn radroots_storage::workspace::local_outbox::LocalOutboxConfig::validate_at(&self, radroots_domain::context::UnixSeconds) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> impl radroots_storage::workspace::local_outbox::LocalOutboxConfig pub fn radroots_storage::workspace::local_outbox::LocalOutboxConfig::new(radroots_identity::key::PublicKey, radroots_identity::key::PublicKey, impl core::convert::AsRef<str>, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> 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 -impl radroots_storage::workspace::local_outbox::LocalOutboxGrant -pub fn radroots_storage::workspace::local_outbox::LocalOutboxGrant::authenticate(&self, &radroots_storage::workspace::AttachmentInput, &radroots_storage::workspace::AttachmentProof, radroots_domain::context::UnixSeconds) -> core::result::Result<radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::WorkspaceError> -pub fn radroots_storage::workspace::local_outbox::LocalOutboxGrant::authenticate_retained_capture(&self, &radroots_storage::workspace::AttachmentInput, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> -pub fn radroots_storage::workspace::local_outbox::LocalOutboxGrant::decode(&[u8]) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> -pub fn radroots_storage::workspace::local_outbox::LocalOutboxGrant::encode(&self) -> core::result::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>, radroots_storage::workspace::WorkspaceError> -pub fn radroots_storage::workspace::local_outbox::LocalOutboxGrant::new(radroots_storage::workspace::AttachmentInput, radroots_domain::context::ActorRef, alloc::string::String, radroots_domain::context::UnixSeconds, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> -pub fn radroots_storage::workspace::local_outbox::LocalOutboxGrant::revoke(&mut self) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> -impl core::ops::drop::Drop for radroots_storage::workspace::local_outbox::LocalOutboxGrant -pub fn radroots_storage::workspace::local_outbox::LocalOutboxGrant::drop(&mut self) -pub const radroots_storage::workspace::local_outbox::GRANT_BYTES_MAX: usize -pub const radroots_storage::workspace::local_outbox::GRANT_ENVELOPE_PURPOSE: &str -pub const radroots_storage::workspace::local_outbox::GRANT_PAYLOAD_SCHEMA: &str -pub fn radroots_storage::workspace::local_outbox::grant_envelope_subject(radroots_domain::identifier::WorkspaceId, radroots_domain::identifier::GrantId) -> alloc::string::String -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 @@ -2339,6 +2338,10 @@ pub fn radroots_storage::command::OperationError::from(radroots_storage::workspa impl core::error::Error for radroots_storage::workspace::WorkspaceError impl core::fmt::Display for radroots_storage::workspace::WorkspaceError pub fn radroots_storage::workspace::WorkspaceError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub enum radroots_storage::workspace::WorkspaceScope +pub radroots_storage::workspace::WorkspaceScope::NewBuyerOutbox +pub radroots_storage::workspace::WorkspaceScope::NewSellerOutbox +pub radroots_storage::workspace::WorkspaceScope::SellerStockOwner pub struct radroots_storage::workspace::AttachmentInput impl radroots_storage::workspace::AttachmentInput pub const fn radroots_storage::workspace::AttachmentInput::authority(&self) -> radroots_domain::context::AuthorityRef @@ -2364,12 +2367,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_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 fn radroots_storage::workspace::WorkspaceBinding::from_authenticated_host(radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::WorkspaceScope, 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 +pub const fn radroots_storage::workspace::WorkspaceBinding::scope(&self) -> radroots_storage::workspace::WorkspaceScope 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,10 +363,10 @@ 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 +pub use radroots_storage_sqlite::workspace::WorkspaceScope pub struct radroots_storage_sqlite::workspace::NativeWorkspace impl radroots_storage_sqlite::workspace::NativeWorkspace pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::authenticate(&self, radroots_storage::workspace::AttachmentInput, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::WorkspaceError> diff --git a/contracts/architecture/decisions/browser_workspace.v2.json b/contracts/architecture/decisions/browser_workspace.v2.json @@ -5,7 +5,7 @@ "owner": "radroots_storage_indexeddb", "feature": "workspace", "target": "wasm32-unknown-unknown", - "shared_policy": "radroots_storage::workspace::local_outbox", + "shared_policy": "radroots_storage::workspace::grant", "native_policy_consumer": "radroots_storage_sqlite::workspace", "shared_grant_wire_private": true, "default_import_side_effects": false, diff --git a/crates/execution/tests/workspace.rs b/crates/execution/tests/workspace.rs @@ -82,9 +82,9 @@ fn binding(change: u8, observed: u64) -> WorkspaceBinding { WorkspaceBinding::from_authenticated_host( input.clone(), if change == 2 { - radroots_storage::workspace::LocalOutboxScope::NewSellerOutbox + radroots_storage::workspace::WorkspaceScope::NewSellerOutbox } else { - radroots_storage::workspace::LocalOutboxScope::NewBuyerOutbox + radroots_storage::workspace::WorkspaceScope::NewBuyerOutbox }, ActorRef::new( key(), diff --git a/crates/storage/src/command.rs b/crates/storage/src/command.rs @@ -166,7 +166,7 @@ impl AdmissionRequest { return Err(OperationError::UnverifiedApproval); } if let Some(listing) = self.command.listing() { - if self.binding.scope() != crate::workspace::LocalOutboxScope::NewSellerOutbox { + if self.binding.scope() != crate::workspace::WorkspaceScope::NewSellerOutbox { return Err(OperationError::Unauthorized); } radroots_protocol::listing::ListingEvent::new( 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, LocalOutboxScope, WorkspaceBinding}; +use crate::workspace::{AttachmentInput, WorkspaceBinding, WorkspaceScope}; use radroots_domain::{ CommandDigest, IssuanceWindow, OperationId, Sequence, TransactionId, UnixSeconds, }; @@ -18,7 +18,7 @@ pub const PREPARED_BYTES_MAX: usize = 65_536; struct Encoded<'a> { version: u8, selection: &'a AttachmentInput, - scope: LocalOutboxScope, + scope: WorkspaceScope, principal: &'a str, grant_revision: Sequence, grant_expires_at: UnixSeconds, @@ -35,7 +35,7 @@ struct Decoded<'a> { version: u8, selection: AttachmentInput, #[serde(default, deserialize_with = "present_scope")] - scope: Option<LocalOutboxScope>, + scope: Option<WorkspaceScope>, principal: String, grant_revision: Sequence, grant_expires_at: UnixSeconds, @@ -50,8 +50,8 @@ struct Decoded<'a> { fn present_scope<'de, D: serde::Deserializer<'de>>( deserializer: D, -) -> Result<Option<LocalOutboxScope>, D::Error> { - LocalOutboxScope::deserialize(deserializer).map(Some) +) -> Result<Option<WorkspaceScope>, D::Error> { + WorkspaceScope::deserialize(deserializer).map(Some) } /// Encodes the original immutable preparation before encryption. A host must @@ -100,7 +100,7 @@ pub fn decode( 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, + (2, None) => WorkspaceScope::NewBuyerOutbox, (3, Some(scope)) => scope, _ => return Err(OperationError::RecoveryRequired), }; @@ -251,7 +251,7 @@ mod tests { legacy.as_object_mut().unwrap().remove("scope"); assert_eq!( read(&legacy).unwrap().request().binding().scope(), - LocalOutboxScope::NewBuyerOutbox + WorkspaceScope::NewBuyerOutbox ); legacy["command"]["context"]["actor"]["role"] = json!("seller"); assert!(read(&legacy).is_err()); @@ -271,7 +271,7 @@ mod tests { let decoded = read(&mismatched).unwrap(); assert_eq!( decoded.request().binding().scope(), - LocalOutboxScope::NewSellerOutbox + WorkspaceScope::NewSellerOutbox ); assert!(same_binding(request.binding(), decoded.request().binding()).is_err()); } diff --git a/crates/storage/src/workspace.rs b/crates/storage/src/workspace.rs @@ -9,6 +9,9 @@ use radroots_domain::{ use radroots_transport::{BoxFuture, host::HostBound}; use zeroize::Zeroizing; +/// Bounded grant metadata shared by qualified workspace hosts. +#[cfg(feature = "protected_outbox")] +pub mod grant; #[cfg(feature = "protected_outbox")] pub mod local_outbox; @@ -208,22 +211,25 @@ 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. +/// A declared workspace permission scope. Metadata alone authenticates none +/// of these permissions; the concrete selected host must qualify its grant. #[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 { +pub enum WorkspaceScope { /// New buyer inquiry and request outbox; no existing order history. NewBuyerOutbox, /// New seller public authoring and private communication outbox; no stock. NewSellerOutbox, + /// Owner scope requiring the separate qualified seller stock namespace. + /// Ordinary local outbox enrollment and opening must refuse this scope. + SellerStockOwner, } -impl LocalOutboxScope { +impl WorkspaceScope { pub(crate) const fn actor_role(self) -> radroots_domain::ActorRole { match self { Self::NewBuyerOutbox => radroots_domain::ActorRole::Buyer, - Self::NewSellerOutbox => radroots_domain::ActorRole::Seller, + Self::NewSellerOutbox | Self::SellerStockOwner => radroots_domain::ActorRole::Seller, } } } @@ -233,7 +239,7 @@ impl LocalOutboxScope { #[derive(Clone, Eq, PartialEq)] pub struct WorkspaceBinding { input: AttachmentInput, - scope: LocalOutboxScope, + scope: WorkspaceScope, actor: ActorRef, principal_id: Box<str>, grant_revision: Sequence, @@ -246,7 +252,7 @@ impl WorkspaceBinding { /// constructor does not turn public metadata into an authenticated context. pub fn from_authenticated_host( input: AttachmentInput, - scope: LocalOutboxScope, + scope: WorkspaceScope, actor: ActorRef, principal_id: impl Into<String>, grant_revision: Sequence, @@ -282,8 +288,8 @@ 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 { + /// Returns the observed scope; signing custody adds no workspace permission. + pub const fn scope(&self) -> WorkspaceScope { self.scope } /// Returns actor data from the persisted authenticated grant. diff --git a/crates/storage/src/workspace/grant.rs b/crates/storage/src/workspace/grant.rs @@ -0,0 +1,229 @@ +//! Shared bounded workspace grant codec; concrete host admission remains separate. +use super::{AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceError, WorkspaceScope}; +use radroots_domain::{ActorRef, GrantId, Sequence, UnixSeconds, WorkspaceId}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use subtle::ConstantTimeEq; +use zeroize::{Zeroize, Zeroizing}; +/// Maximum cleartext grant record, checked before decoding. +pub const GRANT_BYTES_MAX: usize = 16 * 1024; +/// Retained protected outbox context. A stock host needs its own qualified context. +pub const GRANT_ENVELOPE_PURPOSE: &str = "radroots.workspace.grant"; +pub const GRANT_PAYLOAD_SCHEMA: &str = "radroots.workspace.grant.v1"; +pub fn grant_envelope_subject(workspace: WorkspaceId, grant: GrantId) -> String { + // Both IDs have fixed-width canonical hexadecimal representations. + format!("{workspace}{grant}") +} +/// Validated shared grant metadata and current credential/authorization rules. +/// Hosts authenticate its envelope before decoding; this value alone is no authority. +/// Raw Serde construction cannot bypass the bounded validating codec. +pub struct WorkspaceGrant { + wire: GrantWire, +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct GrantWire { + version: u8, + scope: WorkspaceScope, + input: AttachmentInput, + actor: ActorRef, + principal: String, + revision: Sequence, + expires_at: UnixSeconds, + revoked: bool, + verifier: [u8; 32], +} +impl Drop for WorkspaceGrant { + fn drop(&mut self) { + self.wire.verifier.zeroize(); + } +} +impl WorkspaceGrant { + pub fn new( + input: AttachmentInput, + actor: ActorRef, + principal: String, + expires_at: UnixSeconds, + proof: &AttachmentProof, + ) -> Result<Self, WorkspaceError> { + Self::with_scope( + input, + WorkspaceScope::NewBuyerOutbox, + actor, + principal, + expires_at, + proof, + ) + } + pub(super) fn with_scope( + input: AttachmentInput, + scope: WorkspaceScope, + 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, + input, + actor, + principal, + revision: Sequence::new(1).map_err(|_| WorkspaceError::InvalidInput)?, + expires_at, + revoked: false, + verifier, + }, + }; + record.validate()?; + Ok(record) + } + /// Decodes bounded metadata only, without authenticating an envelope or + /// qualifying a host's supported scopes. Outbox hosts use `decode_outbox`. + pub fn decode(bytes: &[u8]) -> Result<Self, WorkspaceError> { + if bytes.len() > GRANT_BYTES_MAX { + return Err(WorkspaceError::RecoveryRequired); + } + let record = Self { + wire: serde_json::from_slice(bytes).map_err(|_| WorkspaceError::RecoveryRequired)?, + }; + record + .validate() + .map_err(|_| WorkspaceError::RecoveryRequired)?; + Ok(record) + } + /// Admits only the retained outbox scopes after envelope authentication. + /// A structurally valid stock-owner claim cannot upgrade an outbox host. + pub fn decode_outbox(bytes: &[u8]) -> Result<Self, WorkspaceError> { + let record = Self::decode(bytes)?; + if record.wire.scope == WorkspaceScope::SellerStockOwner { + return Err(WorkspaceError::RecoveryRequired); + } + Ok(record) + } + pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>, WorkspaceError> { + self.validate()?; + let bytes = Zeroizing::new( + serde_json::to_vec(&self.wire).map_err(|_| WorkspaceError::StorageFailure)?, + ); + if bytes.len() > GRANT_BYTES_MAX { + return Err(WorkspaceError::InvalidInput); + } + Ok(bytes) + } + fn validate(&self) -> Result<(), WorkspaceError> { + if self.wire.version != 1 + || self.wire.actor.role() != 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()) + || self.wire.principal.is_empty() + || self.wire.principal.len() > 128 + || self.wire.principal.chars().any(char::is_control) + || self.wire.revision.get() == 0 + || self.wire.expires_at.get() == 0 + { + return Err(WorkspaceError::InvalidInput); + } + Ok(()) + } + pub fn authenticate( + &self, + input: &AttachmentInput, + proof: &AttachmentProof, + now: UnixSeconds, + ) -> Result<WorkspaceBinding, WorkspaceError> { + self.authenticate_retained_capture(input, proof)?; + if self.wire.revoked { + return Err(WorkspaceError::GrantRevoked); + } + if now.get() == 0 { + return Err(WorkspaceError::Unavailable); + } + if self.wire.expires_at <= now { + return Err(WorkspaceError::GrantExpired); + } + self.validate()?; + WorkspaceBinding::from_authenticated_host( + self.wire.input.clone(), + self.wire.scope, + self.wire.actor, + self.wire.principal.clone(), + self.wire.revision, + self.wire.expires_at, + now, + ) + } + /// Checks only the original protected credential and exact namespace scope. + /// This path is exclusively for appending a matching already obtained + /// artifact to an actual existing claim, never for new issuance or reads. + pub fn authenticate_retained_capture( + &self, + input: &AttachmentInput, + proof: &AttachmentProof, + ) -> Result<(), WorkspaceError> { + // Check the complete secret commitment before projecting detailed state. + let observed = Zeroizing::new(verifier(&self.wire.input, self.wire.scope, proof)); + if !bool::from(observed.as_ref().ct_eq(&self.wire.verifier)) { + return Err(WorkspaceError::Unauthorized); + } + if self.wire.input.workspace_id() != input.workspace_id() { + return Err(WorkspaceError::WrongNamespace); + } + if self.wire.input.authority() != input.authority() { + return Err(WorkspaceError::StaleAuthority); + } + if self.wire.input.checkpoint() != input.checkpoint() { + return Err(WorkspaceError::StaleCheckpoint); + } + if &self.wire.input != input { + return Err(WorkspaceError::Unauthorized); + } + self.validate() + } + pub fn revoke(&mut self) -> Result<(), WorkspaceError> { + self.wire.revoked = true; + self.wire.revision = Sequence::new( + self.wire + .revision + .get() + .checked_add(1) + .ok_or(WorkspaceError::RecoveryRequired)?, + ) + .map_err(|_| WorkspaceError::RecoveryRequired)?; + Ok(()) + } +} +impl WorkspaceScope { + pub(super) 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", + Self::SellerStockOwner => b"radroots.seller_stock.route.v1\0", + } + } + pub(super) 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", + Self::SellerStockOwner => b"radroots.seller_stock.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", + Self::SellerStockOwner => b"radroots.seller_stock.credential.v1\0", + } + } +} +fn verifier(input: &AttachmentInput, scope: WorkspaceScope, proof: &AttachmentProof) -> [u8; 32] { + let mut digest = Sha256::new(); + 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)); + digest.finalize().into() +} diff --git a/crates/storage/src/workspace/local_outbox.rs b/crates/storage/src/workspace/local_outbox.rs @@ -1,27 +1,17 @@ //! Shared pure enrollment and protected grant rules for concrete local hosts. //! No database, runtime, signer or provider is acquired here. -use super::{AttachmentInput, AttachmentProof, LocalOutboxScope, WorkspaceBinding, WorkspaceError}; +use super::{ + AttachmentInput, AttachmentProof, WorkspaceError, WorkspaceScope, grant::WorkspaceGrant, +}; use radroots_domain::{ ActorRef, AuthorityRef, CheckpointDigest, CheckpointRef, Coverage, ExecutorId, Generation, GrantId, PublicKey, RouteDigest, Sequence, UnixSeconds, WorkspaceId, }; -use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use subtle::ConstantTimeEq; -use zeroize::{Zeroize, Zeroizing}; -/// Maximum cleartext grant record, checked before decoding. -pub const GRANT_BYTES_MAX: usize = 16 * 1024; -/// Exact protected grant context, shared by concrete storage hosts. -pub const GRANT_ENVELOPE_PURPOSE: &str = "radroots.workspace.grant"; -pub const GRANT_PAYLOAD_SCHEMA: &str = "radroots.workspace.grant.v1"; -pub fn grant_envelope_subject(workspace: WorkspaceId, grant: GrantId) -> String { - // Both IDs have fixed-width canonical hexadecimal representations. - format!("{workspace}{grant}") -} /// Explicit local enrollment inputs, supplied by a trusted host interaction. /// Creation is limited to an unrelated new outbox, never seller stock. pub struct LocalOutboxConfig { - scope: LocalOutboxScope, + scope: WorkspaceScope, participant: PublicKey, endpoint_identity: PublicKey, principal: String, @@ -46,7 +36,7 @@ impl LocalOutboxConfig { return Err(WorkspaceError::InvalidInput); } Ok(Self { - scope: LocalOutboxScope::NewBuyerOutbox, + scope: WorkspaceScope::NewBuyerOutbox, participant, endpoint_identity, principal: principal.to_owned(), @@ -62,7 +52,7 @@ impl LocalOutboxConfig { expires_at: UnixSeconds, ) -> Result<Self, WorkspaceError> { let mut config = Self::new(participant, endpoint_identity, principal, expires_at)?; - config.scope = LocalOutboxScope::NewSellerOutbox; + config.scope = WorkspaceScope::NewSellerOutbox; Ok(config) } } @@ -92,7 +82,7 @@ impl LocalOutboxConfig { executor: ExecutorId, grant: GrantId, proof: AttachmentProof, - ) -> Result<(AttachmentInput, AttachmentProof, LocalOutboxGrant), WorkspaceError> { + ) -> Result<(AttachmentInput, AttachmentProof, WorkspaceGrant), WorkspaceError> { self.validate_at(now)?; let authority = AuthorityRef::new( executor, @@ -131,7 +121,7 @@ impl LocalOutboxConfig { route, )?; let actor = ActorRef::new(self.participant, self.scope.actor_role(), None, Some(grant)); - let record = LocalOutboxGrant::with_scope( + let record = WorkspaceGrant::with_scope( input.clone(), self.scope, actor, @@ -142,202 +132,3 @@ impl LocalOutboxConfig { Ok((input, proof, record)) } } -/// Validated protected local-outbox grant codec and current authorization rules. -/// Hosts authenticate its envelope before decoding; this value alone is no authority. -/// Raw Serde construction cannot bypass the bounded validating codec. -pub struct LocalOutboxGrant { - wire: GrantWire, -} -#[derive(Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct GrantWire { - version: u8, - scope: LocalOutboxScope, - input: AttachmentInput, - actor: ActorRef, - principal: String, - revision: Sequence, - expires_at: UnixSeconds, - revoked: bool, - verifier: [u8; 32], -} -impl Drop for LocalOutboxGrant { - fn drop(&mut self) { - self.wire.verifier.zeroize(); - } -} -impl LocalOutboxGrant { - pub fn new( - input: AttachmentInput, - actor: ActorRef, - principal: String, - expires_at: UnixSeconds, - proof: &AttachmentProof, - ) -> Result<Self, WorkspaceError> { - 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, - input, - actor, - principal, - revision: Sequence::new(1).map_err(|_| WorkspaceError::InvalidInput)?, - expires_at, - revoked: false, - verifier, - }, - }; - record.validate()?; - Ok(record) - } - pub fn decode(bytes: &[u8]) -> Result<Self, WorkspaceError> { - if bytes.len() > GRANT_BYTES_MAX { - return Err(WorkspaceError::RecoveryRequired); - } - let record = Self { - wire: serde_json::from_slice(bytes).map_err(|_| WorkspaceError::RecoveryRequired)?, - }; - record - .validate() - .map_err(|_| WorkspaceError::RecoveryRequired)?; - Ok(record) - } - pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>, WorkspaceError> { - self.validate()?; - let bytes = Zeroizing::new( - serde_json::to_vec(&self.wire).map_err(|_| WorkspaceError::StorageFailure)?, - ); - if bytes.len() > GRANT_BYTES_MAX { - return Err(WorkspaceError::InvalidInput); - } - Ok(bytes) - } - fn validate(&self) -> Result<(), WorkspaceError> { - if self.wire.version != 1 - || self.wire.actor.role() != 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()) - || self.wire.principal.is_empty() - || self.wire.principal.len() > 128 - || self.wire.principal.chars().any(char::is_control) - || self.wire.revision.get() == 0 - || self.wire.expires_at.get() == 0 - { - return Err(WorkspaceError::InvalidInput); - } - Ok(()) - } - pub fn authenticate( - &self, - input: &AttachmentInput, - proof: &AttachmentProof, - now: UnixSeconds, - ) -> Result<WorkspaceBinding, WorkspaceError> { - self.authenticate_retained_capture(input, proof)?; - if self.wire.revoked { - return Err(WorkspaceError::GrantRevoked); - } - if now.get() == 0 { - return Err(WorkspaceError::Unavailable); - } - if self.wire.expires_at <= now { - return Err(WorkspaceError::GrantExpired); - } - self.validate()?; - WorkspaceBinding::from_authenticated_host( - self.wire.input.clone(), - self.wire.scope, - self.wire.actor, - self.wire.principal.clone(), - self.wire.revision, - self.wire.expires_at, - now, - ) - } - /// Checks only the original protected credential and exact namespace scope. - /// This path is exclusively for appending a matching already obtained - /// artifact to an actual existing claim, never for new issuance or reads. - pub fn authenticate_retained_capture( - &self, - input: &AttachmentInput, - proof: &AttachmentProof, - ) -> Result<(), WorkspaceError> { - // Check the complete secret commitment before projecting detailed state. - let observed = Zeroizing::new(verifier(&self.wire.input, self.wire.scope, proof)); - if !bool::from(observed.as_ref().ct_eq(&self.wire.verifier)) { - return Err(WorkspaceError::Unauthorized); - } - if self.wire.input.workspace_id() != input.workspace_id() { - return Err(WorkspaceError::WrongNamespace); - } - if self.wire.input.authority() != input.authority() { - return Err(WorkspaceError::StaleAuthority); - } - if self.wire.input.checkpoint() != input.checkpoint() { - return Err(WorkspaceError::StaleCheckpoint); - } - if &self.wire.input != input { - return Err(WorkspaceError::Unauthorized); - } - self.validate() - } - pub fn revoke(&mut self) -> Result<(), WorkspaceError> { - self.wire.revoked = true; - self.wire.revision = Sequence::new( - self.wire - .revision - .get() - .checked_add(1) - .ok_or(WorkspaceError::RecoveryRequired)?, - ) - .map_err(|_| WorkspaceError::RecoveryRequired)?; - Ok(()) - } -} -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(scope.credential_domain()); - digest.update(input.workspace_id().as_bytes()); - digest.update(input.grant_id().as_bytes()); - proof.with_secret(|secret| digest.update(secret)); - digest.finalize().into() -} diff --git a/crates/storage/tests/command.rs b/crates/storage/tests/command.rs @@ -34,7 +34,7 @@ fn binding() -> WorkspaceBinding { .unwrap(); WorkspaceBinding::from_authenticated_host( input, - radroots_storage::workspace::LocalOutboxScope::NewBuyerOutbox, + radroots_storage::workspace::WorkspaceScope::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 @@ -3,8 +3,8 @@ use radroots_domain::{ ActorRef, ActorRole, ExecutorId, GrantId, PublicKey, UnixSeconds, WorkspaceId, }; use radroots_storage::workspace::{ - AttachmentProof, LocalOutboxScope, WorkspaceError, - local_outbox::{LocalOutboxConfig, LocalOutboxGrant}, + AttachmentProof, WorkspaceError, WorkspaceScope, grant::WorkspaceGrant, + local_outbox::LocalOutboxConfig, }; fn key() -> PublicKey { @@ -15,7 +15,7 @@ fn enrolled( ) -> ( radroots_storage::workspace::AttachmentInput, AttachmentProof, - LocalOutboxGrant, + WorkspaceGrant, ) { let constructor = if seller { LocalOutboxConfig::seller @@ -54,13 +54,28 @@ fn enrollment_separates_scope_routes_genesis_and_credential_commitments() { } #[test] +fn ordinary_outbox_admission_refuses_structurally_valid_stock_owner_metadata() { + let (_, _, grant) = enrolled(true); + let original = grant.encode().unwrap(); + let mut wire: serde_json::Value = serde_json::from_slice(&original).unwrap(); + wire["scope"] = serde_json::json!("seller_stock_owner"); + let encoded = serde_json::to_vec(&wire).unwrap(); + assert!(WorkspaceGrant::decode(&encoded).is_ok()); + assert!(matches!( + WorkspaceGrant::decode_outbox(&encoded), + Err(WorkspaceError::RecoveryRequired) + )); + assert!(WorkspaceGrant::decode_outbox(&original).is_ok()); +} + +#[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), + (false, WorkspaceScope::NewBuyerOutbox, ActorRole::Buyer), + (true, WorkspaceScope::NewSellerOutbox, ActorRole::Seller), ] { let (input, proof, grant) = enrolled(seller); - let mut grant = LocalOutboxGrant::decode(&grant.encode().unwrap()).unwrap(); + let mut grant = WorkspaceGrant::decode(&grant.encode().unwrap()).unwrap(); let bound = grant .authenticate(&input, &proof, UnixSeconds::new(100).unwrap()) .unwrap(); @@ -91,7 +106,7 @@ fn both_scopes_retain_protected_access_expiry_revocation_and_exact_role() { WorkspaceError::GrantExpired ); grant.revoke().unwrap(); - let grant = LocalOutboxGrant::decode(&grant.encode().unwrap()).unwrap(); + let grant = WorkspaceGrant::decode(&grant.encode().unwrap()).unwrap(); assert_eq!( grant .authenticate(&input, &proof, UnixSeconds::new(100).unwrap()) @@ -111,7 +126,7 @@ fn changing_scope_and_role_cannot_upgrade_an_existing_protected_credential() { 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()), + WorkspaceGrant::decode(&serde_json::to_vec(&changed).unwrap()), Err(WorkspaceError::RecoveryRequired) )); changed["scope"] = serde_json::json!(if seller { @@ -119,7 +134,7 @@ fn changing_scope_and_role_cannot_upgrade_an_existing_protected_credential() { } else { "new_seller_outbox" }); - let changed = LocalOutboxGrant::decode(&serde_json::to_vec(&changed).unwrap()).unwrap(); + let changed = WorkspaceGrant::decode(&serde_json::to_vec(&changed).unwrap()).unwrap(); assert_eq!( changed .authenticate(&input, &proof, UnixSeconds::new(100).unwrap()) @@ -129,11 +144,11 @@ fn changing_scope_and_role_cannot_upgrade_an_existing_protected_credential() { 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()); + assert!(WorkspaceGrant::decode(&serde_json::to_vec(&changed).unwrap()).is_err()); } // The original buyer constructor never accepts a seller actor. assert!( - LocalOutboxGrant::new( + WorkspaceGrant::new( input.clone(), ActorRef::new(key(), ActorRole::Seller, None, Some(input.grant_id())), "device".into(), diff --git a/crates/storage/tests/workspace.rs b/crates/storage/tests/workspace.rs @@ -83,7 +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, + radroots_storage::workspace::WorkspaceScope::NewBuyerOutbox, actor, principal, Sequence::new(revision).unwrap(), @@ -95,7 +95,7 @@ fn host_observations_validate_internal_binding_without_authenticating_metadata() assert_eq!(observed.input(), &input()); assert_eq!( observed.scope(), - radroots_storage::workspace::LocalOutboxScope::NewBuyerOutbox + radroots_storage::workspace::WorkspaceScope::NewBuyerOutbox ); assert_eq!(observed.actor(), actor()); assert_eq!(observed.principal_id(), "device"); diff --git a/crates/storage_indexeddb/src/workspace/crypto.rs b/crates/storage_indexeddb/src/workspace/crypto.rs @@ -7,8 +7,8 @@ use radroots_secrets::{ provider::SecretProvider, wrapping::SecretMaterial, }; -use radroots_storage::workspace::local_outbox::grant_envelope_subject; -use radroots_storage::workspace::{WorkspaceError, local_outbox::GRANT_BYTES_MAX}; +use radroots_storage::workspace::grant::grant_envelope_subject; +use radroots_storage::workspace::{WorkspaceError, grant::GRANT_BYTES_MAX}; use wasm_bindgen::{JsCast, JsValue}; use zeroize::Zeroizing; diff --git a/crates/storage_indexeddb/src/workspace/journal.rs b/crates/storage_indexeddb/src/workspace/journal.rs @@ -13,7 +13,7 @@ use radroots_storage::{ AdmissionOutcome, AdmissionRequest, CommitAttempt, OperationError, PreparedOperation, protected, }, - workspace::{AttachmentProof, WorkspaceBinding, local_outbox::LocalOutboxGrant}, + workspace::{AttachmentProof, WorkspaceBinding, grant::WorkspaceGrant}, }; use sha2::{Digest, Sha256}; use std::{cell::Cell, rc::Rc}; @@ -234,7 +234,7 @@ pub(super) fn storage_error(error: Error) -> OperationError { } } pub(super) struct Access { - grant: LocalOutboxGrant, + grant: WorkspaceGrant, protected: Vec<u8>, pub binding: WorkspaceBinding, proof: AttachmentProof, @@ -271,7 +271,7 @@ impl State { // The current authenticated buyer grant cannot admit public work, and // preparation decoding refuses any such stored command. Preserve the // original private path without another decryption of every T0 part. - if access.binding.scope() != radroots_storage::workspace::LocalOutboxScope::NewBuyerOutbox + if access.binding.scope() != radroots_storage::workspace::WorkspaceScope::NewBuyerOutbox && let Some(prepared) = self.preparation(operation, &before).await? { extra.extend(self.coordinate_guard(&prepared).await?); diff --git a/crates/storage_indexeddb/src/workspace/listing.rs b/crates/storage_indexeddb/src/workspace/listing.rs @@ -139,7 +139,7 @@ impl State { return Ok(Vec::new()); } if prepared.request().binding().scope() - != radroots_storage::workspace::LocalOutboxScope::NewSellerOutbox + != radroots_storage::workspace::WorkspaceScope::NewSellerOutbox { return Err(OperationError::RecoveryRequired); } diff --git a/crates/storage_indexeddb/src/workspace/mod.rs b/crates/storage_indexeddb/src/workspace/mod.rs @@ -27,7 +27,7 @@ use radroots_storage::{ event::SourceGeneration, workspace::{ AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceError, - WorkspaceStore, local_outbox::LocalOutboxGrant, + WorkspaceStore, grant::WorkspaceGrant, }, }; use radroots_transport::BoxFuture; @@ -246,7 +246,7 @@ impl State { &self, input: &AttachmentInput, proof: &AttachmentProof, - ) -> Result<(LocalOutboxGrant, Vec<u8>, WorkspaceBinding), WorkspaceError> { + ) -> Result<(WorkspaceGrant, Vec<u8>, WorkspaceBinding), WorkspaceError> { if self.mode != AccessMode::Current { return Err(WorkspaceError::Unauthorized); } @@ -259,7 +259,7 @@ impl State { &self, input: &AttachmentInput, proof: &AttachmentProof, - ) -> Result<(LocalOutboxGrant, Vec<u8>), WorkspaceError> { + ) -> Result<(WorkspaceGrant, Vec<u8>), WorkspaceError> { self.active()?; if input != &self.selected { return Err(WorkspaceError::Unauthorized); @@ -278,7 +278,7 @@ impl State { &protected, ) .await?; - let record = plaintext.expose_secret(LocalOutboxGrant::decode)?; + let record = plaintext.expose_secret(WorkspaceGrant::decode_outbox)?; record.authenticate_retained_capture(input, proof)?; self.active()?; Ok((record, protected)) diff --git a/crates/storage_indexeddb/src/workspace/recovery.rs b/crates/storage_indexeddb/src/workspace/recovery.rs @@ -4,9 +4,7 @@ use radroots_domain::OperationId; use radroots_storage::command::{ ArtifactEvidence, DeliveryObservation, DeliveryObservationKind, PublicationArtifact, }; -use radroots_storage::workspace::{ - AttachmentInput, AttachmentProof, local_outbox::LocalOutboxGrant, -}; +use radroots_storage::workspace::{AttachmentInput, AttachmentProof, grant::WorkspaceGrant}; use radroots_transport::{sink::DeliveryRequestId, target::TargetFingerprint}; #[derive(Clone, Eq, PartialEq)] @@ -40,7 +38,7 @@ impl CaptureIdentity { } pub(super) struct Authorization { - grant: LocalOutboxGrant, + grant: WorkspaceGrant, close_confirmed: bool, } impl State { @@ -56,7 +54,7 @@ impl State { &self, input: &AttachmentInput, proof: &AttachmentProof, - ) -> Result<(LocalOutboxGrant, Vec<u8>), WorkspaceError> { + ) -> Result<(WorkspaceGrant, Vec<u8>), WorkspaceError> { self.active()?; if input != &self.selected { return Err(WorkspaceError::Unauthorized); diff --git a/crates/storage_indexeddb/tests/browser/run.mjs b/crates/storage_indexeddb/tests/browser/run.mjs @@ -671,6 +671,16 @@ try { await navigator.locks.request(workspaceReceipt.namespace,()=>{}); const recoveredWorkspace=await openReceipt(workspaceReceipt);same(await recoveredWorkspace.authenticate(),1);await recoveredWorkspace.close(); passed('actual worker termination releases writer ownership and the same protected outbox reopens'); + const scopeOwner=await WorkspaceFixture.create_seller(247); + const scopeReceipt={n:247,fingerprint:Array.from(scopeOwner.fingerprint()),selection:Array.from(scopeOwner.selection()),proof:Array.from(scopeOwner.proof()),namespace:scopeOwner.data_namespace()}; + const scopeRows=await workspaceBytes(scopeReceipt);same(scopeRows.keys.length,1); + const stockClaim=await scopeOwner.stock_scope_bytes(crypto.getRandomValues(new Uint8Array(56))); + await changeWorkspace(scopeReceipt,store=>store.put(stockClaim,scopeRows.keys[0])); + const retainedStockClaim=await workspaceBytes(scopeReceipt); + await rejects(()=>scopeOwner.authenticate(),'recovery_required');await scopeOwner.close(); + await rejects(()=>openReceipt(scopeReceipt),'recovery_required'); + sameRows(await workspaceBytes(scopeReceipt),retainedStockClaim); + passed('ordinary browser outbox refuses a valid protected stock-owner claim without repair'); const source=await WorkspaceFixture.create(164);const target=await source.sibling(); const sourceReceipt={namespace:source.data_namespace()},targetReceipt={namespace:target.data_namespace()}; const sourceBytes=await workspaceBytes(sourceReceipt),targetBytes=await workspaceBytes(targetReceipt); diff --git a/crates/storage_indexeddb/tests/browser/src/workspace.rs b/crates/storage_indexeddb/tests/browser/src/workspace.rs @@ -370,8 +370,11 @@ impl WorkspaceFixture { assert_eq!( bound.actor().role(), match bound.scope() { - radroots_storage::workspace::LocalOutboxScope::NewBuyerOutbox => ActorRole::Buyer, - radroots_storage::workspace::LocalOutboxScope::NewSellerOutbox => ActorRole::Seller, + radroots_storage::workspace::WorkspaceScope::NewBuyerOutbox => ActorRole::Buyer, + radroots_storage::workspace::WorkspaceScope::NewSellerOutbox => ActorRole::Seller, + radroots_storage::workspace::WorkspaceScope::SellerStockOwner => { + panic!("ordinary browser outbox admitted a stock-owner scope") + } } ); assert_eq!(bound.actor().organization(), None); @@ -387,10 +390,107 @@ impl WorkspaceFixture { .await .map_err(fail)?; Ok( - bound.scope() == radroots_storage::workspace::LocalOutboxScope::NewSellerOutbox + bound.scope() == radroots_storage::workspace::WorkspaceScope::NewSellerOutbox && bound.actor().role() == ActorRole::Seller, ) } + /// Synthetic fault bytes for ordinary-outbox scope admission tests. + pub async fn stock_scope_bytes(&self, material: Vec<u8>) -> Result<Vec<u8>, JsValue> { + use radroots_secrets::{ + EncryptedEnvelope, + context::{EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId}, + envelope::{Nonce, SealMaterial, SealRequest}, + wrapping::SecretMaterial, + }; + use radroots_storage::workspace::{WorkspaceScope, grant::WorkspaceGrant}; + if material.len() != 56 { + return Err(JsValue::from_str("invalid_fixture_material")); + } + let binding = self + .owner + .authenticate(self.input.clone(), copied(&self.proof)) + .await + .map_err(fail)?; + if binding.scope() != WorkspaceScope::NewSellerOutbox { + return Err(JsValue::from_str("seller_fixture_required")); + } + let (input, _, grant) = LocalOutboxConfig::seller( + self.input.participant(), + self.input.endpoint_identity(), + binding.principal_id(), + binding.expires_at(), + ) + .map_err(fail)? + .enroll( + binding.observed_at(), + self.input.workspace_id(), + self.input.authority().executor_id(), + self.input.grant_id(), + copied(&self.proof), + ) + .map_err(fail)?; + assert_eq!(input, self.input); + let mut wire: serde_json::Value = + serde_json::from_slice(&grant.encode().map_err(fail)?).unwrap(); + wire["scope"] = serde_json::json!("seller_stock_owner"); + let mut verifier = Sha256::new(); + verifier.update(b"radroots.seller_stock.credential.v1\0"); + verifier.update(self.input.workspace_id().as_bytes()); + verifier.update(self.input.grant_id().as_bytes()); + self.proof.with_secret(|secret| verifier.update(secret)); + wire["verifier"] = serde_json::json!(<[u8; 32]>::from(verifier.finalize())); + let encoded = serde_json::to_vec(&wire).unwrap(); + let claim = WorkspaceGrant::decode(&encoded).map_err(fail)?; + assert_eq!( + claim + .authenticate(&self.input, &self.proof, binding.observed_at()) + .map_err(fail)? + .scope(), + WorkspaceScope::SellerStockOwner + ); + let context = EnvelopeContext::new( + EnvelopePurpose::parse("radroots.browser.workspace.grant").unwrap(), + EnvelopeSubject::parse( + "workspace_grant", + format!("{}{}", self.input.workspace_id(), self.input.grant_id()), + ) + .unwrap(), + PayloadSchemaId::parse("radroots.browser.workspace.grant.v2").unwrap(), + ); + let plaintext = SecretMaterial::from_slice(&encoded).unwrap(); + let expected = context.clone(); + let envelope = EncryptedEnvelope::seal( + self.provider.as_ref(), + SealRequest::new( + reference(), + context, + &plaintext, + SealMaterial::new( + SecretMaterial::from_slice(&material[..32]).unwrap(), + Nonce::new(material[32..].try_into().unwrap()), + ), + ), + ) + .await + .map_err(|_| JsValue::from_str("fixture_seal_failed"))?; + let verified = envelope + .open(self.provider.as_ref(), &expected) + .await + .map_err(|_| JsValue::from_str("fixture_open_failed"))?; + let verified_claim = verified + .expose_secret(WorkspaceGrant::decode) + .map_err(fail)?; + assert_eq!( + verified_claim + .authenticate(&self.input, &self.proof, binding.observed_at()) + .map_err(fail)? + .scope(), + WorkspaceScope::SellerStockOwner + ); + envelope + .encode() + .map_err(|_| JsValue::from_str("fixture_encode_failed")) + } pub async fn wrong_proof(&self) -> Result<(), JsValue> { self.owner .authenticate( diff --git a/crates/storage_sqlite/src/workspace/admission.rs b/crates/storage_sqlite/src/workspace/admission.rs @@ -37,7 +37,7 @@ impl Journal<'_> { &protected, ) .await?; - let record = plaintext.expose_secret(GrantRecord::decode)?; + let record = plaintext.expose_secret(GrantRecord::decode_outbox)?; let current = record.authenticate(binding.input(), proof, self.clock.now()?)?; same_binding(binding, ¤t)?; self.namespace.validate()?; diff --git a/crates/storage_sqlite/src/workspace/crypto.rs b/crates/storage_sqlite/src/workspace/crypto.rs @@ -7,7 +7,7 @@ use radroots_secrets::{ provider::{AccessPolicy, ResidencySupport, SecretProvider, SelectionPolicy}, wrapping::SecretMaterial, }; -use radroots_storage::workspace::local_outbox::{ +use radroots_storage::workspace::grant::{ GRANT_ENVELOPE_PURPOSE, GRANT_PAYLOAD_SCHEMA, grant_envelope_subject, }; use std::{fmt, sync::Arc}; diff --git a/crates/storage_sqlite/src/workspace/issuance.rs b/crates/storage_sqlite/src/workspace/issuance.rs @@ -357,7 +357,7 @@ impl Journal<'_> { &protected, ) .await?; - let record = plaintext.expose_secret(GrantRecord::decode)?; + let record = plaintext.expose_secret(GrantRecord::decode_outbox)?; record.authenticate_retained_capture(input, proof)?; self.namespace.validate()?; Ok((record, protected)) diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs @@ -28,8 +28,8 @@ mod tests; pub use crypto::WorkspaceCrypto; pub use radroots_storage::workspace::{ - AttachmentInput, AttachmentProof, LocalOutboxScope, WorkspaceBinding, WorkspaceClock, - WorkspaceError, + AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceError, + WorkspaceScope, }; use radroots_domain::{ExecutorId, GrantId, WorkspaceId}; diff --git a/crates/storage_sqlite/src/workspace/record.rs b/crates/storage_sqlite/src/workspace/record.rs @@ -1 +1 @@ -pub(super) use radroots_storage::workspace::local_outbox::LocalOutboxGrant as GrantRecord; +pub(super) use radroots_storage::workspace::grant::WorkspaceGrant as GrantRecord; diff --git a/crates/storage_sqlite/src/workspace/recovery.rs b/crates/storage_sqlite/src/workspace/recovery.rs @@ -60,7 +60,7 @@ impl RecoveryTurn<'_> { &protected, ) .await?; - let record = plaintext.expose_secret(GrantRecord::decode)?; + let record = plaintext.expose_secret(GrantRecord::decode_outbox)?; record.authenticate_retained_capture(&input, &proof)?; *self.cached_grant = Some(RecoveryAuthorization { grant: record, diff --git a/crates/storage_sqlite/src/workspace/tests/issuance_records.rs b/crates/storage_sqlite/src/workspace/tests/issuance_records.rs @@ -141,14 +141,14 @@ pub(in crate::workspace) async fn public_delivery_data() -> DeliveryData { DeliveryAttempt, DeliveryIntent, EvidenceReceipt, ListingInstallation, PreparedOperation, PublicPublicationWork, SigningTarget, }, - workspace::{LocalOutboxScope, WorkspaceBinding}, + workspace::{WorkspaceBinding, WorkspaceScope}, }; let mut data = delivery_data().await; let selected = data.selection(); let time = UnixSeconds::new(100).unwrap(); let binding = WorkspaceBinding::from_authenticated_host( selected.clone(), - LocalOutboxScope::NewSellerOutbox, + WorkspaceScope::NewSellerOutbox, ActorRef::new( participant(), ActorRole::Seller, diff --git a/crates/storage_sqlite/src/workspace/tests/mod.rs b/crates/storage_sqlite/src/workspace/tests/mod.rs @@ -314,6 +314,83 @@ impl WorkspaceClock for FixedClock { } } #[tokio::test] +async fn outbox_open_refuses_valid_protected_stock_scope_without_repair() { + use sha2::{Digest, Sha256}; + use sqlx::Connection; + + let fixture = CryptoFixture::new(); + let path = fixture + ._temp + .path() + .canonicalize() + .unwrap() + .join("wrong-stock-scope"); + let (owner, input, proof) = NativeWorkspace::initialize_local_outbox( + &path, + LocalOutboxConfig::seller( + participant(), + participant(), + "synthetic-device", + UnixSeconds::new(200).unwrap(), + ) + .unwrap(), + fixture.crypto(), + Arc::new(FixedClock(100)), + ) + .await + .unwrap(); + owner.close().await.unwrap(); + let database = path.join("execution_v1.sqlite"); + let options = sqlx::sqlite::SqliteConnectOptions::new().filename(&database); + let mut connection = sqlx::SqliteConnection::connect_with(&options) + .await + .unwrap(); + let original: Vec<u8> = sqlx::query_scalar("SELECT protected FROM workspace_grant") + .fetch_one(&mut connection) + .await + .unwrap(); + let crypto = fixture.crypto(); + let clear = crypto + .open(input.workspace_id(), input.grant_id(), &original) + .await + .unwrap(); + let mut wire: serde_json::Value = + clear.expose_secret(|bytes| serde_json::from_slice(bytes).unwrap()); + wire["scope"] = serde_json::json!("seller_stock_owner"); + let mut verifier = Sha256::new(); + verifier.update(b"radroots.seller_stock.credential.v1\0"); + verifier.update(input.workspace_id().as_bytes()); + verifier.update(input.grant_id().as_bytes()); + proof.with_secret(|secret| verifier.update(secret)); + wire["verifier"] = serde_json::json!(<[u8; 32]>::from(verifier.finalize())); + let encoded = zeroize::Zeroizing::new(serde_json::to_vec(&wire).unwrap()); + let metadata = record::GrantRecord::decode(&encoded).unwrap(); + assert_eq!( + metadata + .authenticate(&input, &proof, UnixSeconds::new(100).unwrap()) + .unwrap() + .scope(), + WorkspaceScope::SellerStockOwner + ); + let sealed = crypto + .seal(input.workspace_id(), input.grant_id(), &encoded) + .await + .unwrap(); + sqlx::query("UPDATE workspace_grant SET protected=?") + .bind(sealed) + .execute(&mut connection) + .await + .unwrap(); + connection.close().await.unwrap(); + let retained = host_fs::read(&database).unwrap(); + assert!(matches!( + NativeWorkspace::open_existing(&path, input, fixture.crypto(), Arc::new(FixedClock(100))) + .await, + Err(WorkspaceError::RecoveryRequired) + )); + assert_eq!(host_fs::read(&database).unwrap(), retained); +} +#[tokio::test] async fn seller_scope_survives_protected_close_reopen_without_stock_or_buyer_upgrade() { let fixture = CryptoFixture::new(); let path = fixture @@ -337,7 +414,7 @@ async fn seller_scope_survives_protected_close_reopen_without_stock_or_buyer_upg .await .unwrap(); let binding = owner.authenticate(input.clone(), &proof).await.unwrap(); - assert_eq!(binding.scope(), LocalOutboxScope::NewSellerOutbox); + assert_eq!(binding.scope(), WorkspaceScope::NewSellerOutbox); assert_eq!(binding.actor().role(), ActorRole::Seller); assert_eq!(binding.actor().organization(), None); assert_eq!(input.checkpoint().coverage(), Coverage::Partial); diff --git a/crates/storage_sqlite/src/workspace/tests/operation_records.rs b/crates/storage_sqlite/src/workspace/tests/operation_records.rs @@ -99,7 +99,7 @@ async fn protected_operation_read_refuses_each_inconsistent_payload_and_sql_proj assert_eq!(recovered.identity(), retained.identity()); assert_eq!( recovered.request().binding().scope(), - radroots_storage::workspace::LocalOutboxScope::NewBuyerOutbox + radroots_storage::workspace::WorkspaceScope::NewBuyerOutbox ); assert_eq!(legacy_retained.bytes, legacy); assert_eq!( diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -1009,7 +1009,7 @@ pub(super) async fn initialize( let plaintext = crypto .open(expected.workspace_id(), expected.grant_id(), &protected) .await?; - plaintext.expose_secret(GrantRecord::decode)?; + plaintext.expose_secret(GrantRecord::decode_outbox)?; namespace.validate() } pub(super) async fn read( @@ -1052,7 +1052,7 @@ async fn authenticate( let plaintext = crypto .open(expected.workspace_id(), expected.grant_id(), &protected) .await?; - let record = plaintext.expose_secret(GrantRecord::decode)?; + let record = plaintext.expose_secret(GrantRecord::decode_outbox)?; let binding = record.authenticate(selected, proof, clock.now()?)?; namespace.validate()?; Ok((record, binding)) diff --git a/crates/storage_sqlite/tests/workspace_admission.rs b/crates/storage_sqlite/tests/workspace_admission.rs @@ -674,7 +674,7 @@ 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 + radroots_storage::workspace::WorkspaceScope::NewSellerOutbox } else { binding.scope() },