lib

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

commit eafc7e212ca6e4e08b98e440dfca02e8ce1bb305
parent f406f431629f17c38a1756cb8186238ffe169b59
Author: triesap <tyson@radroots.org>
Date:   Mon, 26 Oct 2026 02:55:45 +0000

recovery: authorize qualified original local intent replay

- Add a separate original-bound recovery provider contract without legacy fallback.
- Qualify local cryptographic recovery within the original issuance window.
- Authorize existing stock claims under current protected native consent.
- Verify native and Linux recovery, refusal, lifecycle and portable contracts.

Diffstat:
Mcontracts/api_baselines/radroots_nostr.txt | 1+
Mcontracts/api_baselines/radroots_signing.txt | 25+++++++++++++++++++++++++
Mcontracts/api_baselines/radroots_storage_sqlite.txt | 9+++++++++
Mcontracts/architecture/decisions/shared_sdk_refactor.v1.json | 18++++++++++++++++++
Mcrates/nostr/README.md | 10++++++++++
Mcrates/nostr/src/commerce/signing_plan.rs | 18+++++++++++++-----
Mcrates/nostr/src/signing/issuance.rs | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/nostr/src/signing/issuance/tests/exact_recovery_tests.rs | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/nostr/src/signing/private.rs | 12+++++++++++-
Mcrates/nostr/tests/commerce_signing.rs | 2+-
Mcrates/signing/README.md | 11+++++++++++
Mcrates/signing/src/issuance.rs | 4++++
Acrates/signing/src/issuance/exact_recovery.rs | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/signing/src/provider.rs | 35++++++++++++++++++++++++++++++++++-
Mcrates/signing/tests/issuance.rs | 2++
Acrates/signing/tests/issuance/exact_recovery.rs | 177+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/README.md | 17+++++++++++++++++
Mcrates/storage_sqlite/src/workspace/mod.rs | 14+++++++-------
Mcrates/storage_sqlite/src/workspace/stock.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/issuance.rs | 2++
Acrates/storage_sqlite/src/workspace/stock/issuance/recovery.rs | 164+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs | 2++
Acrates/storage_sqlite/src/workspace/stock/public_source/exact_recovery_tests.rs | 524+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/stock/public_source/signing_tests.rs | 10+++++++++-
Mcrates/storage_sqlite/src/workspace/worker.rs | 45++++++++++++++++++++++++++++++++++++++++++++-
Mtools/xtask/src/architecture/api_leakage.rs | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mtools/xtask/src/architecture/decision_package.rs | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
27 files changed, 1540 insertions(+), 26 deletions(-)

