lib

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

commit 8c0d337b98a9d3a54853495f8f212a67ffc3bce7
parent eb449d4609197e68ee1c6beb11e3dba1e6272260
Author: triesap <tyson@radroots.org>
Date:   Mon, 26 Oct 2026 20:19:42 +0000

signing: own first dispatch and preserve binding diagnostics

- Consume fresh native permits in one exact issuer invocation.
- Preserve bounded signer rejection across native and browser failures.
- Update generated Swift, Kotlin and packed TypeScript callers.
- Qualify original refusals, retained claims and affected host boundaries.

Diffstat:
Mcontracts/api_baselines/radroots.txt | 4++++
Mcontracts/api_baselines/radroots_execution.txt | 2++
Mcontracts/api_baselines/radroots_signing.txt | 4++++
Mcontracts/api_baselines/radroots_storage_sqlite.txt | 19+++++++++++++++++++
Mcontracts/architecture/decisions/shared_sdk_refactor.v1.json | 14++++++++++++++
Mcrates/execution/README.md | 5+++++
Mcrates/execution/src/session/signer.rs | 9+++++++++
Mcrates/execution/tests/signer_session.rs | 8+++++---
Mcrates/radroots/src/signing.rs | 6+++---
Mcrates/radroots_browser/README.md | 10++++++++++
Mcrates/radroots_browser/src/bindings/error.rs | 61+++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mcrates/radroots_browser/src/bindings/mod.rs | 2++
Mcrates/radroots_browser/src/bindings/receipt.rs | 1+
Acrates/radroots_browser/src/bindings/signer_rejection.rs | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/radroots_browser/src/bindings/states.rs | 2+-
Mcrates/radroots_browser/src/bindings/values.rs | 4++++
Mcrates/radroots_browser/src/client.rs | 9+++++----
Mcrates/radroots_browser/tests/browser/consumer.ts | 39++++++++++++++++++++++++++++++++++++++-
Mcrates/radroots_browser/tests/browser/packed.mjs | 2+-
Mcrates/radroots_browser/tests/browser/src/binding_fixture.rs | 139++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcrates/radroots_browser/tests/browser/src/lib.rs | 9++++++---
Mcrates/radroots_ffi/README.md | 9+++++++++
Mcrates/radroots_ffi/src/error.rs | 45++++++++++++++++++++++++++++++++++++---------
Mcrates/radroots_ffi/src/lib.rs | 2++
Mcrates/radroots_ffi/src/receipt.rs | 1+
Acrates/radroots_ffi/src/signer_rejection.rs | 40++++++++++++++++++++++++++++++++++++++++
Mcrates/radroots_ffi/src/states.rs | 2+-
Mcrates/radroots_ffi/src/values.rs | 2++
Mcrates/radroots_ffi/tests/native/Cargo.lock | 3+++
Mcrates/radroots_ffi/tests/native/Smoke.kt | 47++++++++++++++++++++++++++++++++++++++++++++++-
Mcrates/radroots_ffi/tests/native/Smoke.swift | 47++++++++++++++++++++++++++++++++++++++++++++---
Mcrates/radroots_ffi/tests/native/src/lib.rs | 17+++++++++++++++++
Mcrates/radroots_ffi/tests/native/src/signer.rs | 27++++++++++++++++++++++++++-
Mcrates/radroots_ffi/tests/native/tests/flows.rs | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/signing/README.md | 7+++++++
Mcrates/signing/src/issuance.rs | 13+++++++++++++
Mcrates/signing/tests/package_boundary.rs | 1+
Mcrates/storage_sqlite/README.md | 17+++++++++++++++++
Mcrates/storage_sqlite/src/workspace/mod.rs | 18+++++++++---------
Mcrates/storage_sqlite/src/workspace/stock.rs | 5+++--
Mcrates/storage_sqlite/src/workspace/stock/issuance.rs | 5++++-
Mcrates/storage_sqlite/src/workspace/stock/issuance/claim.rs | 2++
Acrates/storage_sqlite/src/workspace/stock/issuance/claim/dispatch.rs | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs | 16++++++++++------
Acrates/storage_sqlite/src/workspace/stock/public_source/dispatch_tests.rs | 182+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtools/xtask/src/architecture/decision_package.rs | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
46 files changed, 1105 insertions(+), 63 deletions(-)