diff --git a/contracts/api_baselines/radroots_nostr.txt b/contracts/api_baselines/radroots_nostr.txt @@ -384,6 +384,7 @@ impl radroots_signing::provider::ParticipantProvider for radroots_nostr::signing pub fn radroots_nostr::signing::LocalSigner::decrypt_private(&self, radroots_signing::provider::ProviderCall, radroots_identity::key::PublicKey, radroots_signing::provider::PrivateCiphertext) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<radroots_signing::provider::PrivateText, radroots_signing::provider::ProviderError>> pub fn radroots_nostr::signing::LocalSigner::encrypt_private(&self, radroots_signing::provider::ProviderCall, radroots_identity::key::PublicKey, radroots_signing::provider::PrivateText) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<radroots_signing::provider::PrivateCiphertext, radroots_signing::provider::ProviderError>> pub fn radroots_nostr::signing::LocalSigner::provider_state(&self) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<radroots_signing::provider::ProviderState, radroots_signing::provider::ProviderError>> +pub fn radroots_nostr::signing::LocalSigner::recover_exact(&self, radroots_signing::issuance::exact_recovery::ExactRecoveryRequest) -> radroots_signing::signer::BoxFuture<'_, radroots_signing::issuance::exact_recovery::ExactRecoveryOutcome> pub fn radroots_nostr::signing::LocalSigner::sign_exact(&self, radroots_signing::issuance::SigningIntent) -> radroots_signing::signer::BoxFuture<'_, radroots_signing::issuance::SigningOutcome> impl radroots_signing::signer::Signer for radroots_nostr::signing::LocalSigner pub fn radroots_nostr::signing::LocalSigner::sign(&self, radroots_signing::request::SignRequest) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<radroots_signing::receipt::SignReceipt, radroots_signing::error::Error>> diff --git a/contracts/api_baselines/radroots_signing.txt b/contracts/api_baselines/radroots_signing.txt @@ -148,6 +148,13 @@ pub fn radroots_signing::identity::SigningOperationId::fmt(&self, &mut core::fmt pub mod radroots_signing::issuance pub use radroots_signing::issuance::ArtifactRole pub use radroots_signing::issuance::IntentBinding +#[non_exhaustive] pub enum radroots_signing::issuance::ExactRecoveryCapability +pub radroots_signing::issuance::ExactRecoveryCapability::LocalExactReplay +pub radroots_signing::issuance::ExactRecoveryCapability::Unavailable +#[non_exhaustive] pub enum radroots_signing::issuance::ExactRecoveryKind +pub radroots_signing::issuance::ExactRecoveryKind::Indeterminate(radroots_signing::provider::ProviderError) +pub radroots_signing::issuance::ExactRecoveryKind::Obtained(radroots_signing::issuance::SignedArtifact) +pub radroots_signing::issuance::ExactRecoveryKind::Rejected(radroots_signing::issuance::RejectedArtifact) #[non_exhaustive] pub enum radroots_signing::issuance::OutcomeKind pub radroots_signing::issuance::OutcomeKind::NotDispatched(radroots_signing::provider::ProviderError) pub radroots_signing::issuance::OutcomeKind::Obtained(radroots_signing::issuance::SignedArtifact) @@ -163,6 +170,21 @@ impl radroots_signing::issuance::ArtifactFingerprint pub const fn radroots_signing::issuance::ArtifactFingerprint::covered_bytes(self) -> usize pub const fn radroots_signing::issuance::ArtifactFingerprint::sha256(&self) -> &[u8; 32] pub const fn radroots_signing::issuance::ArtifactFingerprint::total_bytes(self) -> usize +pub struct radroots_signing::issuance::ExactRecoveryOutcome +impl radroots_signing::issuance::ExactRecoveryOutcome +pub const fn radroots_signing::issuance::ExactRecoveryOutcome::binding(&self) -> radroots_protocol::intent::IntentBinding +pub fn radroots_signing::issuance::ExactRecoveryOutcome::from_recovery_verification(radroots_signing::issuance::SigningOutcome) -> Self +pub const fn radroots_signing::issuance::ExactRecoveryOutcome::indeterminate(radroots_protocol::intent::IntentBinding, radroots_signing::provider::ProviderError) -> Self +pub fn radroots_signing::issuance::ExactRecoveryOutcome::into_parts(self) -> (radroots_protocol::intent::IntentBinding, radroots_signing::issuance::ExactRecoveryKind) +pub const fn radroots_signing::issuance::ExactRecoveryOutcome::kind(&self) -> &radroots_signing::issuance::ExactRecoveryKind +pub struct radroots_signing::issuance::ExactRecoveryRequest +impl radroots_signing::issuance::ExactRecoveryRequest +pub const fn radroots_signing::issuance::ExactRecoveryRequest::binding(&self) -> radroots_protocol::intent::IntentBinding +pub const fn radroots_signing::issuance::ExactRecoveryRequest::call(&self) -> &radroots_signing::provider::ProviderCall +pub fn radroots_signing::issuance::ExactRecoveryRequest::new(radroots_signing::issuance::SigningIntent, radroots_signing::provider::ProviderCall) -> core::result::Result<Self, radroots_signing::provider::ProviderError> +pub const fn radroots_signing::issuance::ExactRecoveryRequest::original(&self) -> &radroots_signing::issuance::SigningIntent +impl core::fmt::Debug for radroots_signing::issuance::ExactRecoveryRequest +pub fn radroots_signing::issuance::ExactRecoveryRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_signing::issuance::RejectedArtifact impl radroots_signing::issuance::RejectedArtifact pub const fn radroots_signing::issuance::RejectedArtifact::fingerprint(self) -> core::option::Option<radroots_signing::issuance::ArtifactFingerprint> @@ -252,10 +274,12 @@ impl radroots_signing::provider::ProviderState pub const fn radroots_signing::provider::ProviderState::decryption(self) -> radroots_signing::provider::PrivateCryptoCapability pub const fn radroots_signing::provider::ProviderState::encryption(self) -> radroots_signing::provider::PrivateCryptoCapability pub const fn radroots_signing::provider::ProviderState::exact_issuance(self) -> core::option::Option<radroots_signing::recovery::ReplayCapability> +pub const fn radroots_signing::provider::ProviderState::exact_recovery(self) -> radroots_signing::issuance::ExactRecoveryCapability pub const fn radroots_signing::provider::ProviderState::identity(self) -> radroots_identity::key::PublicKey pub const fn radroots_signing::provider::ProviderState::new(radroots_identity::key::PublicKey, radroots_signing::provider::PrivateCryptoCapability, radroots_signing::provider::PrivateCryptoCapability, radroots_signing::recovery::ReplayCapability) -> Self pub const fn radroots_signing::provider::ProviderState::signing_replay(self) -> radroots_signing::recovery::ReplayCapability pub const fn radroots_signing::provider::ProviderState::with_exact_issuance(self, core::option::Option<radroots_signing::recovery::ReplayCapability>) -> Self +pub const fn radroots_signing::provider::ProviderState::with_exact_recovery(self, radroots_signing::issuance::ExactRecoveryCapability) -> Self pub struct radroots_signing::provider::SignerHandle impl radroots_signing::provider::SignerHandle pub fn radroots_signing::provider::SignerHandle::into_parts(self) -> (radroots_signing::host::Shared<dyn radroots_signing::provider::ParticipantProvider>, radroots_signing::host::Shared<dyn radroots_signing::provider::SignerCallbacks>) @@ -267,6 +291,7 @@ pub trait radroots_signing::provider::ParticipantProvider: radroots_signing::sig pub fn radroots_signing::provider::ParticipantProvider::decrypt_private(&self, radroots_signing::provider::ProviderCall, radroots_identity::key::PublicKey, radroots_signing::provider::PrivateCiphertext) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<radroots_signing::provider::PrivateText, radroots_signing::provider::ProviderError>> pub fn radroots_signing::provider::ParticipantProvider::encrypt_private(&self, radroots_signing::provider::ProviderCall, radroots_identity::key::PublicKey, radroots_signing::provider::PrivateText) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<radroots_signing::provider::PrivateCiphertext, radroots_signing::provider::ProviderError>> pub fn radroots_signing::provider::ParticipantProvider::provider_state(&self) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<radroots_signing::provider::ProviderState, radroots_signing::provider::ProviderError>> +pub fn radroots_signing::provider::ParticipantProvider::recover_exact(&self, radroots_signing::issuance::ExactRecoveryRequest) -> radroots_signing::signer::BoxFuture<'_, radroots_signing::issuance::ExactRecoveryOutcome> pub fn radroots_signing::provider::ParticipantProvider::sign_exact(&self, radroots_signing::issuance::SigningIntent) -> radroots_signing::signer::BoxFuture<'_, radroots_signing::issuance::SigningOutcome> pub trait radroots_signing::provider::SignerCallbacks: radroots_signing::host::HostBound pub fn radroots_signing::provider::SignerCallbacks::close(&self) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<(), radroots_signing::provider::ProviderError>> diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -428,6 +428,8 @@ pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::initialize_loc pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::open_existing(&std::path::Path, radroots_storage::workspace::AttachmentInput, radroots_storage_sqlite::workspace::WorkspaceCrypto, alloc::sync::Arc<dyn radroots_storage::workspace::WorkspaceClock>) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::revoke(&self, radroots_storage::workspace::AttachmentInput, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> impl radroots_storage_sqlite::workspace::NativeWorkspace +pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::authorize_stock_exact_replay(&self, radroots_storage_sqlite::workspace::StockClaimRequest, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::StockExactReplayPermit, radroots_storage::command::OperationError> +impl radroots_storage_sqlite::workspace::NativeWorkspace pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::bind_stock_signing_intents(&self, radroots_storage_sqlite::workspace::StockSigningPlanRequest, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::StockSigningPlanOutcome, radroots_storage::command::OperationError> pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_signing_plan(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage_sqlite::workspace::StockBoundSigningPlan>, radroots_storage::command::OperationError> impl radroots_storage_sqlite::workspace::NativeWorkspace @@ -601,6 +603,13 @@ pub const fn radroots_storage_sqlite::workspace::StockEvidenceReceipt::digest(&s pub const fn radroots_storage_sqlite::workspace::StockEvidenceReceipt::observed_at_unix_ms(&self) -> core::option::Option<core::num::nonzero::NonZeroU64> pub const fn radroots_storage_sqlite::workspace::StockEvidenceReceipt::recipient(&self) -> radroots_identity::key::PublicKey pub const fn radroots_storage_sqlite::workspace::StockEvidenceReceipt::signing_attempt_id(&self) -> radroots_domain::identifier::SigningAttemptId +pub struct radroots_storage_sqlite::workspace::StockExactReplayPermit +impl radroots_storage_sqlite::workspace::StockExactReplayPermit +pub const fn radroots_storage_sqlite::workspace::StockExactReplayPermit::authorized_at(&self) -> radroots_domain::context::UnixSeconds +pub fn radroots_storage_sqlite::workspace::StockExactReplayPermit::into_recovery_request(self, radroots_signing::provider::ProviderCall) -> core::result::Result<(radroots_signing::issuance::exact_recovery::ExactRecoveryRequest, radroots_storage_sqlite::workspace::StockSigningAttempt), radroots_storage::command::OperationError> +pub const fn radroots_storage_sqlite::workspace::StockExactReplayPermit::report(&self) -> &radroots_storage_sqlite::workspace::StockSigningAttempt +impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockExactReplayPermit +pub fn radroots_storage_sqlite::workspace::StockExactReplayPermit::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage_sqlite::workspace::StockGrantEnrollment impl radroots_storage_sqlite::workspace::StockGrantEnrollment pub fn radroots_storage_sqlite::workspace::StockGrantEnrollment::input(&self) -> &radroots_storage::workspace::AttachmentInput diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json @@ -72,6 +72,24 @@ "existing_order_or_history_recovery": false }, "native_seller_stock_authority": { + "qualified_local_recovery": { + "provider_method": "radroots_signing.provider.ParticipantProvider.recover_exact", + "adapter": "radroots_nostr.signing.LocalSigner", + "native_authorizer": "NativeWorkspace.authorize_stock_exact_replay", + "captured_replay": "local_replay_safe", + "native_catalog": 13, + "worker_charge_bytes": 1048576, + "existing_protected_claim_required": true, + "current_execute_consent_required": true, + "original_window_required": true, + "call_budget_extends_original_window": false, + "recovery_refusal_proves_original_unissued": false, + "creates_claim_or_stock_effect": false, + "provider_work_inside_sql": false, + "unsupported_legacy_fallback": false, + "after_expiry_retrieval_available": false, + "legacy_and_first_dispatch_unchanged": true + }, "scope": "seller_stock_owner", "database": "stock_execution_v1.sqlite", "lock": ".stock_execution_v1.lock", diff --git a/crates/nostr/README.md b/crates/nostr/README.md @@ -181,6 +181,16 @@ durable transition. The owning successor contract is The optional pinned Node fixture producer under `tools/protocol_oracle` is development-only; standalone Rust tests consume checked-in synthetic vectors. +The local participant adapter implements separately qualified exact-intent +recovery through `recover_exact`. It recomputes only the complete original +preimage while the original first-issuance window remains open and the current +recovery-call budget permits work. A longer call budget cannot renew the original +window: the earlier claim may have preceded an invocation that never began. +Identity/clock/cancellation refusal retains original uncertainty, and post-effect +clock failure cannot discard obtained bytes. This path performs no encryption, +route replacement, network call or legacy fallback. After-expiry durable signer +retrieval is unavailable. Legacy replay and first-dispatch behavior are unchanged. + `commerce::VerifiedCommerceSigningPlan::verify` checks both exact recipient ciphertexts against the original rumor through the selected participant provider, verifies original signed DM advertisements and their selected subsets, diff --git a/crates/nostr/src/commerce/signing_plan.rs b/crates/nostr/src/commerce/signing_plan.rs @@ -84,16 +84,24 @@ async fn state( replay: SigningReplay, ) -> Result<(), ProviderError> { let state = provider.provider_state().await?; - let expected = match replay { - SigningReplay::NonReplayable => ReplayCapability::NonReplayable, - SigningReplay::LocalReplaySafe => ReplayCapability::LocalReplaySafe, - SigningReplay::ExactReplayByRequestId => ReplayCapability::ExactReplayByRequestId, + let supported = match replay { + SigningReplay::NonReplayable => { + state.exact_issuance() == Some(ReplayCapability::NonReplayable) + } + SigningReplay::LocalReplaySafe => { + state.exact_issuance().is_some() + && state.exact_recovery() + == radroots_signing::issuance::ExactRecoveryCapability::LocalExactReplay + } + SigningReplay::ExactReplayByRequestId => { + state.exact_issuance() == Some(ReplayCapability::ExactReplayByRequestId) + } }; if call.identity() != rumor.author() || state.identity() != rumor.author() || state.encryption() != PrivateCryptoCapability::Nip44V2 || state.decryption() != PrivateCryptoCapability::Nip44V2 - || state.exact_issuance() != Some(expected) + || !supported { return Err(ProviderError::CapabilityUnavailable); } diff --git a/crates/nostr/src/signing/issuance.rs b/crates/nostr/src/signing/issuance.rs @@ -46,6 +46,71 @@ impl LocalSigner { } } +impl LocalSigner { + pub(super) fn recover_original( + &self, + request: radroots_signing::issuance::ExactRecoveryRequest, + ) -> BoxFuture<'_, radroots_signing::issuance::ExactRecoveryOutcome> { + use radroots_signing::issuance::ExactRecoveryOutcome; + Box::pin(async move { + let binding = request.binding(); + let original = request.original(); + if original.author() != self.public_key || request.call().identity() != self.public_key + { + return ExactRecoveryOutcome::indeterminate( + binding, + ProviderError::IdentityChanged, + ); + } + let unsigned = + match original.with_event(crate::plan_signing::unsigned_event_from_fields) { + Ok(unsigned) => unsigned, + Err(_) => { + return ExactRecoveryOutcome::indeterminate( + binding, + ProviderError::InvalidInput, + ); + } + }; + let now = match (self.clock)() { + Ok(now) => now, + Err(_) => { + return ExactRecoveryOutcome::indeterminate( + binding, + ProviderError::ProviderFailure, + ); + } + }; + // A claim may have committed before its original invocation ever + // started. Recomputing after original expiry could then create the + // first signature late. A new recovery budget cannot permit that. + if let Err(reason) = original.check_before_effect(self.public_key, now) { + return ExactRecoveryOutcome::indeterminate(binding, reason); + } + if let Err(reason) = request.call().check_before_effect(self.public_key, now) { + return ExactRecoveryOutcome::indeterminate(binding, reason); + } + // Only this qualified local adapter performs exact-preimage replay. + // Unsupported providers never fall through to legacy signing. + let event = match unsigned.sign_with_keys(&self.keys) { + Ok(event) => event, + Err(_) => { + return ExactRecoveryOutcome::indeterminate( + binding, + ProviderError::ProviderFailure, + ); + } + }; + let observed = (self.clock)().ok().and_then(NonZeroU64::new); + ExactRecoveryOutcome::from_recovery_verification(SigningOutcome::capture( + original, + event.as_json(), + observed, + )) + }) + } +} + #[cfg(test)] mod tests { use super::*; @@ -64,6 +129,8 @@ mod tests { const AUTHOR: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; const CREATED: u64 = 1_700_000_000; const DEADLINE: u64 = CREATED * 1000 + 10_000; + #[path = "exact_recovery_tests.rs"] + mod exact_recovery; #[derive(Default)] struct ClockState { calls: usize, @@ -76,6 +143,8 @@ mod tests { let mut state = state.borrow_mut(); state.calls += 1; match (state.mode, state.calls) { + (8, 1) => Ok(DEADLINE), + (9, 2) => Ok(u64::MAX), (1, 2) | (3, 1) => Err(SigningError::new(Kind::InternalError)), (2, 2) => Ok(DEADLINE + 1), (4, 1) | (7, 2) => Ok(0), diff --git a/crates/nostr/src/signing/issuance/tests/exact_recovery_tests.rs b/crates/nostr/src/signing/issuance/tests/exact_recovery_tests.rs @@ -0,0 +1,116 @@ +//! Real local signatures with the original issuance window kept intact. +use super::*; +use radroots_signing::issuance::{ + ExactRecoveryCapability, ExactRecoveryKind, ExactRecoveryRequest, +}; + +fn request(original: SigningIntent, cancellation: CancellationSignal) -> ExactRecoveryRequest { + ExactRecoveryRequest::new( + original, + ProviderCall::new( + AUTHOR.parse().unwrap(), + NonZeroU64::new(DEADLINE + 10_000).unwrap(), + cancellation, + ), + ) + .unwrap() +} + +#[tokio::test] +async fn local_recovery_returns_only_original_exact_fields_and_keeps_obtained_bytes_after_observation_failure() + { + for mode in [0, 1, 2, 6, 7, 9] { + let (signer, original) = setup(mode); + let expected = original.binding(); + let event_id = original.with_event(|_, id| id); + let state = signer.provider_state().await.unwrap(); + assert_eq!( + state.exact_issuance(), + Some(ReplayCapability::NonReplayable) + ); + assert_eq!( + state.exact_recovery(), + ExactRecoveryCapability::LocalExactReplay + ); + let outcome = signer + .recover_exact(request(original, CancellationSignal::new())) + .await; + assert_eq!(outcome.binding(), expected); + let ExactRecoveryKind::Obtained(artifact) = outcome.kind() else { + panic!("actual original signature lost: {outcome:?}") + }; + artifact.with_json(|raw| { + let event = nostr::Event::from_json(raw).unwrap(); + event.verify().unwrap(); + assert_eq!(event.id.to_hex(), event_id.to_hex()); + assert_eq!(event.pubkey.to_hex(), AUTHOR); + assert_eq!(event.content, "synthetic unchanged exact preimage"); + }); + assert_eq!( + artifact.observed_at_unix_ms().is_none(), + matches!(mode, 1 | 7 | 9) + ); + CLOCK.with(|state| assert_eq!(state.borrow().calls, 2)); + } +} + +#[tokio::test] +async fn fresh_recovery_budget_never_renews_expired_original_or_proves_it_unissued() { + for mode in [3, 4, 5, 8] { + let (signer, original) = setup(mode); + let expected = original.binding(); + let outcome = signer + .recover_exact(request(original, CancellationSignal::new())) + .await; + assert_eq!(outcome.binding(), expected); + assert!(matches!( + outcome.kind(), + ExactRecoveryKind::Indeterminate( + ProviderError::ProviderFailure | ProviderError::DeadlineExceeded + ) + )); + CLOCK.with(|state| assert_eq!(state.borrow().calls, 1)); + } +} + +#[tokio::test] +async fn current_cancellation_wrong_actual_key_and_shorter_recovery_budget_refuse_before_crypto() { + let (signer, original) = setup(0); + let signal = CancellationSignal::new(); + signal.cancel(); + let outcome = signer.recover_exact(request(original, signal)).await; + assert!(matches!( + outcome.kind(), + ExactRecoveryKind::Indeterminate(ProviderError::Cancelled) + )); + CLOCK.with(|state| assert_eq!(state.borrow().calls, 1)); + let (_, original) = setup(0); + let other = LocalSigner::with_clock( + parse_secret_key("0000000000000000000000000000000000000000000000000000000000000002") + .unwrap(), + clock, + ) + .unwrap(); + let outcome = other + .recover_exact(request(original, CancellationSignal::new())) + .await; + assert!(matches!( + outcome.kind(), + ExactRecoveryKind::Indeterminate(ProviderError::IdentityChanged) + )); + CLOCK.with(|state| assert_eq!(state.borrow().calls, 0)); + let (signer, original) = setup(0); + let call = ProviderCall::new( + signer.public_key(), + NonZeroU64::new(CREATED * 1000).unwrap(), + CancellationSignal::new(), + ); + let outcome = signer + .recover_exact(ExactRecoveryRequest::new(original, call).unwrap()) + .await; + assert!(matches!( + outcome.kind(), + ExactRecoveryKind::Indeterminate(ProviderError::DeadlineExceeded) + )); + CLOCK.with(|state| assert_eq!(state.borrow().calls, 1)); +} diff --git a/crates/nostr/src/signing/private.rs b/crates/nostr/src/signing/private.rs @@ -57,7 +57,10 @@ impl ParticipantProvider for LocalSigner { ) .with_exact_issuance(Some( radroots_signing::recovery::ReplayCapability::NonReplayable, - ))) + )) + .with_exact_recovery( + radroots_signing::issuance::ExactRecoveryCapability::LocalExactReplay, + )) }) } @@ -68,6 +71,13 @@ impl ParticipantProvider for LocalSigner { self.issue_exact(intent) } + fn recover_exact( + &self, + request: radroots_signing::issuance::ExactRecoveryRequest, + ) -> BoxFuture<'_, radroots_signing::issuance::ExactRecoveryOutcome> { + self.recover_original(request) + } + fn encrypt_private( &self, call: ProviderCall, diff --git a/crates/nostr/tests/commerce_signing.rs b/crates/nostr/tests/commerce_signing.rs @@ -212,6 +212,6 @@ async fn independent_peer_self_ciphertexts_routes_and_exact_intents_verify_and_a rebuild(original, SigningReplay::LocalReplaySafe, false) ) .await - .is_err() + .is_ok() ); } diff --git a/crates/signing/README.md b/crates/signing/README.md @@ -98,6 +98,17 @@ chat, record, rumor and complete-event limits before using these primitives. Capability and replay observations do not replace actual provider qualification or permit reissue of retained uncertain work. +`ParticipantProvider::recover_exact` is a separate original-intent boundary. +`ExactRecoveryRequest` retains the complete original intent and a distinct +recovery-call budget. The executor must check captured T1 replay policy, current +authorization and the actual adapter's documented method. Unsupported adapters +return original-bound indeterminate state without calling legacy or first-issue +signing. `ExactRecoveryOutcome` has no proven-unissued variant: refusal, expiry +or cancellation of this invocation proves nothing about the earlier invocation. +Obtained bytes are independently verified against the original fields/binding +and must remain owned through append-only durable capture. Provider capability +observations, request construction and outcome metadata confer no authority. + `SignerHandle` pairs a provider with its exact `SignerCallbacks` host scope. The lower signing port owns this contract so adapters do not depend on an executor. A composing lifecycle owner must quiesce dispatch, drain observers, diff --git a/crates/signing/src/issuance.rs b/crates/signing/src/issuance.rs @@ -31,6 +31,10 @@ mod dm_relays; pub use dm_relays::VerifiedDmRelayAdvertisement; pub use radroots_protocol::intent::{ArtifactRole, IntentBinding}; +mod exact_recovery; +pub use exact_recovery::{ + ExactRecoveryCapability, ExactRecoveryKind, ExactRecoveryOutcome, ExactRecoveryRequest, +}; /// Bounded exact preimage and immutable provenance. It is neither an /// authenticated command context nor evidence of T0/T1 admission. diff --git a/crates/signing/src/issuance/exact_recovery.rs b/crates/signing/src/issuance/exact_recovery.rs @@ -0,0 +1,109 @@ +//! Exact-intent recovery data. Refusal of a recovery call proves nothing about +//! the original invocation and can never authorize a stock release. +use super::{ + IntentBinding, OutcomeKind, RejectedArtifact, SignedArtifact, SigningIntent, SigningOutcome, +}; +use crate::provider::{ProviderCall, ProviderError}; + +/// Support actually implemented by a provider, requiring independent adapter +/// qualification. A declaration alone is never permission to request an intent. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum ExactRecoveryCapability { + /// No qualified original-intent recovery method is available. + Unavailable, + /// A local custody owner can recompute only the complete original preimage + /// while its original first-issuance window is still open. + LocalExactReplay, +} + +/// Original immutable intent and a distinct bounded recovery-call budget. +/// Construction renews no original first-issuance deadline or business consent. +pub struct ExactRecoveryRequest { + original: SigningIntent, + call: ProviderCall, +} +impl ExactRecoveryRequest { + /// Checks identity and representation only. The executor must authenticate + /// current original-operation recovery access and the adapter's support. + pub fn new(original: SigningIntent, call: ProviderCall) -> Result<Self, ProviderError> { + if original.author() != call.identity() { + return Err(ProviderError::IdentityChanged); + } + if call.deadline_unix_ms().get() > super::MAX_OBSERVATION_UNIX_MS { + return Err(ProviderError::InvalidInput); + } + Ok(Self { original, call }) + } + /// Borrows the exact original fields, event ID, deadline and intent binding. + pub const fn original(&self) -> &SigningIntent { + &self.original + } + /// Borrows only this recovery invocation's identity/deadline/cancellation. + pub const fn call(&self) -> &ProviderCall { + &self.call + } + /// Returns the immutable original intent binding, never a new request ID. + pub const fn binding(&self) -> IntentBinding { + self.original.binding() + } +} +impl core::fmt::Debug for ExactRecoveryRequest { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("ExactRecoveryRequest(<redacted>)") + } +} + +/// Recovery observations do not include a proven-unissued variant. +#[derive(Debug)] +#[non_exhaustive] +pub enum ExactRecoveryKind { + /// Exact authenticated original-intent bytes are now obtained. + Obtained(SignedArtifact), + /// The original issuance remains unresolved, including unsupported methods, + /// current refusal, cancellation and failure of this recovery invocation. + Indeterminate(ProviderError), + /// Untrusted output is neither success nor proof of original nonissuance. + Rejected(RejectedArtifact), +} + +/// A bound recovery observation, distinct from durable capture or business state. +#[derive(Debug)] +pub struct ExactRecoveryOutcome { + binding: IntentBinding, + kind: ExactRecoveryKind, +} +impl ExactRecoveryOutcome { + /// Retains uncertainty about the original intent without dispatching work. + pub const fn indeterminate(binding: IntentBinding, reason: ProviderError) -> Self { + Self { + binding, + kind: ExactRecoveryKind::Indeterminate(reason), + } + } + /// Converts actual exact-field verification output. A pre-dispatch refusal + /// for a recovery invocation cannot prove the original was unissued. + pub fn from_recovery_verification(outcome: SigningOutcome) -> Self { + let (binding, kind) = outcome.into_parts(); + let kind = match kind { + OutcomeKind::Obtained(value) => ExactRecoveryKind::Obtained(value), + OutcomeKind::Rejected(value) => ExactRecoveryKind::Rejected(value), + OutcomeKind::Unknown(reason) | OutcomeKind::NotDispatched(reason) => { + ExactRecoveryKind::Indeterminate(reason) + } + }; + Self { binding, kind } + } + /// Returns the original operation/intent binding. + pub const fn binding(&self) -> IntentBinding { + self.binding + } + /// Borrows the actual observation, never permission to release or reissue. + pub const fn kind(&self) -> &ExactRecoveryKind { + &self.kind + } + /// Transfers obtained original bytes to their durable evidence owner. + pub fn into_parts(self) -> (IntentBinding, ExactRecoveryKind) { + (self.binding, self.kind) + } +} diff --git a/crates/signing/src/provider.rs b/crates/signing/src/provider.rs @@ -165,6 +165,7 @@ pub struct ProviderState { decryption: PrivateCryptoCapability, signing_replay: crate::recovery::ReplayCapability, exact_issuance: Option<crate::recovery::ReplayCapability>, + exact_recovery: crate::issuance::ExactRecoveryCapability, } impl ProviderState { /// Reports capabilities actually implemented by the observing provider. @@ -180,6 +181,7 @@ impl ProviderState { decryption, signing_replay, exact_issuance: None, + exact_recovery: crate::issuance::ExactRecoveryCapability::Unavailable, } } /// Returns the observed participant key, independently of any hosted principal. @@ -206,6 +208,21 @@ impl ProviderState { self.exact_issuance } + /// Reports separately implemented original-intent recovery. This metadata + /// alone cannot authorize replay or qualify an adapter. + pub const fn exact_recovery(self) -> crate::issuance::ExactRecoveryCapability { + self.exact_recovery + } + /// Reports actual adapter support, independently of legacy replay and the + /// first-dispatch method. Current access and captured T1 policy still apply. + pub const fn with_exact_recovery( + mut self, + value: crate::issuance::ExactRecoveryCapability, + ) -> Self { + self.exact_recovery = value; + self + } + /// Records the actual provider's qualified exact-intent support. This /// observation alone never authorizes replay or business execution. pub const fn with_exact_issuance( @@ -243,7 +260,7 @@ impl ProviderCall { self.identity } - /// Returns the captured first-issue deadline without consulting a clock. + /// Returns this invocation's captured scheduling deadline without a clock. pub const fn deadline_unix_ms(&self) -> NonZeroU64 { self.deadline_unix_ms } @@ -297,6 +314,22 @@ pub trait ParticipantProvider: Signer { }) } + /// Recovers only the complete original intent according to this adapter's + /// qualified method and the executor's retained T1 policy/current access. + /// Unsupported adapters preserve original uncertainty without invoking any + /// signing method. Refusal of this call proves no original nonissuance. + fn recover_exact( + &self, + request: crate::issuance::ExactRecoveryRequest, + ) -> BoxFuture<'_, crate::issuance::ExactRecoveryOutcome> { + Box::pin(async move { + crate::issuance::ExactRecoveryOutcome::indeterminate( + request.binding(), + ProviderError::CapabilityUnavailable, + ) + }) + } + /// Observes the actual key and currently available methods without signing. fn provider_state(&self) -> BoxFuture<'_, Result<ProviderState, ProviderError>>; /// Encrypts private text using provider-owned custody and qualified entropy. diff --git a/crates/signing/tests/issuance.rs b/crates/signing/tests/issuance.rs @@ -12,6 +12,8 @@ use std::{num::NonZeroU64, str::FromStr}; const AUTHOR: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; const CREATED: u64 = 1_700_000_000; +#[path = "issuance/exact_recovery.rs"] +mod exact_recovery; fn plan(content: &str, tags: Vec<Vec<String>>) -> AuthoredEventPlan { AuthoredEventPlan::from_generic( GenericEventDraft::new( diff --git a/crates/signing/tests/issuance/exact_recovery.rs b/crates/signing/tests/issuance/exact_recovery.rs @@ -0,0 +1,177 @@ +//! Original-bound observations, not authorization or durable effect tests. +use super::*; +use radroots_signing::{ + Error, SignReceipt, SignRequest, Signer, SignerStatus, + provider::{ + ParticipantProvider, PrivateCiphertext, PrivateCryptoCapability, PrivateText, ProviderState, + }, + recovery::ReplayCapability, + signer::BoxFuture, +}; +use std::{ + sync::atomic::{AtomicUsize, Ordering}, + task::{Context, Poll, Waker}, +}; + +fn call(identity: PublicKey, deadline: u64) -> ProviderCall { + ProviderCall::new( + identity, + NonZeroU64::new(deadline).unwrap(), + CancellationSignal::new(), + ) +} + +#[test] +fn recovery_data_preserves_original_binding_and_rejects_foreign_or_unbounded_call_budget() { + let original = intent("private retained original", vec![], 7, 8); + let binding = original.binding(); + let request = ExactRecoveryRequest::new( + original, + call( + PublicKey::from_str(AUTHOR).unwrap(), + CREATED * 1000 + 20_000, + ), + ) + .unwrap(); + assert_eq!(request.binding(), binding); + assert_eq!(request.original().binding(), binding); + assert_eq!( + request.call().deadline_unix_ms().get(), + CREATED * 1000 + 20_000 + ); + assert_eq!(format!("{request:?}"), "ExactRecoveryRequest(<redacted>)"); + let other = + PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5") + .unwrap(); + assert!(matches!( + ExactRecoveryRequest::new( + intent("x", vec![], 7, 8), + call(other, CREATED * 1000 + 20_000) + ), + Err(ProviderError::IdentityChanged) + )); + assert!(matches!( + ExactRecoveryRequest::new( + intent("x", vec![], 7, 8), + call(PublicKey::from_str(AUTHOR).unwrap(), u64::MAX) + ), + Err(ProviderError::InvalidInput) + )); +} + +#[test] +fn refusal_of_this_recovery_invocation_never_proves_original_nonissuance() { + let binding = intent("private retained original", vec![], 7, 8).binding(); + for reason in [ + ProviderError::CapabilityUnavailable, + ProviderError::Cancelled, + ProviderError::DeadlineExceeded, + ProviderError::ProviderFailure, + ] { + for observed in [ + SigningOutcome::not_dispatched(binding, reason), + SigningOutcome::unknown(binding, reason), + ] { + let converted = ExactRecoveryOutcome::from_recovery_verification(observed); + assert_eq!(converted.binding(), binding); + assert!( + matches!(converted.kind(), ExactRecoveryKind::Indeterminate(value) if *value==reason) + ); + } + } +} + +#[test] +fn verified_original_bytes_and_tampering_keep_distinct_recovery_observations() { + let original = intent("private retained original", vec![], 7, 8); + let raw = signed(&original); + let expected = original.binding(); + let recovered = ExactRecoveryOutcome::from_recovery_verification(SigningOutcome::capture( + &original, + raw.clone(), + None, + )); + assert_eq!(recovered.binding(), expected); + let (_, ExactRecoveryKind::Obtained(artifact)) = recovered.into_parts() else { + panic!("actual original bytes lost") + }; + assert_eq!(artifact.with_json(str::to_owned), raw); + assert!(artifact.observed_at_unix_ms().is_none()); + let wrong = signed(&intent("different fields", vec![], 7, 8)); + let rejected = ExactRecoveryOutcome::from_recovery_verification(SigningOutcome::capture( + &original, wrong, None, + )); + assert!(matches!(rejected.kind(), ExactRecoveryKind::Rejected(_))); + assert!(!format!("{rejected:?}").contains("private retained original")); +} + +struct Unsupported(AtomicUsize); +impl Signer for Unsupported { + fn status(&self) -> BoxFuture<'_, Result<SignerStatus, Error>> { + panic!("unexpected legacy status") + } + fn sign(&self, _request: SignRequest) -> BoxFuture<'_, Result<SignReceipt, Error>> { + self.0.fetch_add(1, Ordering::SeqCst); + panic!("legacy fallback") + } +} +impl ParticipantProvider for Unsupported { + fn provider_state(&self) -> BoxFuture<'_, Result<ProviderState, ProviderError>> { + Box::pin(async { + Ok(ProviderState::new( + PublicKey::from_str(AUTHOR).unwrap(), + PrivateCryptoCapability::Unavailable, + PrivateCryptoCapability::Unavailable, + ReplayCapability::LocalReplaySafe, + )) + }) + } + fn sign_exact(&self, _intent: SigningIntent) -> BoxFuture<'_, SigningOutcome> { + self.0.fetch_add(1, Ordering::SeqCst); + panic!("first-dispatch fallback") + } + fn encrypt_private( + &self, + _call: ProviderCall, + _recipient: PublicKey, + _text: PrivateText, + ) -> BoxFuture<'_, Result<PrivateCiphertext, ProviderError>> { + panic!("unexpected encryption") + } + fn decrypt_private( + &self, + _call: ProviderCall, + _sender: PublicKey, + _text: PrivateCiphertext, + ) -> BoxFuture<'_, Result<PrivateText, ProviderError>> { + panic!("unexpected decryption") + } +} + +#[test] +fn an_unsupported_recovery_method_never_falls_back_to_declared_legacy_replay_or_signing() { + let provider = Unsupported(AtomicUsize::new(0)); + let original = intent("private retained original", vec![], 7, 8); + let expected = original.binding(); + let request = ExactRecoveryRequest::new( + original, + call( + PublicKey::from_str(AUTHOR).unwrap(), + CREATED * 1000 + 20_000, + ), + ) + .unwrap(); + let mut future = provider.recover_exact(request); + let Poll::Ready(value) = future + .as_mut() + .poll(&mut Context::from_waker(Waker::noop())) + else { + panic!("unsupported method waited") + }; + assert_eq!(value.binding(), expected); + assert!(matches!( + value.kind(), + ExactRecoveryKind::Indeterminate(ProviderError::CapabilityUnavailable) + )); + assert_eq!(provider.0.load(Ordering::SeqCst), 0); +} diff --git a/crates/storage_sqlite/README.md b/crates/storage_sqlite/README.md @@ -497,3 +497,20 @@ preparation. Fresh T1, claim and installation for an aborted original refuse; original history remains readable. These primitives do not yet provide the complete ordinary caller workflow, claimed-attempt reconciliation, amendments, fulfillment, browser stock or platform resource qualification. + +`authorize_stock_exact_replay` returns a non-cloneable `StockExactReplayPermit` +only for an existing protected catalog13 claim whose retained T1 permits local +exact replay. A short read transaction rechecks current ExecuteAndRecover +consent, original actor/resources, acknowledged minimum, original window and +non-regressing time, order eligibility, backing and raw/root/grant/claim witnesses. +RecoverOnly can read original claims but cannot mint this first-capable replay +permission. Authorization creates no claim, stock movement or root update and +cannot upgrade NonReplayable or predecessor records. The bounded worker owns +accepted authorization after observer loss and drains before close. + +The permit transfers exact original data to the separately qualified provider +after SQL ends. Obtained S uses existing append-only capture and original T2; +indeterminate/refused recovery keeps the original claim nonspendable. No result +of a recovery refusal proves original nonissuance or authorizes cleanup. Complete +ordinary commerce ownership, proven-negative reconciliation and final cross-host +and resource acceptance remain separate requirements. diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs @@ -28,13 +28,13 @@ pub use stock::{ StockClaimReference, StockClaimRequest, StockConsentCapture, StockConsentMode, StockConsentOutcome, StockConsentReceipt, StockDispatchPermit, StockEnrollment, StockEvidenceCapture, StockEvidenceOutcome, StockEvidencePage, StockEvidenceReceipt, - 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, + 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, }; mod worker; diff --git a/crates/storage_sqlite/src/workspace/stock.rs b/crates/storage_sqlite/src/workspace/stock.rs @@ -29,7 +29,7 @@ mod order_state; pub use issuance::{ StockCapturedEvidence, StockClaimOutcome, StockClaimRequest, StockDispatchPermit, StockEvidenceCapture, StockEvidenceOutcome, StockEvidencePage, StockEvidenceReceipt, - StockSigningAttempt, + StockExactReplayPermit, StockSigningAttempt, }; 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 @@ -10,6 +10,7 @@ use sqlx::Row; pub(in crate::workspace) mod claim; 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 evidence::{ @@ -17,6 +18,7 @@ pub use evidence::{ StockEvidenceReceipt, }; pub(super) use projection::{Projection, raw_projection}; +pub use recovery::StockExactReplayPermit; pub(super) async fn check_counts(connection: &mut SqliteConnection) -> Result<(), WorkspaceError> { let catalog: i64 = sqlx::query_scalar("PRAGMA user_version") diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/recovery.rs b/crates/storage_sqlite/src/workspace/stock/issuance/recovery.rs @@ -0,0 +1,164 @@ +//! Qualified local replay authorization over an existing protected claim. +use super::super::{ + inventory::{Turn, acceptance}, + order_state, +}; +use super::{StockClaimRequest, StockSigningAttempt, claim, signing_plan}; +use crate::workspace::{AttachmentProof, NativeWorkspace, WorkspaceError}; +use radroots_domain::UnixSeconds; +use radroots_protocol::intent::SigningReplay; +use radroots_signing::{ + issuance::{ExactRecoveryRequest, SigningIntent}, + provider::ProviderCall, + request::CancellationSignal, +}; +use radroots_storage::command::OperationError; +use sqlx::Connection; + +/// Single-use current authorization for qualified exact local replay only. +/// This is never a new first-dispatch claim, proof of issuance or nonissuance. +pub struct StockExactReplayPermit { + report: StockSigningAttempt, + at: UnixSeconds, +} +impl StockExactReplayPermit { + /// Borrows the original protected attempt; this report cannot mint a permit. + pub const fn report(&self) -> &StockSigningAttempt { + &self.report + } + /// Returns the final checked workspace authorization observation. + pub const fn authorized_at(&self) -> UnixSeconds { + self.at + } + /// Transfers exact original intent data to the separately qualified provider. + /// The owner must retain obtained S through durable capture after observer + /// loss. The actual local adapter checks both original and call windows. + pub fn into_recovery_request( + self, + call: ProviderCall, + ) -> Result<(ExactRecoveryRequest, StockSigningAttempt), OperationError> { + let intent: SigningIntent = claim::intent( + self.report.bound_plan(), + self.report.recipient(), + CancellationSignal::new(), + )?; + if intent.binding() != self.report.binding() { + return Err(OperationError::RecoveryRequired); + } + let request = + ExactRecoveryRequest::new(intent, call).map_err(|_| OperationError::InvalidCommand)?; + Ok((request, self.report)) + } +} +impl core::fmt::Debug for StockExactReplayPermit { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("StockExactReplayPermit(<redacted>)") + } +} + +pub(in crate::workspace) async fn authorize( + turn: &mut Turn<'_>, + request: StockClaimRequest, + proof: AttachmentProof, +) -> Result<StockExactReplayPermit, OperationError> { + let auth = Box::pin(signing_plan::load( + turn, + &request.binding, + request.minimum, + request.operation, + request.digest, + &proof, + )) + .await?; + if auth.access.authority.catalog != 13 { + return Err(OperationError::UnsupportedOperation); + } + let plan = auth.plan.as_ref().ok_or(OperationError::StaleState)?; + // Later provider capabilities cannot upgrade the retained T1 policy. + if plan.bound.plan().replay() != SigningReplay::LocalReplaySafe { + return Err(OperationError::UnsupportedOperation); + } + let intent = claim::intent(&plan.bound, request.recipient, CancellationSignal::new())?; + let (retained, witness) = Box::pin(claim::existing( + turn, + &auth, + request.operation, + request.recipient, + )) + .await?; + let retained = retained.ok_or(OperationError::StaleState)?; + if intent.binding() != retained.report.binding() { + return Err(OperationError::RecoveryRequired); + } + let at = auth.access.current.observed_at(); + acceptance::check_consent(&auth.access, &auth.consent, &auth.command, true, at)?; + if at < plan.bound.bound_at() + || at < retained.report.claimed_at() + || at >= plan.bound.preparation().first_issue_deadline() + { + return Err(OperationError::DeadlineExceeded); + } + let order = Box::pin(order_state::signing_state( + turn, + &auth.access, + auth.original.receipt.order_id(), + request.operation, + true, + )) + .await?; + let backing = Box::pin(super::super::inventory::backing::read( + turn, + &auth.access, + auth.original.receipt.held_pools(), + )) + .await?; + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let checked: Result<UnixSeconds, OperationError> = async { + Box::pin(witness.confirm(&mut tx)).await?; + retained.confirm(&mut tx).await?; + if let Some(order) = &order { + order.confirm(&mut tx).await?; + } + for pool in &backing { + pool.confirm(&mut tx).await?; + } + let current = + Box::pin(auth.confirm(&mut tx, turn.namespace, turn.clock, &proof, true)).await?; + if current.observed_at() < at || current.observed_at() < retained.report.claimed_at() { + return Err(WorkspaceError::Unavailable.into()); + } + Ok(current.observed_at()) + } + .await; + // No write, claim, stock movement, provider call or durable result is + // manufactured by authorization. A failed rollback still fences the owner. + if tx.rollback().await.is_err() { + *turn.uncertain = true; + return Err(OperationError::RecoveryRequired); + } + Ok(StockExactReplayPermit { + report: retained.report, + at: checked?, + }) +} + +impl NativeWorkspace { + /// Authenticates current first-capable local replay rights for an existing + /// original claim. Unsupported/expired/recovery-only state dispatches nothing. + pub async fn authorize_stock_exact_replay( + &self, + request: StockClaimRequest, + proof: &AttachmentProof, + ) -> Result<StockExactReplayPermit, OperationError> { + self.worker + .authorize_stock_exact_replay( + request, + proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, + ) + .await + } +} 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 @@ -2,6 +2,8 @@ use super::*; #[path = "evidence_tests.rs"] mod evidence; +#[path = "exact_recovery_tests.rs"] +mod exact_recovery; use crate::workspace::{StockClaimOutcome, StockClaimRequest, StockSigningAttempt}; use radroots_signing::issuance::OutcomeKind; diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/exact_recovery_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/exact_recovery_tests.rs @@ -0,0 +1,524 @@ +//! Actual original-claim local recovery, current authorization and existing S/T2. +use super::*; +use crate::workspace::{ + StockEvidenceCapture, StockEvidenceOutcome, StockExactReplayPermit, StockInstallationOutcome, + StockInstallationRequest, +}; +use radroots_signing::issuance::ExactRecoveryKind; + +async fn local_ready(r: &Rig) -> StockAcceptanceReceipt { + local_ready_command(r).await.1 +} +async fn local_ready_command(r: &Rig) -> (CapturedOrderAcceptance, StockAcceptanceReceipt) { + let (command, receipt) = prepared(r).await; + let candidate = candidate_with_replay(r, &receipt, 42, SigningReplay::LocalReplaySafe).await; + let request = + StockSigningPlanRequest::new(r.binding.clone(), inventory_minimum(r).await, candidate) + .unwrap(); + let plan = bound( + r.store + .bind_stock_signing_intents(request, r.enrollment.proof()) + .await + .unwrap(), + ); + assert_eq!(plan.plan().replay(), SigningReplay::LocalReplaySafe); + (command, receipt) +} +async fn authorize( + r: &Rig, + receipt: &StockAcceptanceReceipt, + recipient: PublicKey, +) -> Result<StockExactReplayPermit, OperationError> { + r.store + .authorize_stock_exact_replay(selector(r, receipt, recipient).await, r.enrollment.proof()) + .await +} +fn call(r: &Rig, deadline: u64) -> ProviderCall { + ProviderCall::new( + r.enrollment.input().participant(), + NonZeroU64::new(deadline).unwrap(), + CancellationSignal::new(), + ) +} +fn signer() -> LocalSigner { + LocalSigner::with_clock(SecretKey::parse(&format!("{:064x}", 3)).unwrap(), || { + Ok(150000) + }) + .unwrap() +} + +#[tokio::test] +async fn original_local_claim_reopens_recovers_exact_s_and_installs_once_without_another_hold() { + let mut r = Rig::new().await; + let receipt = Box::pin(local_ready(&r)).await; + let recipient = receipt + .rumor() + .recipients() + .iter() + .copied() + .find(|key| *key != r.enrollment.input().participant()) + .unwrap(); + let StockClaimOutcome::Fresh(first) = claim(&r, &receipt, recipient).await.unwrap() else { + panic!("first claim") + }; + let original_attempt = first.report().attempt_id(); + let original_binding = first.report().binding(); + drop(first); // Actual dispatch result is unavailable; the durable claim stays. + let acknowledged = inventory_minimum(&r).await; + reopen_plain(&mut r).await; + let permitted = authorize(&r, &receipt, recipient).await.unwrap(); + assert_eq!(permitted.report().attempt_id(), original_attempt); + assert_eq!(permitted.report().binding(), original_binding); + assert_eq!(inventory_minimum(&r).await, acknowledged); + let (request, report) = permitted.into_recovery_request(call(&r, 250000)).unwrap(); + assert_eq!(request.binding(), original_binding); + let expected_event = request.original().with_event(|_, id| id); + let outcome = signer().recover_exact(request).await; + assert_eq!(outcome.binding(), original_binding); + let (_, ExactRecoveryKind::Obtained(signed)) = outcome.into_parts() else { + panic!("qualified original S") + }; + assert_eq!(signed.event_id(), expected_event); + let capture = signed + .with_json(|raw| { + StockEvidenceCapture::verify( + r.binding.clone(), + &report, + raw, + signed.observed_at_unix_ms(), + ) + }) + .unwrap(); + assert!(matches!( + r.store + .capture_stock_signing_evidence(&capture, r.enrollment.proof()) + .await + .unwrap(), + StockEvidenceOutcome::Committed(_) + )); + let request = || { + StockInstallationRequest::new( + r.binding.clone(), + acknowledged, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + ) + }; + let StockInstallationOutcome::Installed(installed) = r + .store + .install_stock_agreement(request(), r.enrollment.proof()) + .await + .unwrap() + else { + panic!("original T2") + }; + let first_install = installed.attempt(); + let current = inventory_minimum(&r).await; + let StockInstallationOutcome::Installed(again) = r + .store + .install_stock_agreement(request(), r.enrollment.proof()) + .await + .unwrap() + else { + panic!("same installation") + }; + assert_eq!(again.attempt(), first_install); + assert_eq!(inventory_minimum(&r).await, current); + let selected = r + .store + .pool( + r.binding.clone(), + current, + pool(80), + r.enrollment + .proof() + .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) + .unwrap(), + ) + .await + .unwrap() + .unwrap() + .snapshot(); + assert_eq!(selected.balances().physical().available.get(), 9); + assert_eq!(selected.balances().physical().preparatory_hold.get(), 0); + assert_eq!(selected.balances().physical().committed_hold.get(), 1); + assert!(matches!( + claim(&r, &receipt, recipient).await.unwrap(), + StockClaimOutcome::Existing(_) + )); + let installed_replay = authorize(&r, &receipt, recipient).await.unwrap(); + assert_eq!(installed_replay.report().binding(), original_binding); + assert_eq!(inventory_minimum(&r).await, current); + drop(installed_replay); + reopen_plain(&mut r).await; + let original = read(&r, &receipt, recipient).await.unwrap().unwrap(); + assert_eq!(original.attempt_id(), original_attempt); + assert_eq!(original.binding(), original_binding); + assert_eq!(inventory_minimum(&r).await, current); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn ordinary_outbox_refuses_exact_replay_without_adopting_stock_authority() { + let r = Rig::new().await; + let receipt = local_ready(&r).await; + let request = selector(&r, &receipt, receipt.rumor().recipients()[0]).await; + let (outbox, _, proof) = NativeWorkspace::initialize_local_outbox( + &r.path.with_file_name("separate-outbox"), + crate::workspace::LocalOutboxConfig::seller( + r.enrollment.input().participant(), + r.enrollment.input().participant(), + "synthetic-recovery-outbox", + UnixSeconds::new(500).unwrap(), + ) + .unwrap(), + r.fixture.crypto(), + r.clock.clone(), + ) + .await + .unwrap(); + assert_eq!( + outbox + .authorize_stock_exact_replay(request, &proof) + .await + .unwrap_err(), + OperationError::UnsupportedOperation + ); + outbox.close().await.unwrap(); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn missing_claim_nonreplayable_policy_and_original_expiry_never_mint_replay_permission() { + for mode in [0, 1, 2] { + let r = Rig::new().await; + let receipt = if mode == 1 { + ready(&r).await + } else { + local_ready(&r).await + }; + let recipient = receipt.rumor().recipients()[0]; + if mode != 0 { + assert!(matches!( + claim(&r, &receipt, recipient).await.unwrap(), + StockClaimOutcome::Fresh(_) + )); + } + let request = selector(&r, &receipt, recipient).await; + let before = inventory_minimum(&r).await; + if mode == 2 { + r.clock + .0 + .store(receipt.first_issue_deadline().get(), Ordering::SeqCst); + } + assert!( + r.store + .authorize_stock_exact_replay(request, r.enrollment.proof()) + .await + .is_err() + ); + assert_eq!(inventory_minimum(&r).await, before); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn wrong_original_digest_recipient_and_damaged_claim_or_backing_refuse_without_new_effect() { + for mode in [0, 1, 2, 3] { + let r = Rig::new().await; + let receipt = local_ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + assert!(matches!( + claim(&r, &receipt, recipient).await.unwrap(), + StockClaimOutcome::Fresh(_) + )); + let request = StockClaimRequest::new( + r.binding.clone(), + inventory_minimum(&r).await, + receipt.attempt().operation_id(), + if mode == 0 { + radroots_domain::CommandDigest::from_bytes([99; 32]) + } else { + receipt.attempt().command_digest() + }, + if mode == 1 { + (4..=6) + .map(|value| { + LocalSigner::with_clock( + SecretKey::parse(&format!("{value:064x}")).unwrap(), + || Ok(150000), + ) + .unwrap() + .public_key() + }) + .find(|key| !receipt.rumor().recipients().contains(key)) + .unwrap() + } else { + recipient + }, + ); + let mut raw = database(&r).await; + if mode == 2 { + sqlx::raw_sql("UPDATE stock_pools SET protected=randomblob(length(protected))") + .execute(&mut raw) + .await + .unwrap(); + } + if mode == 3 { + sqlx::raw_sql("DELETE FROM stock_signing_claims") + .execute(&mut raw) + .await + .unwrap(); + } + assert!( + r.store + .authorize_stock_exact_replay(request, r.enrollment.proof()) + .await + .is_err() + ); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_operations WHERE family=5") + .fetch_one(&mut raw) + .await + .unwrap(); + assert_eq!(count, 0); + raw.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn replacement_recover_only_grant_reads_the_original_but_cannot_authorize_local_recomputation() + { + let r = Rig::new().await; + let (command, receipt) = local_ready_command(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let StockClaimOutcome::Fresh(first) = claim(&r, &receipt, recipient).await.unwrap() else { + panic!("first claim") + }; + let original = first.report().attempt_id(); + drop(first); + // Stay inside the original issuance window: refusal must be actual rights, + // rather than merely an already-expired original operation. + r.clock.0.store(160, Ordering::SeqCst); + let child = StockGrantEnrollment::prepare( + &SellerAuthoritySelection::from_attachment(r.enrollment.input()), + "recovery reader".into(), + UnixSeconds::new(290).unwrap(), + StockGrantScope::full_inventory(), + ) + .unwrap(); + assert!(matches!( + r.store + .enroll_stock_grant( + r.binding.clone(), + inventory_minimum(&r).await, + r.enrollment.proof(), + &child + ) + .await + .unwrap(), + StockGrantOutcome::Committed(_) + )); + let binding = r + .store + .authenticate(child.input().clone(), child.proof()) + .await + .unwrap(); + let consent = StockConsentCapture::prepare( + SellerAuthoritySelection::from_attachment(r.enrollment.input()), + child.input().grant_id(), + StockConsentMode::RecoverOnly, + StockResources::all_pools(), + UnixSeconds::new(280).unwrap(), + CapturedOrderAcceptance::parse(command.protected_wire()).unwrap(), + ) + .unwrap(); + assert!(matches!( + r.store + .issue_stock_consent( + r.binding.clone(), + inventory_minimum(&r).await, + &consent, + r.enrollment.proof() + ) + .await + .unwrap(), + StockConsentOutcome::Committed(_) + )); + let minimum = inventory_minimum(&r).await; + let request = || { + StockClaimRequest::new( + binding.clone(), + minimum, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + recipient, + ) + }; + assert_eq!( + r.store + .stock_signing_attempt(request(), child.proof()) + .await + .unwrap() + .unwrap() + .attempt_id(), + original + ); + assert_eq!( + r.store + .authorize_stock_exact_replay(request(), child.proof()) + .await + .unwrap_err(), + OperationError::Unauthorized + ); + assert_eq!(inventory_minimum(&r).await, minimum); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn replay_authorization_rechecks_actual_late_root_grant_plan_claim_backing_and_clock_changes() +{ + for statement in [ + "UPDATE stock_pools SET protected=randomblob(length(protected))", + "UPDATE stock_grants SET protected=randomblob(length(protected))", + "UPDATE stock_operations SET protected=randomblob(length(protected)) WHERE family=3", + "DELETE FROM stock_signing_claims", + "UPDATE stock_authority SET protected=randomblob(length(protected))", + "clock_expired", + "clock_rollback", + ] { + let mut r = Rig::new().await; + let receipt = local_ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + assert!(matches!( + claim(&r, &receipt, recipient).await.unwrap(), + StockClaimOutcome::Fresh(_) + )); + let request = selector(&r, &receipt, recipient).await; + let provider = reopen(&mut r).await; + let mut raw = database(&r).await; + provider + .gate + .arm(Direction::Unwrap, "radroots.seller_stock.authority.v13", 0); + let mut pending = Box::pin( + r.store + .authorize_stock_exact_replay(request, r.enrollment.proof()), + ); + assert!(futures::poll!(pending.as_mut()).is_pending()); + provider.gate.entered(); + match statement { + "clock_expired" => r + .clock + .0 + .store(receipt.first_issue_deadline().get(), Ordering::SeqCst), + "clock_rollback" => r.clock.0.store(149, Ordering::SeqCst), + _ => { + sqlx::raw_sql(statement).execute(&mut raw).await.unwrap(); + } + } + provider.gate.release(); + assert!(pending.await.is_err(), "{statement}"); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM stock_operations WHERE family=5") + .fetch_one(&mut raw) + .await + .unwrap(), + 0 + ); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM stock_operations WHERE family=4") + .fetch_one(&mut raw) + .await + .unwrap(), + 1 + ); + raw.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn observer_loss_drains_authorization_without_signing_or_a_new_claim_and_reopen_keeps_original() + { + let mut r = Rig::new().await; + let receipt = local_ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let StockClaimOutcome::Fresh(first) = claim(&r, &receipt, recipient).await.unwrap() else { + panic!("first claim") + }; + let original = first.report().attempt_id(); + drop(first); + let before = inventory_minimum(&r).await; + let request = selector(&r, &receipt, recipient).await; + let provider = reopen(&mut r).await; + provider + .gate + .arm(Direction::Unwrap, "radroots.seller_stock.authority.v13", 0); + let mut pending = Box::pin( + r.store + .authorize_stock_exact_replay(request, r.enrollment.proof()), + ); + assert!(futures::poll!(pending.as_mut()).is_pending()); + provider.gate.entered(); + drop(pending); + let mut closing = Box::pin(r.store.close()); + assert!(futures::poll!(closing.as_mut()).is_pending()); + provider.gate.release(); + closing.await.unwrap(); + reopen_plain(&mut r).await; + assert_eq!(inventory_minimum(&r).await, before); + let permitted = authorize(&r, &receipt, recipient).await.unwrap(); + assert_eq!(permitted.report().attempt_id(), original); + drop(permitted); + assert_eq!(inventory_minimum(&r).await, before); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn uncertain_original_claim_never_authorizes_replay_and_reopen_does_not_create_a_missing_claim() + { + let mut r = Rig::new().await; + let receipt = local_ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let before = inventory_minimum(&r).await; + let request = selector(&r, &receipt, recipient).await; + let mut raw = database(&r).await; + sqlx::raw_sql("CREATE TABLE deferred_fault(value INTEGER REFERENCES stock_authority(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fault AFTER INSERT ON stock_signing_claims BEGIN INSERT INTO deferred_fault VALUES(2); END").execute(&mut raw).await.unwrap(); + assert!(matches!( + r.store + .claim_stock_signing_attempt(request, r.enrollment.proof()) + .await + .unwrap(), + StockClaimOutcome::Unknown(_) + )); + let request = || { + StockClaimRequest::new( + r.binding.clone(), + before, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + recipient, + ) + }; + assert_eq!( + r.store + .authorize_stock_exact_replay(request(), r.enrollment.proof()) + .await + .unwrap_err(), + OperationError::RecoveryRequired + ); + r.store.close().await.unwrap(); + sqlx::raw_sql("DROP TRIGGER fault; DROP TABLE deferred_fault") + .execute(&mut raw) + .await + .unwrap(); + raw.close().await.unwrap(); + reopen_plain(&mut r).await; + assert!(authorize(&r, &receipt, recipient).await.is_err()); + assert_eq!(inventory_minimum(&r).await, before); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); +} diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/signing_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/signing_tests.rs @@ -22,6 +22,14 @@ async fn candidate( receipt: &StockAcceptanceReceipt, nonce: u8, ) -> VerifiedCommerceSigningPlan { + candidate_with_replay(r, receipt, nonce, SigningReplay::NonReplayable).await +} +async fn candidate_with_replay( + r: &Rig, + receipt: &StockAcceptanceReceipt, + nonce: u8, + replay: SigningReplay, +) -> VerifiedCommerceSigningPlan { let provider = LocalSigner::with_clock(SecretKey::parse(&format!("{:064x}", 3)).unwrap(), || { Ok(150000) @@ -85,7 +93,7 @@ async fn candidate( rumor, seals.try_into().unwrap(), routes.try_into().unwrap(), - SigningReplay::NonReplayable, + replay, ) .unwrap(); VerifiedCommerceSigningPlan::verify(&provider, call(), rumor, plan) diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -85,6 +85,11 @@ enum Job { AttachmentProof, Reply<stock::StockClaimOutcome, OperationError>, ), + AuthorizeStockExactReplay( + Box<stock::StockClaimRequest>, + AttachmentProof, + Reply<stock::StockExactReplayPermit, OperationError>, + ), StockSigningAttempt( Box<stock::StockClaimRequest>, AttachmentProof, @@ -333,6 +338,9 @@ impl Job { Self::ClaimStockSigning(_, _, reply) => { let _ = reply.send(Err(OperationError::RecoveryRequired)); } + Self::AuthorizeStockExactReplay(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } Self::StockSigningAttempt(_, _, reply) => { let _ = reply.send(Err(OperationError::RecoveryRequired)); } @@ -595,6 +603,7 @@ impl Handle { | Job::StockSigningPlan(..) | Job::ClaimStockSigning(..) | Job::StockSigningAttempt(..) + | Job::AuthorizeStockExactReplay(..) | Job::CaptureStockEvidence(..) | Job::StockEvidence(..) | Job::StockEvidencePage(..) @@ -1001,6 +1010,26 @@ impl Handle { }; let _ = reply.send(result); } + Job::AuthorizeStockExactReplay(request, proof, reply) => { + let result = if kind == Kind::SellerStock { + Box::pin(stock::issuance::recovery::authorize( + &mut stock::inventory::Turn { + connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + } Job::StockSigningAttempt(request, proof, reply) => { let result = if kind == Kind::SellerStock { Box::pin(stock::issuance::claim::read( @@ -1807,6 +1836,19 @@ impl Handle { self.send(Job::ClaimStockSigning(Box::new(request), proof, reply))?; result.await.unwrap_or(Ok(unknown)) } + pub(super) async fn authorize_stock_exact_replay( + &self, + request: stock::StockClaimRequest, + proof: AttachmentProof, + ) -> Result<stock::StockExactReplayPermit, OperationError> { + let (reply, result) = oneshot::channel(); + self.send(Job::AuthorizeStockExactReplay( + Box::new(request), + proof, + reply, + ))?; + result.await.map_err(|_| OperationError::RecoveryRequired)? + } pub(super) async fn stock_signing_attempt( &self, request: stock::StockClaimRequest, @@ -1956,7 +1998,8 @@ impl Handle { Job::BindStockSigningPlan(..) | Job::StockSigningPlan(..) | Job::ClaimStockSigning(..) - | Job::StockSigningAttempt(..) => 1024 * 1024, + | Job::StockSigningAttempt(..) + | Job::AuthorizeStockExactReplay(..) => 1024 * 1024, Job::RetainStockSource(..) => 256 * 1024, Job::ChangeStockGrant(..) | Job::ExecuteInventory(..) => 64 * 1024, Job::CaptureDeliveryObservation(..) => 96 * 1024, diff --git a/tools/xtask/src/architecture/api_leakage.rs b/tools/xtask/src/architecture/api_leakage.rs @@ -629,6 +629,7 @@ fn collect_module( if units.contains_key(&module) { return Ok(()); } + let inside_inline_module = inline_items.is_some(); let (items, source_relative) = if let Some(items) = inline_items { let relative = source_path .strip_prefix(package_root) @@ -685,6 +686,14 @@ fn collect_module( child_module.push(child.ident.to_string()); let child_public = is_public(&child.vis); let child_effective = initially_effective && child_public; + let attribute_base = if inside_inline_module { + module_directory + } else { + source_path.parent().unwrap_or_else(|| Path::new(".")) + }; + let child_directory = path_attribute(&child) + .map(|path| attribute_base.join(path)) + .unwrap_or_else(|| module_directory.join(child.ident.to_string())); if let Some((_, inline)) = child.content { collect_module( package_root, @@ -693,12 +702,12 @@ fn collect_module( child_public, child_effective, source_path, - &module_directory.join(child.ident.to_string()), + &child_directory, Some(inline), units, )?; } else { - let child_path = module_source_path(source_path, module_directory, &child)?; + let child_path = module_source_path(attribute_base, module_directory, &child)?; collect_module( package_root, child_module, @@ -706,7 +715,7 @@ fn collect_module( child_public, child_effective, &child_path, - &module_directory.join(child.ident.to_string()), + &self::module_directory(&child_path)?, None, units, )?; @@ -732,15 +741,12 @@ fn module_directory(source_path: &Path) -> Result<PathBuf, String> { } fn module_source_path( - source_path: &Path, + attribute_base: &Path, module_directory: &Path, item_mod: &syn::ItemMod, ) -> Result<PathBuf, String> { if let Some(path) = path_attribute(item_mod) { - return Ok(source_path - .parent() - .unwrap_or_else(|| Path::new(".")) - .join(path)); + return Ok(attribute_base.join(path)); } let name = item_mod.ident.to_string(); let flat = module_directory.join(format!("{name}.rs")); @@ -1456,6 +1462,69 @@ mod tests { .expect("scan fixture") } + #[test] + fn path_attributes_follow_physical_files_and_inline_module_directories() { + // Rust Reference items.mod.outlined.path: inline paths include their + // module directories; a redirected file owns its physical child path. + for (source, branch, leaf) in [ + ( + "pub mod branch;", + Some(( + "src/branch.rs", + "pub mod inline { #[path = \"leaf.rs\"] pub mod leaf; }", + )), + "src/branch/inline/leaf.rs", + ), + ( + "pub mod branch;", + Some(( + "src/branch/mod.rs", + "pub mod inline { #[path = \"leaf.rs\"] pub mod leaf; }", + )), + "src/branch/inline/leaf.rs", + ), + ( + "pub mod outer { pub mod inner { #[path = \"leaf.rs\"] pub mod leaf; } }", + None, + "src/outer/inner/leaf.rs", + ), + ( + "#[path = \"thread_files\"] pub mod thread { #[path = \"leaf.rs\"] pub mod leaf; }", + None, + "src/thread_files/leaf.rs", + ), + ( + "#[path = \"redirect/payload.rs\"] pub mod branch;", + Some(("src/redirect/payload.rs", "pub mod leaf;")), + "src/redirect/payload/leaf.rs", + ), + ] { + let root = tempfile::TempDir::new().unwrap(); + let package = "radroots_signing"; + let metadata = fixture_metadata(root.path(), package, source); + let base = root.path().join(package); + if let Some((name, body)) = branch { + let path = base.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, body).unwrap(); + } + let path = base.join(leaf); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write( + path, + "pub fn exposed() -> tokio::runtime::Runtime { todo!() }", + ) + .unwrap(); + let findings = scan_workspace(root.path(), &policy(), &metadata).unwrap(); + assert!( + findings + .iter() + .any(|finding| finding.source == leaf && finding.forbidden_path == "tokio"), + "{leaf}: {findings:?}" + ); + } + } + fn write_baseline_decision(root: &std::path::Path) { fs::create_dir_all(root.join("contracts/architecture/decisions")) .expect("baseline decision directory"); diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -103,6 +103,7 @@ struct StockCapabilityContract { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct NativeSellerStockAuthority { + qualified_local_recovery: QualifiedLocalRecovery, source_payload_schemas: Vec<String>, source_profile_dispositions: Vec<String>, source_owner_administration_required: bool, @@ -216,6 +217,27 @@ struct AcceptancePreparation { #[derive(Deserialize)] #[serde(deny_unknown_fields)] +struct QualifiedLocalRecovery { + provider_method: String, + adapter: String, + native_authorizer: String, + captured_replay: String, + native_catalog: u16, + worker_charge_bytes: u32, + existing_protected_claim_required: bool, + current_execute_consent_required: bool, + original_window_required: bool, + call_budget_extends_original_window: bool, + recovery_refusal_proves_original_unissued: bool, + creates_claim_or_stock_effect: bool, + provider_work_inside_sql: bool, + unsupported_legacy_fallback: bool, + after_expiry_retrieval_available: bool, + legacy_and_first_dispatch_unchanged: bool, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] struct PreparationAbort { shared_storage_port: String, shared_model_owner: String, @@ -590,6 +612,36 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { .signing_issuance .capture_retains_distinct_valid_encodings && !stock.signing_issuance.agreement_installed + && stock.qualified_local_recovery.provider_method + == "radroots_signing.provider.ParticipantProvider.recover_exact" + && stock.qualified_local_recovery.adapter == "radroots_nostr.signing.LocalSigner" + && stock.qualified_local_recovery.native_authorizer + == "NativeWorkspace.authorize_stock_exact_replay" + && stock.qualified_local_recovery.captured_replay == "local_replay_safe" + && stock.qualified_local_recovery.native_catalog == 13 + && stock.qualified_local_recovery.worker_charge_bytes == 1048576 + && stock + .qualified_local_recovery + .existing_protected_claim_required + && stock + .qualified_local_recovery + .current_execute_consent_required + && stock.qualified_local_recovery.original_window_required + && !stock + .qualified_local_recovery + .call_budget_extends_original_window + && !stock + .qualified_local_recovery + .recovery_refusal_proves_original_unissued + && !stock.qualified_local_recovery.creates_claim_or_stock_effect + && !stock.qualified_local_recovery.provider_work_inside_sql + && !stock.qualified_local_recovery.unsupported_legacy_fallback + && !stock + .qualified_local_recovery + .after_expiry_retrieval_available + && stock + .qualified_local_recovery + .legacy_and_first_dispatch_unchanged && stock.preparation_abort.payload_version == 1 && stock.preparation_abort.journal_family == 7 && stock.preparation_abort.worker_charge_bytes == 1048576 @@ -1401,6 +1453,37 @@ mod tests { } #[test] + fn qualified_local_recovery_keeps_original_policy_window_and_current_rights() { + for (field, bad) in [ + ("provider_method", json!("sign_exact")), + ("adapter", json!("legacy_signer")), + ("native_authorizer", json!("caller_assertion")), + ("captured_replay", json!("non_replayable")), + ("native_catalog", json!(12)), + ("worker_charge_bytes", json!(1048577)), + ("existing_protected_claim_required", json!(false)), + ("current_execute_consent_required", json!(false)), + ("original_window_required", json!(false)), + ("call_budget_extends_original_window", json!(true)), + ("recovery_refusal_proves_original_unissued", json!(true)), + ("creates_claim_or_stock_effect", json!(true)), + ("provider_work_inside_sql", json!(true)), + ("unsupported_legacy_fallback", json!(true)), + ("after_expiry_retrieval_available", json!(true)), + ("legacy_and_first_dispatch_unchanged", json!(false)), + ] { + assert!( + validate_bytes(&changed( + &format!("/native_seller_stock_authority/qualified_local_recovery/{field}"), + bad + )) + .is_err(), + "{field}" + ); + } + } + + #[test] fn public_sources_require_original_signatures_bounded_parts_and_profile_independent_heads() { for (field, bad) in [ ("schema_version", json!(7)),