diff --git a/contracts/api_baselines/radroots.txt b/contracts/api_baselines/radroots.txt @@ -166,10 +166,12 @@ pub async fn radroots::orders::Orders<'a>::accept(&self, radroots_execution::wor pub async fn radroots::orders::Orders<'a>::acceptance_status(&self, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> radroots_execution::Result<radroots_execution::session::commerce::AcceptanceStatus> pub async fn radroots::orders::Orders<'a>::resume_acceptance(&self, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> radroots_execution::ExecutionResult<radroots_execution::session::commerce::AcceptanceStatus> pub mod radroots::signing +pub use radroots::signing::ArtifactFingerprint pub use radroots::signing::ArtifactRole pub use radroots::signing::AuthorizationHeader pub use radroots::signing::BlossomAuthorizationPlan pub use radroots::signing::BlossomSigningError +pub use radroots::signing::ExactIssuer pub use radroots::signing::ExactRecoveryCapability pub use radroots::signing::ExactRecoveryKind pub use radroots::signing::ExactRecoveryOutcome @@ -179,6 +181,8 @@ pub use radroots::signing::Mode pub use radroots::signing::Operations pub use radroots::signing::OutcomeKind pub use radroots::signing::Provider +pub use radroots::signing::RejectedArtifact +pub use radroots::signing::RejectionReason pub use radroots::signing::SignedArtifact pub use radroots::signing::SigningIntent pub use radroots::signing::SigningOutcome diff --git a/contracts/api_baselines/radroots_execution.txt b/contracts/api_baselines/radroots_execution.txt @@ -153,6 +153,8 @@ impl radroots_execution::session::SignerSession pub async fn radroots_execution::session::SignerSession::verify_commerce_plan(&self, radroots_signing::provider::ProviderCall, &radroots_protocol::commerce::rumor::EncodedCommerceRumor, radroots_protocol::commerce::signing_plan::CommerceSigningPlan) -> core::result::Result<radroots_signing::commerce::VerifiedCommerceSigningPlan, radroots_signing::provider::ProviderError> impl core::clone::Clone for radroots_execution::session::SignerSession pub fn radroots_execution::session::SignerSession::clone(&self) -> Self +impl radroots_signing::issuance::ExactIssuer for radroots_execution::session::SignerSession +pub fn radroots_execution::session::SignerSession::issue_exact(&self, radroots_signing::issuance::SigningIntent) -> radroots_signing::signer::BoxFuture<'_, radroots_signing::issuance::SigningOutcome> pub struct radroots_execution::session::WorkPermit<H: radroots_execution::session::SessionHost> impl<H: radroots_execution::session::SessionHost> core::ops::drop::Drop for radroots_execution::session::WorkPermit<H> pub fn radroots_execution::session::WorkPermit<H>::drop(&mut self) diff --git a/contracts/api_baselines/radroots_signing.txt b/contracts/api_baselines/radroots_signing.txt @@ -241,6 +241,10 @@ impl core::fmt::Debug for radroots_signing::issuance::VerifiedDmRelayAdvertiseme pub fn radroots_signing::issuance::VerifiedDmRelayAdvertisement::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub const radroots_signing::issuance::MAX_EVENT_UNIX_SECONDS: u64 pub const radroots_signing::issuance::SIGNED_EVENT_MAX_BYTES: usize +pub trait radroots_signing::issuance::ExactIssuer: radroots_signing::host::HostBound +pub fn radroots_signing::issuance::ExactIssuer::issue_exact(&self, radroots_signing::issuance::SigningIntent) -> radroots_signing::signer::BoxFuture<'_, radroots_signing::issuance::SigningOutcome> +impl<T: radroots_signing::provider::ParticipantProvider + ?core::marker::Sized> radroots_signing::issuance::ExactIssuer for T +pub fn T::issue_exact(&self, radroots_signing::issuance::SigningIntent) -> radroots_signing::signer::BoxFuture<'_, radroots_signing::issuance::SigningOutcome> pub mod radroots_signing::provider pub enum radroots_signing::provider::PrivateCryptoCapability pub radroots_signing::provider::PrivateCryptoCapability::Nip44V2 diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -382,6 +382,17 @@ pub radroots_storage_sqlite::workspace::StockConsentOutcome::Unknown::command_op pub radroots_storage_sqlite::workspace::StockConsentOutcome::Unknown::control_operation: radroots_domain::identifier::OperationId pub radroots_storage_sqlite::workspace::StockConsentOutcome::Unknown::subject: radroots_domain::identifier::GrantId pub radroots_storage_sqlite::workspace::StockConsentOutcome::Unknown::transaction: radroots_domain::identifier::TransactionId +pub enum radroots_storage_sqlite::workspace::StockDispatchOutcome +pub radroots_storage_sqlite::workspace::StockDispatchOutcome::Obtained +pub radroots_storage_sqlite::workspace::StockDispatchOutcome::Obtained::artifact: radroots_signing::issuance::SignedArtifact +pub radroots_storage_sqlite::workspace::StockDispatchOutcome::Obtained::attempt: radroots_storage_sqlite::workspace::StockSigningAttempt +pub radroots_storage_sqlite::workspace::StockDispatchOutcome::Rejected +pub radroots_storage_sqlite::workspace::StockDispatchOutcome::Rejected::attempt: radroots_storage_sqlite::workspace::StockSigningAttempt +pub radroots_storage_sqlite::workspace::StockDispatchOutcome::Rejected::rejection: radroots_signing::issuance::RejectedArtifact +pub radroots_storage_sqlite::workspace::StockDispatchOutcome::Unissued(radroots_storage_sqlite::workspace::StockUnissuedInvocation) +pub radroots_storage_sqlite::workspace::StockDispatchOutcome::Unknown +pub radroots_storage_sqlite::workspace::StockDispatchOutcome::Unknown::attempt: radroots_storage_sqlite::workspace::StockSigningAttempt +pub radroots_storage_sqlite::workspace::StockDispatchOutcome::Unknown::reason: radroots_signing::provider::ProviderError pub enum radroots_storage_sqlite::workspace::StockGrantOutcome pub radroots_storage_sqlite::workspace::StockGrantOutcome::Committed(radroots_storage_sqlite::workspace::StockGrantReceipt) pub radroots_storage_sqlite::workspace::StockGrantOutcome::Unknown(radroots_domain::identifier::TransactionId) @@ -550,6 +561,8 @@ pub const fn radroots_storage_sqlite::workspace::StockConsentReceipt::subject_gr pub const fn radroots_storage_sqlite::workspace::StockConsentReceipt::transaction_id(&self) -> radroots_domain::identifier::TransactionId pub struct radroots_storage_sqlite::workspace::StockDispatchPermit impl radroots_storage_sqlite::workspace::StockDispatchPermit +pub fn radroots_storage_sqlite::workspace::StockDispatchPermit::dispatch(self, &dyn radroots_signing::issuance::ExactIssuer, radroots_signing::request::CancellationSignal) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<radroots_storage_sqlite::workspace::StockDispatchOutcome, radroots_storage::command::OperationError>> +impl radroots_storage_sqlite::workspace::StockDispatchPermit pub fn radroots_storage_sqlite::workspace::StockDispatchPermit::into_signing_intent(self, radroots_signing::request::CancellationSignal) -> core::result::Result<(radroots_signing::issuance::SigningIntent, radroots_storage_sqlite::workspace::StockSigningAttempt), radroots_storage::command::OperationError> pub const fn radroots_storage_sqlite::workspace::StockDispatchPermit::report(&self) -> &radroots_storage_sqlite::workspace::StockSigningAttempt impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockDispatchPermit @@ -731,6 +744,12 @@ pub fn radroots_storage_sqlite::workspace::StockSourceSnapshot::protected_seal(& pub const fn radroots_storage_sqlite::workspace::StockSourceSnapshot::receipt(&self) -> &radroots_storage_sqlite::workspace::StockSourceReceipt impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockSourceSnapshot pub fn radroots_storage_sqlite::workspace::StockSourceSnapshot::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_sqlite::workspace::StockUnissuedInvocation +impl radroots_storage_sqlite::workspace::StockUnissuedInvocation +pub const fn radroots_storage_sqlite::workspace::StockUnissuedInvocation::attempt(&self) -> &radroots_storage_sqlite::workspace::StockSigningAttempt +pub const fn radroots_storage_sqlite::workspace::StockUnissuedInvocation::reason(&self) -> radroots_signing::provider::ProviderError +impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockUnissuedInvocation +pub fn radroots_storage_sqlite::workspace::StockUnissuedInvocation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage_sqlite::workspace::WorkspaceCrypto impl radroots_storage_sqlite::workspace::WorkspaceCrypto pub fn radroots_storage_sqlite::workspace::WorkspaceCrypto::new(alloc::sync::Arc<dyn radroots_secrets::provider::SecretProvider>, radroots_secrets::id::SecretRef, radroots_secrets::wrapping::SecretMaterial, radroots_secrets::provider::AccessPolicy) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json @@ -256,6 +256,20 @@ "rejected_signer_report_is_nonissuance": false, "generic_peer_installed_before_rejected_self_return": true, "unknown_installation_blocks_delivery": true, + "native_first_dispatch_owns_issuer_invocation": true, + "exact_issuer_port": "radroots_signing.issuance.ExactIssuer", + "native_failure_boundary": "radroots_ffi.Error", + "native_failure_preserves_signer_rejection": true, + "native_failure_fingerprint_bytes": 32, + "native_failure_coverage": "canonical_decimal_strings", + "native_failure_max_bytes": 128, + "browser_failure_boundary": "radroots_browser.bindings.Failure", + "browser_failure_preserves_signer_rejection": true, + "browser_failure_max_bytes": 128, + "original_unissued_live_observation_owner": "radroots_storage_sqlite.workspace.StockUnissuedInvocation", + "original_unissued_observation_is_durable": false, + "original_unissued_observation_releases_stock": false, + "recovery_refusal_creates_original_unissued_observation": false, "ordinary_existing_claim_grants_first_dispatch": false, "ordinary_replay_requires_original_policy_and_current_permit": true, "ordinary_acceptance_implies_delivery": false, diff --git a/crates/execution/README.md b/crates/execution/README.md @@ -255,3 +255,8 @@ through resume and close, including when another operation encounters that retained obligation. Observation append failures likewise retain their original operation. A failed conversion is cached without discarding its signed input; neither a new caller nor close may relabel it as a successful capture. + +The observed `SignerSession` implements Signing's narrow `ExactIssuer` port +through the existing scoped exact call, preserving actual current identity, +capability, single-call admission, callback lifetime and bound-result checks. +The port itself supplies no fresh claim or durable nonissuance authority. diff --git a/crates/execution/src/session/signer.rs b/crates/execution/src/session/signer.rs @@ -18,6 +18,15 @@ struct Binding { callbacks: Shared<dyn SignerCallbacks>, } +impl radroots_signing::issuance::ExactIssuer for SignerSession { + fn issue_exact( + &self, + intent: radroots_signing::issuance::SigningIntent, + ) -> radroots_signing::signer::BoxFuture<'_, radroots_signing::issuance::SigningOutcome> { + Box::pin(self.sign_exact(intent)) + } +} + impl Binding { fn shared_copy(&self) -> Self { Self { diff --git a/crates/execution/tests/signer_session.rs b/crates/execution/tests/signer_session.rs @@ -549,12 +549,13 @@ fn exact_intent(second: bool, operation: u8) -> radroots_signing::issuance::Sign #[cfg(not(target_arch = "wasm32"))] #[test] fn exact_issuance_requires_successful_observation_actual_support_and_the_frozen_key() { + use radroots_signing::issuance::ExactIssuer; use radroots_signing::issuance::OutcomeKind; let Fixture { session, control, .. } = scope(); assert!(matches!( - block_on(session.sign_exact(exact_intent(false, 1))).kind(), + block_on(ExactIssuer::issue_exact(&session, exact_intent(false, 1))).kind(), OutcomeKind::NotDispatched(ProviderError::CapabilityUnavailable) )); block_on(session.observe()).unwrap(); @@ -572,7 +573,7 @@ fn exact_issuance_requires_successful_observation_actual_support_and_the_frozen_ )); assert!(!session.identity_changed()); assert!(matches!( - block_on(session.sign_exact(exact_intent(false, 1))).kind(), + block_on(ExactIssuer::issue_exact(&session, exact_intent(false, 1))).kind(), OutcomeKind::Unknown(_) )); assert_eq!(control.sign_calls.load(Ordering::SeqCst), 1); @@ -607,6 +608,7 @@ fn exact_issuance_requires_successful_observation_actual_support_and_the_frozen_ #[cfg(not(target_arch = "wasm32"))] #[test] fn pending_exact_issuance_retains_callbacks_until_its_bound_outcome_is_observed() { + use radroots_signing::issuance::ExactIssuer; use radroots_signing::issuance::{OutcomeKind, SigningOutcome}; let Fixture { session, @@ -621,7 +623,7 @@ fn pending_exact_issuance_retains_callbacks_until_its_bound_outcome_is_observed( let binding = input.binding(); let (send, receive) = oneshot::channel(); *control.sign_response.lock().unwrap() = Some(receive); - let mut issue = Box::pin(session.sign_exact(input)); + let mut issue = ExactIssuer::issue_exact(&session, input); let mut cx = Context::from_waker(noop_waker_ref()); assert!(issue.as_mut().poll(&mut cx).is_pending()); let mut close = Box::pin(session.close()); diff --git a/crates/radroots/src/signing.rs b/crates/radroots/src/signing.rs @@ -4,9 +4,9 @@ pub use radroots_sdk::signing::{ BlossomAuthorizationPlan, Mode, Operations, Provider, blossom_upload_request, }; pub use radroots_signing::issuance::{ - ArtifactRole, ExactRecoveryCapability, ExactRecoveryKind, ExactRecoveryOutcome, - ExactRecoveryRequest, IntentBinding, OutcomeKind, SignedArtifact, SigningIntent, - SigningOutcome, + ArtifactFingerprint, ArtifactRole, ExactIssuer, ExactRecoveryCapability, ExactRecoveryKind, + ExactRecoveryOutcome, ExactRecoveryRequest, IntentBinding, OutcomeKind, RejectedArtifact, + RejectionReason, SignedArtifact, SigningIntent, SigningOutcome, }; #[cfg(any(feature = "blossom", feature = "nostr", feature = "full"))] diff --git a/crates/radroots_browser/README.md b/crates/radroots_browser/README.md @@ -12,6 +12,16 @@ and uses configured public write targets. Public results remain typed Listings; they acquire no private recipient, wrapping or stock authority. Scoped operation reads and explicit retry retain original signing and publication evidence. +Effectful methods return the shared `ExecutionResult`; queries/resources retain +compact errors. Generated `Failure` values preserve actual code/retry and +original operation/admission with optional fixed signer rejection and exact +SHA-256 prefix coverage. Byte counts are canonical decimal strings. No raw +signer payload crosses the boundary. Unknown projection retains diagnostics, +and drain/close preserve the original pending operation. Native and browser +boundary errors keep a128-byte stack limit by boxing optional diagnostics; +generated callers still receive typed values. Caller diagnostics grant no +business, original nonissuance or stock-release authority. + Accepted commands belong to a bounded local Rust task owner independently of their observation futures. Close permanently stops admission, drains original obtained evidence, disconnects the shared session, disposes original socket and diff --git a/crates/radroots_browser/src/bindings/error.rs b/crates/radroots_browser/src/bindings/error.rs @@ -1,4 +1,4 @@ -use super::Admission; +use super::{Admission, SignerRejection}; use wasm_bindgen::prelude::*; /// Pure command-parser failures retained across the native boundary. @@ -24,12 +24,15 @@ pub enum Error { retry: String, operation_id: Option<String>, admission: Admission, + signer_rejection: Option<Box<SignerRejection>>, }, UnsupportedState { axis: String, operation_id: Option<String>, + signer_rejection: Option<Box<SignerRejection>>, }, } +const _: () = assert!(core::mem::size_of::<Error>() <= 128); impl Error { pub(crate) fn command( field: &'static str, @@ -48,6 +51,7 @@ impl Error { return Self::UnsupportedState { axis: "command_input".to_owned(), operation_id: None, + signer_rejection: None, }; } }; @@ -63,16 +67,22 @@ impl Error { } pub(crate) fn with_operation(self, id: String) -> Self { match self { - Self::UnsupportedState { axis, .. } => Self::UnsupportedState { + Self::UnsupportedState { + axis, + signer_rejection, + .. + } => Self::UnsupportedState { axis, operation_id: Some(id), + signer_rejection, }, value => value, } } -} -impl From<radroots_execution::Error> for Error { - fn from(value: radroots_execution::Error) -> Self { + fn operation( + value: radroots_execution::Error, + signer_rejection: Option<Box<SignerRejection>>, + ) -> Self { let operation_id = value.context().operation_id().map(|v| v.to_string()); match Admission::try_from(value.context().admission()) { Ok(admission) => Self::Operation { @@ -80,14 +90,34 @@ impl From<radroots_execution::Error> for Error { retry: value.retry().as_str().to_owned(), operation_id, admission, + signer_rejection, + }, + Err(Self::UnsupportedState { axis, .. }) => Self::UnsupportedState { + axis, + operation_id, + signer_rejection, + }, + Err(_) => Self::UnsupportedState { + axis: "admission".into(), + operation_id, + signer_rejection, }, - Err(Self::UnsupportedState { axis, .. }) => { - Self::UnsupportedState { axis, operation_id } - } - Err(other) => other, } } } +impl From<radroots_execution::Error> for Error { + fn from(value: radroots_execution::Error) -> Self { + Self::operation(value, None) + } +} +impl From<radroots_execution::ExecutionFailure> for Error { + fn from(value: radroots_execution::ExecutionFailure) -> Self { + Self::operation( + value.error(), + value.signer_rejection().map(|v| Box::new(v.into())), + ) + } +} /// Input-free exception value. No private input, provider cause or path crosses. #[derive(Clone)] @@ -103,6 +133,8 @@ pub struct Failure { pub admission: Option<Admission>, #[wasm_bindgen(readonly, getter_with_clone)] pub field: Option<String>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub signer_rejection: Option<SignerRejection>, } impl From<Error> for Failure { fn from(value: Error) -> Self { @@ -113,6 +145,7 @@ impl From<Error> for Failure { operation_id: None, admission: None, field: Some(field), + signer_rejection: None, }, Error::CommandInput { field, kind } => Self { code: match kind { @@ -125,25 +158,33 @@ impl From<Error> for Failure { operation_id: None, admission: None, field: Some(field), + signer_rejection: None, }, Error::Operation { code, retry, operation_id, admission, + signer_rejection, } => Self { code, retry: Some(retry), operation_id, admission: Some(admission), field: None, + signer_rejection: signer_rejection.map(|v| *v), }, - Error::UnsupportedState { axis, operation_id } => Self { + Error::UnsupportedState { + axis, + operation_id, + signer_rejection, + } => Self { code: "UnsupportedState".into(), retry: None, operation_id, admission: None, field: Some(axis), + signer_rejection: signer_rejection.map(|v| *v), }, } } diff --git a/crates/radroots_browser/src/bindings/mod.rs b/crates/radroots_browser/src/bindings/mod.rs @@ -5,6 +5,7 @@ mod client; mod error; mod inputs; mod receipt; +mod signer_rejection; mod states; mod values; @@ -12,6 +13,7 @@ pub use client::{BrowserClient, Workspace}; pub use error::{Error, Failure, InputFailure}; pub use inputs::{CommandRequest, InquiryInput, ListingInput, ListingReference}; pub use receipt::{Artifact, DeliveryAttempt, Observation, Receipt, Target, TargetPolicy}; +pub use signer_rejection::{SignerFingerprint, SignerRejection, SignerRejectionReason}; pub use states::{ Admission, ArtifactRole, BusinessInstallation, Delivery, Issuance, OperationKind, RecoveryRequirement, SatisfactionClass, SessionState, StartMode, TargetObservation, diff --git a/crates/radroots_browser/src/bindings/receipt.rs b/crates/radroots_browser/src/bindings/receipt.rs @@ -214,6 +214,7 @@ fn project_inner<T>( let context = || Error::UnsupportedState { axis: "receipt_data".to_owned(), operation_id: Some(value.context().operation_id().to_string()), + signer_rejection: None, }; let artifacts = value .artifacts() diff --git a/crates/radroots_browser/src/bindings/signer_rejection.rs b/crates/radroots_browser/src/bindings/signer_rejection.rs @@ -0,0 +1,49 @@ +//! Output-only bounded diagnostics; no raw signer response is retained. +use radroots_signing::issuance::{RejectedArtifact, RejectionReason}; +use wasm_bindgen::prelude::*; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[wasm_bindgen] +pub enum SignerRejectionReason { + TooLarge, + InvalidArtifact, + InvalidSignature, + BindingMismatch, + Unsupported, +} +#[derive(Clone, Debug)] +#[wasm_bindgen] +pub struct SignerFingerprint { + #[wasm_bindgen(readonly, getter_with_clone)] + pub sha256: Vec<u8>, + #[wasm_bindgen(readonly, getter_with_clone)] + pub covered_bytes: String, + #[wasm_bindgen(readonly, getter_with_clone)] + pub total_bytes: String, +} +#[derive(Clone, Debug)] +#[wasm_bindgen] +pub struct SignerRejection { + #[wasm_bindgen(readonly)] + pub reason: SignerRejectionReason, + #[wasm_bindgen(readonly, getter_with_clone)] + pub fingerprint: Option<SignerFingerprint>, +} +impl From<RejectedArtifact> for SignerRejection { + fn from(value: RejectedArtifact) -> Self { + Self { + reason: match value.reason() { + RejectionReason::TooLarge => SignerRejectionReason::TooLarge, + RejectionReason::InvalidArtifact => SignerRejectionReason::InvalidArtifact, + RejectionReason::InvalidSignature => SignerRejectionReason::InvalidSignature, + RejectionReason::BindingMismatch => SignerRejectionReason::BindingMismatch, + _ => SignerRejectionReason::Unsupported, + }, + fingerprint: value.fingerprint().map(|v| SignerFingerprint { + sha256: v.sha256().to_vec(), + covered_bytes: v.covered_bytes().to_string(), + total_bytes: v.total_bytes().to_string(), + }), + } + } +} diff --git a/crates/radroots_browser/src/bindings/states.rs b/crates/radroots_browser/src/bindings/states.rs @@ -29,7 +29,7 @@ macro_rules! bridge { use $native as Native; match value { $(Native::$variant => Ok(Self::$variant),)+ - _ => Err(Error::UnsupportedState { axis: stringify!($name).to_owned(), operation_id: None }), + _ => Err(Error::UnsupportedState { axis: stringify!($name).to_owned(), operation_id: None, signer_rejection: None }), } } } diff --git a/crates/radroots_browser/src/bindings/values.rs b/crates/radroots_browser/src/bindings/values.rs @@ -73,6 +73,7 @@ impl ListingValue { Error::UnsupportedState { axis: "listing_terms".into(), operation_id: None, + signer_rejection: None, } .into() }) @@ -107,6 +108,7 @@ impl ChatValue { _ => Err(Error::UnsupportedState { axis: "chat_relation".into(), operation_id: None, + signer_rejection: None, } .into()), } @@ -118,6 +120,7 @@ impl ChatValue { _ => Err(Error::UnsupportedState { axis: "chat_relation".into(), operation_id: None, + signer_rejection: None, } .into()), } @@ -129,6 +132,7 @@ impl ChatValue { _ => Err(Error::UnsupportedState { axis: "chat_relation".into(), operation_id: None, + signer_rejection: None, } .into()), } diff --git a/crates/radroots_browser/src/client.rs b/crates/radroots_browser/src/client.rs @@ -103,7 +103,7 @@ impl SessionHost for Resources { Box::pin(async move { self.tasks.drain().await?; if let Some(commands) = &self.commands { - commands.drain().await.map_err(operation)?; + commands.drain().await?; } Ok(()) }) @@ -291,7 +291,7 @@ impl Inbox<'_> { &self, context: CommandContext, input: InquireInput, - ) -> Result<OperationReceipt<ChatMessage>> { + ) -> radroots_execution::ExecutionResult<OperationReceipt<ChatMessage>> { self.client .session .inquire(self.client.workspace.clone(), context, input) @@ -310,7 +310,8 @@ impl Listings<'_> { &self, context: CommandContext, input: radroots_protocol::listing::PublishInput, - ) -> Result<OperationReceipt<radroots_domain::listing::Listing>> { + ) -> radroots_execution::ExecutionResult<OperationReceipt<radroots_domain::listing::Listing>> + { self.client .session .publish_listing(self.client.workspace.clone(), context, input) @@ -346,7 +347,7 @@ impl Operations<'_> { &self, id: OperationId, expected: Option<CommandDigest>, - ) -> Result<radroots_execution::OperationStatus> { + ) -> radroots_execution::ExecutionResult<radroots_execution::OperationStatus> { self.client .session .resume_command(self.client.workspace.clone(), &self.scope, id, expected) diff --git a/crates/radroots_browser/tests/browser/consumer.ts b/crates/radroots_browser/tests/browser/consumer.ts @@ -3,6 +3,7 @@ import init, { Receipt, Failure, Admission, BusinessInstallation, Issuance, OperationKind, SessionState, StartMode, TargetObservation, verify_listing_publications, verify_binding_inquiry, advertisements, + FixtureRejection, SignerRejectionReason, } from '@radroots/browser-feasibility'; function assert(value: unknown, message: string): asserts value { @@ -15,6 +16,41 @@ const now = (): string => String(Math.floor(Date.now() / 1000)); const deadline = (): string => String(Math.floor(Date.now() / 1000) + 120); const text = '\uFEFF cafe\u0301 / café 🥕\u0000 '; +async function rejectedSigners(base: string, context: string): Promise<void> { + const cases = [ + {mode:FixtureRejection.Malformed,reason:SignerRejectionReason.InvalidArtifact,covered:'34',total:'34',digest:'ba883ea08dff4c078672a055dd2be042d9debb5b22c66527e4499c068011879d'}, + {mode:FixtureRejection.Oversized,reason:SignerRejectionReason.TooLarge,covered:'65536',total:'65537',digest:'d2d5af5c0316f5c2b119635386239edc87abce035f851c3f6ee127e6c3cbf435'}, + {mode:FixtureRejection.Foreign,reason:SignerRejectionReason.BindingMismatch,covered:undefined,total:undefined,digest:undefined}, + ]; + for (const value of cases) { + const host=await BindingFixture.create_rejected(base.replace('http:','ws:')+'/listing/'+context,`rejected_${context}_${value.mode}`,value.mode); + const client=host.client(),scope=host.workspace(); await client.start(StartMode.Online); + const request=new CommandRequest(id('18'),deadline()),input=listingInput(); + let refused=false; + try { await client.publish_listing(scope,request,input); } + catch(error:unknown) { + assert(error instanceof Failure,'actual generated rejected failure'); refused=true; + assert(error.code==='signer_tampering'&&error.retry==='manual_reconciliation','original failure code/retry'); + assert(error.operation_id===id('18')&&error.admission===Admission.Confirmed,'original confirmed identity'); + const diagnostic=error.signer_rejection; assert(diagnostic,'bounded signer metadata'); + assert(diagnostic.reason===value.reason,'original fixed rejection reason'); + const fingerprint=diagnostic.fingerprint; + if(fingerprint){ + assert(fingerprint.covered_bytes===value.covered&&fingerprint.total_bytes===value.total,'exact coverage strings'); + const bytes=fingerprint.sha256; + assert(bytes.length===32&&Array.from(bytes).map(byte=>byte.toString(16).padStart(2,'0')).join('')===value.digest,'independent original prefix digest'); + fingerprint.free(); + }else assert(value.digest===undefined,'no invented or discarded fingerprint'); + diagnostic.free(); error.free(); + } + assert(refused&&host.signing_calls()===1,'one actual callback and no successful signature'); + const facts=await client.operation(scope,id('18'),undefined); + assert(facts&&facts.business_installation===BusinessInstallation.NotInstalled,'rejection is no business success'); + facts.free(); await client.close(); assert(host.callbacks_closed()===1,'rejected callback owner closes'); scope.close(); + for(const item of [request,input,scope,client,host])item.free(); + } +} + async function refuses(call: () => unknown, code: string): Promise<void> { try { await call(); } catch (error: unknown) { assert(error instanceof Failure, 'typed generated failure'); @@ -153,8 +189,9 @@ export async function run(base: string, context: string): Promise<unknown> { await readClient.close(); await resumedClient.close(); assert(privateReopened.callbacks_closed() === 1 && reopened.callbacks_closed() === 1, 'all original callback scopes close'); await refuses(()=>client.start(StartMode.Online),'capability_unavailable'); + await rejectedSigners(base,context); scope.close(); resumedScope.close(); buyerScope.close(); readScope.close(); for (const value of [original,resumed,message,read]) value.free(); for (const value of [request,denied,privateRequest,input,inquiry,scope,resumedScope,buyerScope,readScope,client,resumedClient,buyerClient,readClient,seller,reopened,buyer,privateReopened]) value.free(); - return {passed:['packed generated public call and exact replay','reopen/query and original exact-byte retry','all typed receipt axes','private JS call and independent nested authentication','bounded inputs, scope and lifecycle refusals','actual ordered close'],revision,messageId}; + return {passed:['packed generated public call and exact replay','reopen/query and original exact-byte retry','all typed receipt axes','private JS call and independent nested authentication','bounded inputs, scope and lifecycle refusals','actual ordered close','bounded rejected signer metadata and exact coverage'],revision,messageId}; } diff --git a/crates/radroots_browser/tests/browser/packed.mjs b/crates/radroots_browser/tests/browser/packed.mjs @@ -107,7 +107,7 @@ try{ worker.onerror=event=>{worker.terminate();reject(Error(event.message));}; worker.onmessage=event=>{worker.terminate();event.data.error?reject(Error(event.data.error)):resolve(event.data);};worker.postMessage(base); }),base); - assert.equal(main.passed.length,6);assert.deepEqual(main.passed,dedicated.passed);assert.deepEqual(errors,[]); + assert.equal(main.passed.length,7);assert.deepEqual(main.passed,dedicated.passed);assert.deepEqual(errors,[]); for(const context of ['main','worker']){ const publications=observed.filter(item=>item.route==='/'+context&&item.message[0]==='EVENT'); assert.equal(publications.length,2);assert.equal(new Set(publications.map(item=>item.message[1].id)).size,2); diff --git a/crates/radroots_browser/tests/browser/src/binding_fixture.rs b/crates/radroots_browser/tests/browser/src/binding_fixture.rs @@ -2,6 +2,98 @@ use super::*; use radroots_browser::bindings::{BrowserClient, Workspace}; +#[derive(Clone, Copy)] +#[wasm_bindgen] +pub enum FixtureRejection { + Malformed, + Oversized, + Foreign, +} + +// Controlled callback responses through the production scoped issuer. +struct RejectedSigner { + local: LocalSigner, + mode: FixtureRejection, + calls: Rc<Cell<u32>>, +} +impl radroots_signing::Signer for RejectedSigner { + fn status( + &self, + ) -> BoxFuture<'_, Result<radroots_signing::SignerStatus, radroots_signing::Error>> { + radroots_signing::Signer::status(&self.local) + } + fn sign( + &self, + _: radroots_signing::SignRequest, + ) -> BoxFuture<'_, Result<radroots_signing::SignReceipt, radroots_signing::Error>> { + panic!("rejection fixture must not invoke legacy signing") + } +} +impl radroots_signing::provider::ParticipantProvider for RejectedSigner { + fn provider_state( + &self, + ) -> BoxFuture<'_, Result<radroots_signing::provider::ProviderState, ProviderError>> { + radroots_signing::provider::ParticipantProvider::provider_state(&self.local) + } + fn sign_exact( + &self, + intent: radroots_signing::issuance::SigningIntent, + ) -> BoxFuture<'_, radroots_signing::issuance::SigningOutcome> { + use radroots_signing::issuance::{ArtifactRole, IntentBinding, SigningOutcome}; + self.calls.set(self.calls.get() + 1); + Box::pin(async move { + match self.mode { + FixtureRejection::Malformed => SigningOutcome::capture( + &intent, + "synthetic private rejection canary".into(), + None, + ), + FixtureRejection::Oversized => { + SigningOutcome::capture(&intent, "X".repeat(65537), None) + } + FixtureRejection::Foreign => SigningOutcome::not_dispatched( + IntentBinding::from_components( + OperationId::from_bytes([0xf1; 32]), + [0xf2; 32], + [0xf3; 32], + ArtifactRole::PublicEvent, + None, + core::num::NonZeroU64::new(1).unwrap(), + ) + .unwrap(), + ProviderError::Cancelled, + ), + } + }) + } + fn encrypt_private( + &self, + call: radroots_signing::provider::ProviderCall, + recipient: PublicKey, + text: radroots_signing::provider::PrivateText, + ) -> BoxFuture<'_, Result<radroots_signing::provider::PrivateCiphertext, ProviderError>> { + radroots_signing::provider::ParticipantProvider::encrypt_private( + &self.local, + call, + recipient, + text, + ) + } + fn decrypt_private( + &self, + call: radroots_signing::provider::ProviderCall, + sender: PublicKey, + text: radroots_signing::provider::PrivateCiphertext, + ) -> BoxFuture<'_, Result<radroots_signing::provider::PrivateText, ProviderError>> { + radroots_signing::provider::ParticipantProvider::decrypt_private( + &self.local, + call, + sender, + text, + ) + } +} + #[wasm_bindgen] pub struct BindingFixture { existing: Rc<Existing>, @@ -9,6 +101,8 @@ pub struct BindingFixture { client: Client, scope: WorkspaceSession, callbacks: Rc<Callbacks>, + rejection: Option<FixtureRejection>, + signing_calls: Rc<Cell<u32>>, } #[wasm_bindgen] impl BindingFixture { @@ -18,7 +112,18 @@ impl BindingFixture { seller: bool, ) -> Result<BindingFixture, JsValue> { let existing = Rc::new(Existing::create_scope(&label, seller).await?); - Self::open(existing, base).await + Self::open(existing, base, None).await + } + pub async fn create_rejected( + base: String, + label: String, + mode: FixtureRejection, + ) -> Result<BindingFixture, JsValue> { + let existing = Rc::new(Existing::create_scope(&label, true).await?); + Self::open(existing, base, Some(mode)).await + } + pub fn signing_calls(&self) -> u32 { + self.signing_calls.get() } pub fn client(&self) -> BrowserClient { BrowserClient::from_browser(self.client.clone()) @@ -34,19 +139,45 @@ impl BindingFixture { self.client.state() == SessionState::Closed, "fixture reopen requires explicit actual close", )?; - Self::open(self.existing.clone(), self.base.clone()).await + Self::open(self.existing.clone(), self.base.clone(), self.rejection).await } } impl BindingFixture { - async fn open(existing: Rc<Existing>, base: String) -> Result<Self, JsValue> { + async fn open( + existing: Rc<Existing>, + base: String, + rejection: Option<FixtureRejection>, + ) -> Result<Self, JsValue> { let (client, scope) = existing.open(&base).await?; - let callbacks = signer(&client).await?; + let signing_calls = Rc::new(Cell::new(0)); + let callbacks = if let Some(mode) = rejection { + let callbacks = Rc::new(Callbacks { + quiesced: Cell::new(0), + closed: Cell::new(0), + }); + client + .attach_signer(SignerHandle::new( + Rc::new(RejectedSigner { + local: local_signer(), + mode, + calls: signing_calls.clone(), + }), + callbacks.clone(), + )) + .await + .map_err(fail)?; + callbacks + } else { + signer(&client).await? + }; Ok(Self { existing, base, client, scope, callbacks, + rejection, + signing_calls, }) } } diff --git a/crates/radroots_browser/tests/browser/src/lib.rs b/crates/radroots_browser/tests/browser/src/lib.rs @@ -97,14 +97,17 @@ impl SignerCallbacks for Callbacks { fn signer_clock() -> Result<u64, radroots_signing::Error> { Ok(js_sys::Date::now() as u64) } -async fn signer(client: &Client) -> Result<Rc<Callbacks>, JsValue> { - let signer = LocalSigner::with_clock( +fn local_signer() -> LocalSigner { + LocalSigner::with_clock( parse_secret_key("0000000000000000000000000000000000000000000000000000000000000001") .unwrap(), signer_clock, ) .unwrap() - .with_nonce_source(Rc::new(BrowserNonceSource)); + .with_nonce_source(Rc::new(BrowserNonceSource)) +} +async fn signer(client: &Client) -> Result<Rc<Callbacks>, JsValue> { + let signer = local_signer(); let callbacks = Rc::new(Callbacks { quiesced: Cell::new(0), closed: Cell::new(0), diff --git a/crates/radroots_ffi/README.md b/crates/radroots_ffi/README.md @@ -10,6 +10,15 @@ boundary owns language conversion, with exact identifiers and integer/decimal strings, explicit optional values and tagged business results. It does not implement a second command engine, storage adapter, signer or retry policy. +Effectful command errors preserve the shared execution failure's actual code, +retry class, original operation and admission. Optional `SignerRejection` carries +a fixed reason and optional SHA-256 fingerprint with exact covered/total byte +counts as canonical decimal strings. A prefix digest does not claim full +coverage. No raw signer response or private input enters these diagnostics. +Future unsupported reasons remain explicit, and unsupported state projection +retains any bounded diagnostic. The generated error schema changes with this +contract; source-owned Swift and Kotlin fixtures regenerate and execute it. + Host injection is distinct from a general foreign-language open/enrollment factory, platform custody and callback qualification. These additional surfaces must be implemented and exercised before they are advertised. This package is diff --git a/crates/radroots_ffi/src/error.rs b/crates/radroots_ffi/src/error.rs @@ -1,4 +1,4 @@ -use crate::Admission; +use crate::{Admission, SignerRejection}; /// Pure command-parser failures retained across the native boundary. #[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] @@ -21,13 +21,16 @@ pub enum Error { retry: String, operation_id: Option<String>, admission: Admission, + signer_rejection: Option<Box<SignerRejection>>, }, #[error("unsupported boundary state {axis}")] UnsupportedState { axis: String, operation_id: Option<String>, + signer_rejection: Option<Box<SignerRejection>>, }, } +const _: () = assert!(core::mem::size_of::<Error>() <= 128); impl Error { pub(crate) fn command(field: &'static str, error: radroots::CommandError) -> Self { let kind = match error { @@ -39,6 +42,7 @@ impl Error { return Self::UnsupportedState { axis: "command_input".to_owned(), operation_id: None, + signer_rejection: None, }; } }; @@ -54,16 +58,19 @@ impl Error { } pub(crate) fn with_operation(self, id: String) -> Self { match self { - Self::UnsupportedState { axis, .. } => Self::UnsupportedState { + Self::UnsupportedState { + axis, + signer_rejection, + .. + } => Self::UnsupportedState { axis, operation_id: Some(id), + signer_rejection, }, value => value, } } -} -impl From<radroots::Error> for Error { - fn from(value: radroots::Error) -> Self { + fn operation(value: radroots::Error, signer_rejection: Option<Box<SignerRejection>>) -> Self { let operation_id = value.context().operation_id().map(|v| v.to_string()); match Admission::try_from(value.context().admission()) { Ok(admission) => Self::Operation { @@ -71,11 +78,31 @@ impl From<radroots::Error> for Error { retry: value.retry().as_str().to_owned(), operation_id, admission, + signer_rejection, + }, + Err(Self::UnsupportedState { axis, .. }) => Self::UnsupportedState { + axis, + operation_id, + signer_rejection, + }, + Err(_) => Self::UnsupportedState { + axis: "admission".to_owned(), + operation_id, + signer_rejection, }, - Err(Self::UnsupportedState { axis, .. }) => { - Self::UnsupportedState { axis, operation_id } - } - Err(other) => other, } } } +impl From<radroots::Error> for Error { + fn from(value: radroots::Error) -> Self { + Self::operation(value, None) + } +} +impl From<radroots::ExecutionFailure> for Error { + fn from(value: radroots::ExecutionFailure) -> Self { + Self::operation( + value.error(), + value.signer_rejection().map(|v| Box::new(v.into())), + ) + } +} diff --git a/crates/radroots_ffi/src/lib.rs b/crates/radroots_ffi/src/lib.rs @@ -6,6 +6,7 @@ mod client; mod error; mod inputs; mod receipt; +mod signer_rejection; mod states; mod values; @@ -13,6 +14,7 @@ pub use client::{NativeClient, Workspace}; pub use error::{Error, InputFailure}; pub use inputs::{CommandRequest, InquiryInput, ListingInput, ListingReference}; pub use receipt::{Artifact, DeliveryAttempt, Observation, Receipt, Target, TargetPolicy}; +pub use signer_rejection::{SignerFingerprint, SignerRejection, SignerRejectionReason}; pub use states::{ Admission, ArtifactRole, BusinessInstallation, Delivery, Issuance, OperationKind, RecoveryRequirement, SatisfactionClass, SessionState, StartMode, TargetObservation, diff --git a/crates/radroots_ffi/src/receipt.rs b/crates/radroots_ffi/src/receipt.rs @@ -144,6 +144,7 @@ fn project_inner<T>( let context = || Error::UnsupportedState { axis: "receipt_data".to_owned(), operation_id: Some(value.context().operation_id().to_string()), + signer_rejection: None, }; let artifacts = value .artifacts() diff --git a/crates/radroots_ffi/src/signer_rejection.rs b/crates/radroots_ffi/src/signer_rejection.rs @@ -0,0 +1,40 @@ +//! Bounded output-only signer diagnostics, without raw response material. +use radroots::signing::{RejectedArtifact, RejectionReason}; + +#[derive(Clone, Copy, Debug, Eq, PartialEq, uniffi::Enum)] +pub enum SignerRejectionReason { + TooLarge, + InvalidArtifact, + InvalidSignature, + BindingMismatch, + Unsupported, +} +#[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] +pub struct SignerFingerprint { + pub sha256: Vec<u8>, + pub covered_bytes: String, + pub total_bytes: String, +} +#[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] +pub struct SignerRejection { + pub reason: SignerRejectionReason, + pub fingerprint: Option<SignerFingerprint>, +} +impl From<RejectedArtifact> for SignerRejection { + fn from(value: RejectedArtifact) -> Self { + Self { + reason: match value.reason() { + RejectionReason::TooLarge => SignerRejectionReason::TooLarge, + RejectionReason::InvalidArtifact => SignerRejectionReason::InvalidArtifact, + RejectionReason::InvalidSignature => SignerRejectionReason::InvalidSignature, + RejectionReason::BindingMismatch => SignerRejectionReason::BindingMismatch, + _ => SignerRejectionReason::Unsupported, + }, + fingerprint: value.fingerprint().map(|v| SignerFingerprint { + sha256: v.sha256().to_vec(), + covered_bytes: v.covered_bytes().to_string(), + total_bytes: v.total_bytes().to_string(), + }), + } + } +} diff --git a/crates/radroots_ffi/src/states.rs b/crates/radroots_ffi/src/states.rs @@ -26,7 +26,7 @@ macro_rules! bridge { use $native as Native; match value { $(Native::$variant => Ok(Self::$variant),)+ - _ => Err(Error::UnsupportedState { axis: stringify!($name).to_owned(), operation_id: None }), + _ => Err(Error::UnsupportedState { axis: stringify!($name).to_owned(), operation_id: None, signer_rejection: None }), } } } diff --git a/crates/radroots_ffi/src/values.rs b/crates/radroots_ffi/src/values.rs @@ -56,6 +56,7 @@ impl ListingValue { serde_json::to_vec(self.inner.terms()).map_err(|_| Error::UnsupportedState { axis: "listing_terms".to_owned(), operation_id: None, + signer_rejection: None, }) } } @@ -99,6 +100,7 @@ impl ChatValue { _ => Err(Error::UnsupportedState { axis: "chat_relation".to_owned(), operation_id: None, + signer_rejection: None, }), } } diff --git a/crates/radroots_ffi/tests/native/Cargo.lock b/crates/radroots_ffi/tests/native/Cargo.lock @@ -1719,7 +1719,10 @@ dependencies = [ "radroots_domain", "radroots_event", "radroots_event_codec", + "radroots_nostr", + "radroots_protocol", "radroots_secrets", + "radroots_signing", "radroots_storage", "radroots_transport", "rustix", diff --git a/crates/radroots_ffi/tests/native/Smoke.kt b/crates/radroots_ffi/tests/native/Smoke.kt @@ -158,6 +158,50 @@ private suspend fun cancelledObservers() = coroutineScope { close(host, next) } + +private suspend fun rejectedSignerFlow() { + data class Case(val mode: FixtureRejection, val reason: SignerRejectionReason, val covered: String?, val total: String?, val digest: String?) + val cases = listOf( + Case(FixtureRejection.MALFORMED, SignerRejectionReason.INVALID_ARTIFACT, + "synthetic private rejection canary".toByteArray().size.toString(), "synthetic private rejection canary".toByteArray().size.toString(), + "ba883ea08dff4c078672a055dd2be042d9debb5b22c66527e4499c068011879d"), + Case(FixtureRejection.OVERSIZED, SignerRejectionReason.TOO_LARGE, + "65536", "65537", "d2d5af5c0316f5c2b119635386239edc87abce035f851c3f6ee127e6c3cbf435"), + Case(FixtureRejection.FOREIGN, SignerRejectionReason.BINDING_MISMATCH, null, null, null) + ) + for (case in cases) { + val host = Host.open(seller = true, unknownSigning = false, pauseAfterSigning = false) + host.setRejectedSigning(case.mode) + val session = host.session(); session.client.start(StartMode.ONLINE) + val context = request(host, "18") + var refused = false + try { + session.client.publishListing(session.workspace, context, listing(host, "18")) + } catch (error: RadrootsException.Operation) { + refused = true + check(error.code == "signer_tampering" && error.retry == "manual_reconciliation") + check(error.operationId == context.operationId && error.admission == Admission.CONFIRMED) + val diagnostic = checkNotNull(error.signerRejection) + check(diagnostic.reason == case.reason) + val fingerprint = diagnostic.fingerprint + if (fingerprint != null) { + check(fingerprint.coveredBytes == case.covered && fingerprint.totalBytes == case.total) + check(fingerprint.sha256.size == 32) + check(fingerprint.sha256.joinToString("") { "%02x".format(it.toInt() and 255) } == case.digest) + } else { + check(case.digest == null) + } + } + check(refused) + val facts = session.client.operation(session.workspace, context.operationId, null) + check(facts?.businessInstallation == BusinessInstallation.NOT_INSTALLED) + val measured = host.measurements() + check(measured.signingCalls == "1" && measured.legacySigningCalls == "0" && measured.originalSignedEvents.isEmpty()) + close(host, session) + } +} + + fun main(args: Array<String>) = runBlocking { if ("--plain-panic" in args) { var caught = false @@ -173,5 +217,6 @@ fun main(args: Array<String>) = runBlocking { privateFlowAndErrors() unknownFlow() cancelledObservers() - println("{\"language\":\"kotlin\",\"state\":\"passed\",\"actual_workflows\":4,\"result_panic_caught\":true}") + rejectedSignerFlow() + println("{\"language\":\"kotlin\",\"state\":\"passed\",\"actual_workflows\":5,\"result_panic_caught\":true}") } diff --git a/crates/radroots_ffi/tests/native/Smoke.swift b/crates/radroots_ffi/tests/native/Smoke.swift @@ -104,7 +104,8 @@ func privateFlowAndErrors() async throws { do { _ = try await session.client.inquire(workspace: other.workspace, request: request(host, "13"), input: input) throw SmokeFailure.failed("foreign scope accepted") - } catch Error.Operation(_, _, let operation, let admission) { + } catch Error.Operation(_, _, let operation, let admission, let rejected) { + try check(rejected == nil, "foreign admission has no signer diagnostic") try check(operation == String(repeating: "13", count: 32) && admission == .notAdmitted, "retained safe error context") } try check(try host.measurements().signingCalls == before.signingCalls, "refusal has no signature") @@ -113,7 +114,8 @@ func privateFlowAndErrors() async throws { do { _ = try await session.client.inquire(workspace: session.workspace, request: request(host, "16"), input: input) throw SmokeFailure.failed("closed attachment accepted") - } catch Error.Operation(_, _, _, let admission) { + } catch Error.Operation(_, _, _, let admission, let rejected) { + try check(rejected == nil, "closed admission has no signer diagnostic") try check(admission == .notAdmitted, "actual attachment close releases authority") } try check(try host.measurements().signingCalls == before.signingCalls, "closed scope has no signature") @@ -169,6 +171,44 @@ func cancelledObservers() async throws { try await close(host, next) } + +func rejectedSignerFlow() async throws { + let cases: [(FixtureRejection, SignerRejectionReason, String?, String?, String?)] = [ + (.malformed, .invalidArtifact, String("synthetic private rejection canary".utf8.count), String("synthetic private rejection canary".utf8.count), "ba883ea08dff4c078672a055dd2be042d9debb5b22c66527e4499c068011879d"), + (.oversized, .tooLarge, "65536", "65537", "d2d5af5c0316f5c2b119635386239edc87abce035f851c3f6ee127e6c3cbf435"), + (.foreign, .bindingMismatch, nil, nil, nil) + ] + for (mode, reason, covered, total, digest) in cases { + let host = try await Host.open(seller: true, unknownSigning: false, pauseAfterSigning: false) + host.setRejectedSigning(mode: mode) + let session = host.session(); _ = try await session.client.start(mode: .online) + let context = try request(host, "18") + do { + _ = try await session.client.publishListing(workspace: session.workspace, request: context, input: listing(host, "18")) + throw SmokeFailure.failed("rejected signer accepted") + } catch Error.Operation(let code, let retry, let operation, let admission, let diagnostic) { + try check(code == "signer_tampering" && retry == "manual_reconciliation", "original rejection code/retry") + try check(operation == context.operationId && admission == .confirmed, "original confirmed command") + guard let diagnostic else { throw SmokeFailure.failed("lost bounded signer metadata") } + try check(diagnostic.reason == reason, "fixed rejection reason") + if let fingerprint = diagnostic.fingerprint { + try check(fingerprint.coveredBytes == covered && fingerprint.totalBytes == total, "exact prefix coverage") + try check(fingerprint.sha256.count == 32, "bounded SHA-256") + let actual = fingerprint.sha256.map { String(format: "%02x", $0) }.joined() + try check(actual == digest, "actual original prefix hash") + } else { + try check(digest == nil, "no fabricated/missing fingerprint") + } + } + let facts = try await session.client.operation(workspace: session.workspace, operationId: context.operationId, expectedDigest: nil) + try check(facts?.businessInstallation == .notInstalled, "rejection is no business success") + let measured = try host.measurements() + try check(measured.signingCalls == "1" && measured.legacySigningCalls == "0" && measured.originalSignedEvents.isEmpty, "no signature or legacy fallback") + try await close(host, session) + } +} + + @main enum NativeSmoke { static func main() async throws { if CommandLine.arguments.contains("--plain-panic") { _ = fixturePanicProbe(); throw SmokeFailure.failed("plain panic returned") } @@ -191,6 +231,7 @@ func cancelledObservers() async throws { try await privateFlowAndErrors(); trace("swift private workflow passed") try await unknownFlow(); trace("swift unknown workflow passed") try await cancelledObservers(); trace("swift cancellation workflow passed") - print("{\"language\":\"swift\",\"state\":\"passed\",\"actual_workflows\":4,\"result_panic_caught\":true}") + try await rejectedSignerFlow(); trace("swift bounded rejection workflow passed") + print("{\"language\":\"swift\",\"state\":\"passed\",\"actual_workflows\":5,\"result_panic_caught\":true}") } } diff --git a/crates/radroots_ffi/tests/native/src/lib.rs b/crates/radroots_ffi/tests/native/src/lib.rs @@ -94,6 +94,13 @@ pub enum FixturePolicy { Required, } +#[derive(Clone, Copy, uniffi::Enum)] +pub enum FixtureRejection { + Malformed, + Oversized, + Foreign, +} + /// Test resources and counters. The shared client owns every command effect. #[derive(uniffi::Object)] pub struct Host { @@ -205,6 +212,16 @@ impl Host { pub fn set_unknown_signing(&self, unknown: bool) { self.signer.unknown.store(unknown, Ordering::SeqCst); } + pub fn set_rejected_signing(&self, mode: FixtureRejection) { + self.signer.rejection.store( + match mode { + FixtureRejection::Malformed => 1, + FixtureRejection::Oversized => 2, + FixtureRejection::Foreign => 3, + }, + Ordering::SeqCst, + ); + } pub fn release_signer(&self) { self.signer.release(); } diff --git a/crates/radroots_ffi/tests/native/src/signer.rs b/crates/radroots_ffi/tests/native/src/signer.rs @@ -13,7 +13,7 @@ use radroots_signing::{ }; use std::sync::{ Arc, - atomic::{AtomicBool, AtomicU64, Ordering}, + atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, }; use tokio::sync::Notify; @@ -22,6 +22,7 @@ pub(crate) struct MeasuredSigner { pub calls: AtomicU64, pub legacy_calls: AtomicU64, pub unknown: AtomicBool, + pub rejection: AtomicUsize, pub pause_next: AtomicBool, pub paused: AtomicBool, release: Notify, @@ -40,6 +41,7 @@ impl MeasuredSigner { calls: AtomicU64::new(0), legacy_calls: AtomicU64::new(0), unknown: AtomicBool::new(unknown), + rejection: AtomicUsize::new(0), pause_next: AtomicBool::new(pause), paused: AtomicBool::new(false), release: Notify::new(), @@ -70,6 +72,29 @@ impl ParticipantProvider for MeasuredSigner { fn sign_exact(&self, intent: SigningIntent) -> BoxFuture<'_, SigningOutcome> { Box::pin(async move { self.calls.fetch_add(1, Ordering::SeqCst); + match self.rejection.load(Ordering::SeqCst) { + 1 => { + return SigningOutcome::capture( + &intent, + "synthetic private rejection canary".into(), + None, + ); + } + 2 => return SigningOutcome::capture(&intent, "X".repeat(65537), None), + 3 => { + let foreign = radroots_signing::issuance::IntentBinding::from_components( + radroots_domain::OperationId::from_bytes([0xf1; 32]), + [0xf2; 32], + [0xf3; 32], + radroots_signing::issuance::ArtifactRole::PublicEvent, + None, + std::num::NonZeroU64::new(1).unwrap(), + ) + .unwrap(); + return SigningOutcome::not_dispatched(foreign, ProviderError::Cancelled); + } + _ => {} + } if self.unknown.load(Ordering::SeqCst) { return SigningOutcome::unknown(intent.binding(), ProviderError::ProviderFailure); } diff --git a/crates/radroots_ffi/tests/native/tests/flows.rs b/crates/radroots_ffi/tests/native/tests/flows.rs @@ -1,4 +1,5 @@ //! Real host/kernel effects through the same production objects used by languages. + use nostr::JsonUtil; use radroots_ffi::{ Admission, BusinessInstallation, CommandRequest, InquiryInput, Issuance, ListingInput, @@ -450,3 +451,100 @@ async fn lost_observers_preserve_actual_obtained_signature_through_close_and_reo assert_eq!(host.measurements().unwrap().signing_calls, "1"); close(&host, &reopened).await; } + +#[tokio::test] +async fn rejected_command_metadata_crosses_the_actual_native_boundary_without_raw_payloads() { + use radroots_ffi::{Error, SignerRejectionReason}; + use radroots_native_binding_fixture::FixtureRejection; + for (mode, reason, expected) in [ + ( + FixtureRejection::Malformed, + SignerRejectionReason::InvalidArtifact, + Some(( + "synthetic private rejection canary".len().to_string(), + "synthetic private rejection canary".len().to_string(), + "ba883ea08dff4c078672a055dd2be042d9debb5b22c66527e4499c068011879d", + )), + ), + ( + FixtureRejection::Oversized, + SignerRejectionReason::TooLarge, + Some(( + "65536".into(), + "65537".into(), + "d2d5af5c0316f5c2b119635386239edc87abce035f851c3f6ee127e6c3cbf435", + )), + ), + ( + FixtureRejection::Foreign, + SignerRejectionReason::BindingMismatch, + None, + ), + ] { + let host = Host::open(true, false, false).await.unwrap(); + host.set_rejected_signing(mode); + let session = host.session(); + session.client.start(StartMode::Online).await.unwrap(); + let context = request(&host, 70); + let operation = context.operation_id.clone(); + let error = session + .client + .publish_listing(session.workspace.clone(), context, listing(&host, 70)) + .await + .err() + .expect("actual rejected callback"); + assert!(!format!("{error:?} {error}").contains("synthetic private rejection canary")); + let Error::Operation { + code, + retry, + operation_id, + admission, + signer_rejection: Some(rejected), + } = error + else { + panic!("bounded original command diagnostic must cross the generated component") + }; + assert_eq!(code, "signer_tampering"); + assert_eq!(retry, "manual_reconciliation"); + assert_eq!(operation_id.as_deref(), Some(operation.as_str())); + assert_eq!(admission, Admission::Confirmed); + assert_eq!(rejected.reason, reason); + match (rejected.fingerprint, expected) { + (None, None) => {} + (Some(actual), Some((covered, total, digest))) => { + assert_eq!(actual.covered_bytes, covered); + assert_eq!(actual.total_bytes, total); + assert_eq!(actual.sha256.len(), 32); + // Independent Python hashlib vectors, not the producing Rust hash. + assert_eq!( + actual + .sha256 + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::<String>(), + digest + ); + } + _ => panic!("fingerprint presence must survive without fabrication"), + } + let facts = session + .client + .operation(session.workspace.clone(), operation, None) + .await + .unwrap() + .unwrap(); + assert_eq!( + facts.business_installation, + BusinessInstallation::NotInstalled + ); + assert_eq!(host.measurements().unwrap().signing_calls, "1"); + assert_eq!(host.measurements().unwrap().legacy_signing_calls, "0"); + assert!( + host.measurements() + .unwrap() + .original_signed_events + .is_empty() + ); + close(&host, &session).await; + } +} diff --git a/crates/signing/README.md b/crates/signing/README.md @@ -294,3 +294,10 @@ decryption, signs nothing and retains the original call deadline. The proof grants no workspace consent, T1 commit, dispatch, stock or network authority. This portable verifier is shared by scoped execution and concrete native T1; the predecessor Nostr export is removed without an alias. + +`issuance::ExactIssuer` is the narrow target-aware exact-signature IO port. +Participant providers delegate to their existing exact method; an observed +execution scope can supply the same port while retaining identity, capability +and callback lifecycle checks. The port grants no first-dispatch authority or +adapter qualification. A caller-created outcome is not proof of an original +invocation: the concrete executor must own its fresh permit through that call. diff --git a/crates/signing/src/issuance.rs b/crates/signing/src/issuance.rs @@ -36,6 +36,19 @@ pub use exact_recovery::{ ExactRecoveryCapability, ExactRecoveryKind, ExactRecoveryOutcome, ExactRecoveryRequest, }; +/// Narrow exact-signature IO boundary, with native or browser-local futures. +/// Implementations must preserve obtained material and honestly distinguish a +/// pre-dispatch refusal from uncertainty. The port and its response confer no +/// first-dispatch authority, durable evidence or adapter qualification. +pub trait ExactIssuer: crate::host::HostBound { + fn issue_exact(&self, intent: SigningIntent) -> crate::signer::BoxFuture<'_, SigningOutcome>; +} +impl<T: crate::provider::ParticipantProvider + ?Sized> ExactIssuer for T { + fn issue_exact(&self, intent: SigningIntent) -> crate::signer::BoxFuture<'_, SigningOutcome> { + crate::provider::ParticipantProvider::sign_exact(self, intent) + } +} + /// Bounded exact preimage and immutable provenance. It is neither an /// authenticated command context nor evidence of T0/T1 admission. /// It has no automatic input-bearing diagnostics or serialization. diff --git a/crates/signing/tests/package_boundary.rs b/crates/signing/tests/package_boundary.rs @@ -266,6 +266,7 @@ fn production_sources_publish_only_the_approved_traits_and_no_host_stack() { public_traits, [ "CurrentAuthoringAuthority", + "ExactIssuer", "HostBound", "NonceSource", "ParticipantProvider", diff --git a/crates/storage_sqlite/README.md b/crates/storage_sqlite/README.md @@ -543,3 +543,20 @@ and validates a replacement against the existing namespace. It never initializes or migrates a store. Only a confirmed original capture clears database uncertainty; errors/unknown results keep the fence. No current issuance clock, new claim, signature or stock release is obtained. Ordinary outboxes refuse this port. + +`StockDispatchPermit::dispatch` consumes the newly committed first-dispatch +permit and owns one `ExactIssuer` invocation, enforcing the original callback +binding before classifying its output. Only this path constructs the native +non-cloneable `StockUnissuedInvocation` for a matching pre-dispatch refusal. +Obtained artifacts remain owned; foreign callbacks become bounded rejections, +and indeterminate results retain the original claim. Existing/reopened claims, +caller-created reports and exact-recovery refusals cannot create this live +observation. Qualification concerns the actual selected issuer; a custom trait +implementation supplies no execution evidence or guarantee about unrelated +root-key use. The predecessor intent-extraction method consumes the same permit +and supplies no unissued observation while its composing callers await cutover. + +This live observation is not persisted and cannot authorize abort or release. +Catalog13, protected formats and the absent-claims-only abort rule are unchanged. +Retained/durable original negative capture and the composing caller cutover +remain required before claimed-attempt reconciliation can release stock. diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs @@ -25,15 +25,15 @@ mod stock; pub use stock::{ SellerStockConfig, StockAuthorityReceipt, StockBoundSigningPlan, StockCapturedEvidence, StockClaimOutcome, StockClaimReference, StockClaimRequest, StockConsentCapture, - StockConsentMode, StockConsentOutcome, StockConsentReceipt, StockDispatchPermit, - StockEnrollment, StockEvidenceCapture, StockEvidencePage, StockExactReplayPermit, - StockGrantEnrollment, StockGrantOutcome, StockGrantReceipt, StockHistorySnapshot, - StockInstallationOutcome, StockInstallationReceipt, StockInstallationRequest, - StockListingCapture, StockListingOutcome, StockListingReceipt, StockListingSnapshot, - StockOperationSnapshot, StockPublicationWork, StockRecipientSnapshot, StockRequestSnapshot, - StockSigningAttempt, StockSigningPlanOutcome, StockSigningPlanRequest, StockSigningProgress, - StockSnapshotRequest, StockSourceCapture, StockSourceOutcome, StockSourceProfile, - StockSourceReceipt, StockSourceSnapshot, + StockConsentMode, StockConsentOutcome, StockConsentReceipt, StockDispatchOutcome, + StockDispatchPermit, StockEnrollment, StockEvidenceCapture, StockEvidencePage, + StockExactReplayPermit, StockGrantEnrollment, StockGrantOutcome, StockGrantReceipt, + StockHistorySnapshot, StockInstallationOutcome, StockInstallationReceipt, + StockInstallationRequest, StockListingCapture, StockListingOutcome, StockListingReceipt, + StockListingSnapshot, StockOperationSnapshot, StockPublicationWork, StockRecipientSnapshot, + StockRequestSnapshot, StockSigningAttempt, StockSigningPlanOutcome, StockSigningPlanRequest, + StockSigningProgress, StockSnapshotRequest, StockSourceCapture, StockSourceOutcome, + StockSourceProfile, StockSourceReceipt, StockSourceSnapshot, StockUnissuedInvocation, }; mod worker; diff --git a/crates/storage_sqlite/src/workspace/stock.rs b/crates/storage_sqlite/src/workspace/stock.rs @@ -28,8 +28,9 @@ pub(in crate::workspace) mod issuance; mod ledger; mod order_state; pub use issuance::{ - StockCapturedEvidence, StockClaimOutcome, StockClaimRequest, StockDispatchPermit, - StockEvidenceCapture, StockEvidencePage, StockExactReplayPermit, StockSigningAttempt, + StockCapturedEvidence, StockClaimOutcome, StockClaimRequest, StockDispatchOutcome, + StockDispatchPermit, StockEvidenceCapture, StockEvidencePage, StockExactReplayPermit, + StockSigningAttempt, StockUnissuedInvocation, }; pub(in crate::workspace) mod signing_plan; pub(in crate::workspace) mod snapshot; diff --git a/crates/storage_sqlite/src/workspace/stock/issuance.rs b/crates/storage_sqlite/src/workspace/stock/issuance.rs @@ -14,7 +14,10 @@ pub(in crate::workspace) mod evidence; mod projection; pub(in crate::workspace) mod recovery; pub(super) use claim::read_entry; -pub use claim::{StockClaimOutcome, StockClaimRequest, StockDispatchPermit, StockSigningAttempt}; +pub use claim::{ + StockClaimOutcome, StockClaimRequest, StockDispatchOutcome, StockDispatchPermit, + StockSigningAttempt, StockUnissuedInvocation, +}; pub use evidence::{StockCapturedEvidence, StockEvidenceCapture, StockEvidencePage}; pub(super) use projection::{Projection, raw_projection}; pub use recovery::StockExactReplayPermit; diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/claim.rs b/crates/storage_sqlite/src/workspace/stock/issuance/claim.rs @@ -13,6 +13,8 @@ use radroots_signing::{ request::CancellationSignal, }; use std::{num::NonZeroU64, sync::Arc}; +mod dispatch; +pub use dispatch::{StockDispatchOutcome, StockUnissuedInvocation}; pub(in crate::workspace::stock) mod codec; pub(in crate::workspace::stock) use codec::read_entry; diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/claim/dispatch.rs b/crates/storage_sqlite/src/workspace/stock/issuance/claim/dispatch.rs @@ -0,0 +1,99 @@ +//! The fresh native permit owns its one original exact-issuance invocation. +use super::{OperationError, StockDispatchPermit, StockSigningAttempt}; +use radroots_signing::{ + issuance::{ExactIssuer, OutcomeKind, RejectedArtifact, SignedArtifact}, + provider::ProviderError, + request::CancellationSignal, + signer::BoxFuture, +}; + +/// Live observation from the owned original invocation on a qualified issuer. +/// Private construction prevents caller reports or later recovery refusals from +/// becoming this observation. It is neither durable evidence nor an operation- +/// wide/global nonissuance guarantee, and cannot release any stock by itself. +/// +/// ```compile_fail +/// use radroots_storage_sqlite::workspace::{StockSigningAttempt, StockUnissuedInvocation}; +/// fn forge(attempt: StockSigningAttempt) -> StockUnissuedInvocation { +/// StockUnissuedInvocation { attempt, reason: radroots_signing::provider::ProviderError::Cancelled } +/// } +/// ``` +/// ```compile_fail +/// use radroots_storage_sqlite::workspace::StockUnissuedInvocation; +/// fn duplicate(value: StockUnissuedInvocation) -> (StockUnissuedInvocation, StockUnissuedInvocation) { +/// (value.clone(), value) +/// } +/// ``` +pub struct StockUnissuedInvocation { + attempt: StockSigningAttempt, + reason: ProviderError, +} +impl StockUnissuedInvocation { + pub const fn attempt(&self) -> &StockSigningAttempt { + &self.attempt + } + pub const fn reason(&self) -> ProviderError { + self.reason + } +} +impl core::fmt::Debug for StockUnissuedInvocation { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("StockUnissuedInvocation(<redacted>)") + } +} + +/// Independent original invocation facts. None implies durable S or T2. +#[derive(Debug)] +pub enum StockDispatchOutcome { + Obtained { + attempt: StockSigningAttempt, + artifact: SignedArtifact, + }, + Unissued(StockUnissuedInvocation), + Unknown { + attempt: StockSigningAttempt, + reason: ProviderError, + }, + Rejected { + attempt: StockSigningAttempt, + rejection: RejectedArtifact, + }, +} +impl StockDispatchPermit { + /// Consumes the actual newly confirmed permit and invokes this issuer once. + /// The selected issuer must be qualified for its reported outcomes. Losing + /// this wait retains the durable claim's uncertainty; no second permit is + /// created. Exact recovery never enters this method. Caller-provided outcome + /// values cannot construct its original unissued observation. + pub fn dispatch( + self, + issuer: &dyn ExactIssuer, + cancellation: CancellationSignal, + ) -> BoxFuture<'_, Result<StockDispatchOutcome, OperationError>> { + Box::pin(async move { + let (intent, attempt) = self.into_signing_intent(cancellation)?; + let binding = attempt.binding(); + let (_, kind) = issuer + .issue_exact(intent) + .await + .enforce_binding(binding) + .into_parts(); + Ok(match kind { + OutcomeKind::Obtained(artifact) => { + StockDispatchOutcome::Obtained { attempt, artifact } + } + OutcomeKind::NotDispatched(reason) => { + StockDispatchOutcome::Unissued(StockUnissuedInvocation { attempt, reason }) + } + OutcomeKind::Unknown(reason) => StockDispatchOutcome::Unknown { attempt, reason }, + OutcomeKind::Rejected(rejection) => { + StockDispatchOutcome::Rejected { attempt, rejection } + } + _ => StockDispatchOutcome::Unknown { + attempt, + reason: ProviderError::ProviderFailure, + }, + }) + }) + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs @@ -1,5 +1,7 @@ //! Actual claim transactions; only a newly confirmed claim returns a permit. use super::*; +#[path = "dispatch_tests.rs"] +mod dispatch; #[path = "evidence_tests.rs"] mod evidence; #[path = "exact_recovery_tests.rs"] @@ -134,12 +136,14 @@ async fn each_recipient_gets_one_confirmed_permit_and_original_reopen_never_redi panic!("new committed claim must return a permit"); }; assert_eq!(permit.report().recipient(), *recipient); - let (intent, report) = permit - .into_signing_intent(CancellationSignal::new()) - .unwrap(); - let actual = signer.sign_exact(intent).await; - assert_eq!(actual.binding(), report.binding()); - let (_, OutcomeKind::Obtained(artifact)) = actual.into_parts() else { + let crate::workspace::StockDispatchOutcome::Obtained { + attempt: report, + artifact, + } = permit + .dispatch(&signer, CancellationSignal::new()) + .await + .unwrap() + else { panic!("actual exact signer must obtain bytes"); }; artifact.with_json(|raw| assert!(raw.contains("\"sig\""))); diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/dispatch_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/dispatch_tests.rs @@ -0,0 +1,182 @@ +//! Original invocation observations on actual claims, separate from abort. +use super::*; +use crate::workspace::StockDispatchOutcome; +use radroots_signing::{ + issuance::{ExactIssuer, IntentBinding, RejectionReason, SigningIntent, SigningOutcome}, + provider::ProviderError, + signer::BoxFuture, +}; +use std::sync::atomic::{AtomicUsize, Ordering}; +static CLOCK_MODE: AtomicUsize = AtomicUsize::new(0); +static CLOCK_CALLS: AtomicUsize = AtomicUsize::new(0); +fn clock() -> Result<u64, radroots_signing::Error> { + CLOCK_CALLS.fetch_add(1, Ordering::SeqCst); + match CLOCK_MODE.load(Ordering::SeqCst) { + 0 => Ok(0), + 1 => Ok(230000), + 2 => Err(radroots_signing::Error::new( + radroots_signing::error::Kind::InternalError, + )), + _ => Ok(150000), + } +} +#[tokio::test] +async fn owned_original_local_refusal_retains_claim_and_holds_without_authorizing_abort_or_reissue() +{ + for (mode, reason) in [ + (0, ProviderError::ProviderFailure), + (1, ProviderError::DeadlineExceeded), + (2, ProviderError::ProviderFailure), + (3, ProviderError::Cancelled), + ] { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let StockClaimOutcome::Fresh(permit) = claim(&r, &receipt, recipient).await.unwrap() else { + panic!("new committed claim"); + }; + let original = permit.report().clone(); + let minimum = inventory_minimum(&r).await; + CLOCK_MODE.store(mode, Ordering::SeqCst); + CLOCK_CALLS.store(0, Ordering::SeqCst); + let signer = + LocalSigner::with_clock(SecretKey::parse(&format!("{:064x}", 3)).unwrap(), clock) + .unwrap(); + let cancellation = CancellationSignal::new(); + if mode == 3 { + cancellation.cancel(); + } + let StockDispatchOutcome::Unissued(observation) = + permit.dispatch(&signer, cancellation).await.unwrap() + else { + panic!("actual qualified local pre-crypto refusal"); + }; + assert_eq!(CLOCK_CALLS.load(Ordering::SeqCst), 1); + assert_eq!(observation.attempt().attempt_id(), original.attempt_id()); + assert_eq!(observation.attempt().binding(), original.binding()); + assert_eq!( + observation.attempt().transaction_id(), + original.transaction_id() + ); + assert_eq!(observation.reason(), reason); + assert_eq!(inventory_minimum(&r).await, minimum); + assert!(format!("{observation:?}").contains("<redacted>")); + assert!(matches!( + claim(&r, &receipt, recipient).await.unwrap(), + StockClaimOutcome::Existing(_) + )); + let mut raw = database(&r).await; + let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_signing_evidence") + .fetch_one(&mut raw) + .await + .unwrap(); + assert_eq!(rows, 0); + raw.close().await.unwrap(); + let abort = radroots_storage::inventory::StockAbortRequest::new( + r.binding.clone(), + inventory_minimum(&r).await, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + ); + assert!(matches!( + radroots_storage::inventory::InventoryStore::abort_proven_unissued( + &r.store, + abort, + r.enrollment + .proof() + .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) + .unwrap(), + ) + .await, + Err(OperationError::RecoveryRequired) + )); + assert_eq!(inventory_minimum(&r).await, minimum); + assert_pool(&r, 80, 9, 1, 2).await; + assert_pool(&r, 81, 8, 2, 2).await; + drop(observation); + reopen_plain(&mut r).await; + assert_eq!( + read(&r, &receipt, recipient) + .await + .unwrap() + .unwrap() + .binding(), + original.binding() + ); + assert!(matches!( + claim(&r, &receipt, recipient).await.unwrap(), + StockClaimOutcome::Existing(_) + )); + r.store.close().await.unwrap(); + } +} + +// Controlled IO classification model, not qualification of a remote adapter. +struct Callback { + foreign: IntentBinding, + mode: u8, + calls: AtomicUsize, +} +impl ExactIssuer for Callback { + fn issue_exact(&self, intent: SigningIntent) -> BoxFuture<'_, SigningOutcome> { + self.calls.fetch_add(1, Ordering::SeqCst); + Box::pin(async move { + match self.mode { + 0 => SigningOutcome::not_dispatched(self.foreign, ProviderError::Cancelled), + 1 => SigningOutcome::unknown(intent.binding(), ProviderError::ProviderFailure), + _ => SigningOutcome::capture(&intent, "{}".into(), None), + } + }) + } +} +#[tokio::test] +async fn foreign_refusal_unknown_and_malformed_output_never_create_original_unissued_observations() +{ + for mode in 0..3 { + let r = Rig::new().await; + let receipt = ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let other = receipt.rumor().recipients()[1]; + let StockClaimOutcome::Fresh(permit) = claim(&r, &receipt, recipient).await.unwrap() else { + panic!("first claim") + }; + let StockClaimOutcome::Fresh(foreign) = claim(&r, &receipt, other).await.unwrap() else { + panic!("second claim") + }; + let original = permit.report().clone(); + let callback = Callback { + foreign: foreign.report().binding(), + mode, + calls: AtomicUsize::new(0), + }; + drop(foreign); + match permit + .dispatch(&callback, CancellationSignal::new()) + .await + .unwrap() + { + StockDispatchOutcome::Rejected { attempt, rejection } if mode != 1 => { + assert_eq!(attempt.binding(), original.binding()); + if mode == 0 { + assert_eq!(rejection.reason(), RejectionReason::BindingMismatch); + assert_eq!(rejection.fingerprint(), None); + } else { + assert!(rejection.fingerprint().is_some()); + } + } + StockDispatchOutcome::Unknown { attempt, reason } if mode == 1 => { + assert_eq!(attempt.binding(), original.binding()); + assert_eq!(reason, ProviderError::ProviderFailure); + } + other => panic!("no modeled outcome can prove original nonissuance: {other:?}"), + } + assert_eq!(callback.calls.load(Ordering::SeqCst), 1); + assert!(matches!( + claim(&r, &receipt, recipient).await.unwrap(), + StockClaimOutcome::Existing(_) + )); + assert_pool(&r, 80, 9, 1, 2).await; + assert_pool(&r, 81, 8, 2, 2).await; + r.store.close().await.unwrap(); + } +} diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -339,6 +339,20 @@ struct SigningPlanBinding { rejected_signer_report_is_nonissuance: bool, generic_peer_installed_before_rejected_self_return: bool, unknown_installation_blocks_delivery: bool, + native_first_dispatch_owns_issuer_invocation: bool, + exact_issuer_port: String, + native_failure_boundary: String, + native_failure_preserves_signer_rejection: bool, + native_failure_fingerprint_bytes: u8, + native_failure_coverage: String, + native_failure_max_bytes: u16, + browser_failure_boundary: String, + browser_failure_preserves_signer_rejection: bool, + browser_failure_max_bytes: u16, + original_unissued_live_observation_owner: String, + original_unissued_observation_is_durable: bool, + original_unissued_observation_releases_stock: bool, + recovery_refusal_creates_original_unissued_observation: bool, ordinary_existing_claim_grants_first_dispatch: bool, ordinary_replay_requires_original_policy_and_current_permit: bool, ordinary_acceptance_implies_delivery: bool, @@ -652,6 +666,37 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && stock .signing_plan_binding .unknown_installation_blocks_delivery + && stock + .signing_plan_binding + .native_first_dispatch_owns_issuer_invocation + && stock.signing_plan_binding.exact_issuer_port + == "radroots_signing.issuance.ExactIssuer" + && stock.signing_plan_binding.native_failure_boundary == "radroots_ffi.Error" + && stock + .signing_plan_binding + .native_failure_preserves_signer_rejection + && stock.signing_plan_binding.native_failure_fingerprint_bytes == 32 + && stock.signing_plan_binding.native_failure_coverage == "canonical_decimal_strings" + && stock.signing_plan_binding.native_failure_max_bytes == 128 + && stock.signing_plan_binding.browser_failure_boundary + == "radroots_browser.bindings.Failure" + && stock + .signing_plan_binding + .browser_failure_preserves_signer_rejection + && stock.signing_plan_binding.browser_failure_max_bytes == 128 + && stock + .signing_plan_binding + .original_unissued_live_observation_owner + == "radroots_storage_sqlite.workspace.StockUnissuedInvocation" + && !stock + .signing_plan_binding + .original_unissued_observation_is_durable + && !stock + .signing_plan_binding + .original_unissued_observation_releases_stock + && !stock + .signing_plan_binding + .recovery_refusal_creates_original_unissued_observation && !stock .signing_plan_binding .ordinary_existing_claim_grants_first_dispatch @@ -1772,6 +1817,26 @@ mod tests { json!(false), ), ("unknown_installation_blocks_delivery", json!(false)), + ("native_first_dispatch_owns_issuer_invocation", json!(false)), + ("exact_issuer_port", json!("legacy_signer_fallback")), + ("native_failure_boundary", json!("discarded_primitive")), + ("native_failure_preserves_signer_rejection", json!(false)), + ("native_failure_fingerprint_bytes", json!(64)), + ("native_failure_coverage", json!("floating_point")), + ("native_failure_max_bytes", json!(256)), + ("browser_failure_boundary", json!("discarded_primitive")), + ("browser_failure_preserves_signer_rejection", json!(false)), + ("browser_failure_max_bytes", json!(256)), + ( + "original_unissued_live_observation_owner", + json!("caller_assertion"), + ), + ("original_unissued_observation_is_durable", json!(true)), + ("original_unissued_observation_releases_stock", json!(true)), + ( + "recovery_refusal_creates_original_unissued_observation", + json!(true), + ), ( "ordinary_obtained_owned_before_descriptor_conversion", json!(false),