lib

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

commit 29dc4922ba07ff786b3dd279415a85e59dd1c001
parent 1d7f34d6c7390592f9001fe843115536bf4da76e
Author: triesap <tyson@radroots.org>
Date:   Sat, 17 Oct 2026 16:43:11 +0000

execution: own scoped signer callbacks through observation and close

- Pair participant providers with explicit target-local callback ownership.
- Freeze observed identity and latch drift across shared signer sessions.
- Drain observations and resume callback disposal before releasing roots.
- Verify native lifetimes, portable targets, public APIs and coverage gates.

Diffstat:
MCargo.lock | 2++
Mcontracts/api_baselines/radroots_execution.txt | 10++++++++++
Mcontracts/api_baselines/radroots_signing.txt | 7+++++++
Mcontracts/architecture/deviations.toml | 27+++++++++++++++++++++++++++
Mcontracts/coverage-profiles.toml | 2+-
Mcontracts/crates/catalog.v2.toml | 2+-
Mcontracts/crates/generated/package_groups.v1.toml | 2+-
Mcontracts/crates/generated/platform_inventory.v1.toml | 2+-
Mcontracts/crates/generated/release_inventory.v2.toml | 2+-
Acontracts/execution/signer_session.v1.json | 28++++++++++++++++++++++++++++
Mcrates/execution/Cargo.toml | 3+++
Mcrates/execution/README.md | 8++++++++
Mcrates/execution/src/error.rs | 13+++++++++++++
Mcrates/execution/src/session/mod.rs | 6++++++
Acrates/execution/src/session/signer.rs | 198+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/execution/tests/signer_session.rs | 375+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/signing/README.md | 6++++++
Mcrates/signing/src/provider.rs | 49++++++++++++++++++++++++++++++++++++++++++++++++-
Mcrates/signing/tests/package_boundary.rs | 3++-
19 files changed, 738 insertions(+), 7 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock @@ -3157,6 +3157,8 @@ version = "0.1.0-alpha" dependencies = [ "futures", "radroots_domain", + "radroots_identity", + "radroots_signing", ] [[package]] diff --git a/contracts/api_baselines/radroots_execution.txt b/contracts/api_baselines/radroots_execution.txt @@ -15,6 +15,16 @@ pub async fn radroots_execution::session::Session<H>::start(&self) -> radroots_e pub fn radroots_execution::session::Session<H>::state(&self) -> radroots_execution::session::SessionState impl<H: radroots_execution::session::SessionHost> core::clone::Clone for radroots_execution::session::Session<H> pub fn radroots_execution::session::Session<H>::clone(&self) -> Self +pub struct radroots_execution::session::SignerSession +impl radroots_execution::session::SignerSession +pub async fn radroots_execution::session::SignerSession::close(&self) -> radroots_execution::Result<()> +pub fn radroots_execution::session::SignerSession::identity_changed(&self) -> bool +pub fn radroots_execution::session::SignerSession::new(radroots_signing::provider::SignerHandle) -> Self +pub async fn radroots_execution::session::SignerSession::observe(&self) -> core::result::Result<radroots_signing::provider::ProviderState, radroots_signing::provider::ProviderError> +pub fn radroots_execution::session::SignerSession::observed(&self) -> core::option::Option<radroots_signing::provider::ProviderState> +pub fn radroots_execution::session::SignerSession::state(&self) -> radroots_execution::session::SessionState +impl core::clone::Clone for radroots_execution::session::SignerSession +pub fn radroots_execution::session::SignerSession::clone(&self) -> Self 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 @@ -189,6 +189,10 @@ pub const fn radroots_signing::provider::ProviderState::encryption(self) -> radr 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 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>) +pub fn radroots_signing::provider::SignerHandle::new(radroots_signing::host::Shared<dyn radroots_signing::provider::ParticipantProvider>, radroots_signing::host::Shared<dyn radroots_signing::provider::SignerCallbacks>) -> Self pub const radroots_signing::provider::PRIVATE_CRYPTO_MAX_BYTES: usize pub trait radroots_signing::provider::NonceSource: radroots_signing::host::HostBound pub fn radroots_signing::provider::NonceSource::next_nonce(&self) -> core::result::Result<[u8; 32], radroots_signing::provider::ProviderError> @@ -196,6 +200,9 @@ 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 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>> +pub fn radroots_signing::provider::SignerCallbacks::quiesce(&self) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<(), radroots_signing::provider::ProviderError>> pub mod radroots_signing::receipt #[non_exhaustive] pub struct radroots_signing::receipt::AuthoredSignEvidence impl radroots_signing::receipt::AuthoredSignEvidence diff --git a/contracts/architecture/deviations.toml b/contracts/architecture/deviations.toml @@ -2,6 +2,33 @@ schema_version = 1 architecture_id = "radroots.crates.release.v1" [[deviation]] +id = "RCRV1-DEV-050" +date = "2026-10-17" +status = "closed" +approval = "The user authorizes the complete approved shared SDK refactor and verified source checkpoints with necessary breaking changes and source publication." +affected_steps = ["040", "060", "110", "120", "130"] +spec_anchors = ["contracts/crates/release_v1/radroots_crates_release_v1.toml#package.radroots_signing"] +source_evidence = [ + "Client.attach_signer requires an identity observation bound to a revocable host handle. The current participant provider performs identity/private-crypto effects but has no session-owned callback teardown boundary.", + "The existing execution session already qualifies bounded resource admission, pending-start interruption, draining and resumable ordered callback disposal. Reuse that owner for signer attachment instead of implementing a second lifecycle engine or treating identity as workspace authorization.", +] +replacement_action = "Implement an owned opaque signer handle and scoped signer session using the existing execution session. Freeze the first observed key, reject later identity drift, retain provider/callback roots during admitted observations, stop new admission before disposal and resume interrupted or failed callback closure. Keep the actual NativeConfig Client, authenticated workspace/context and durable commands as distinct obligations; no observed key grants a role or stock authority." +verification = [ + "Validate the prospective deviation before implementation. Prove construction is inert, actual provider observation is invoked, identity drift is rejected, callback close waits for admitted observations, and interrupted or failed disposal resumes without releasing roots early.", + "Prove native thread bounds and WASM local host composition, generated API freshness, unchanged measured coverage policy and owning catalog/architecture/contracts. Bind actual native-provider integration when consumed by the facade.", +] +unresolved_risk = "This component alone does not open a native Client, authenticate a workspace, qualify external callback hosts or execute durable listing/chat work. Concrete host, browser/binding and complete operation qualification remain required." +normative_architecture_change = false +adr_required = false +closure_evidence = [ + "Six native callback-scope cases execute inert construction, actual observation, latched identity drift, bounded concurrent observation, root retention/release, failed/cancelled disposal and lost-observer cleanup. The existing session coordinator remains the lifecycle owner.", + "Native all-feature caller compilation, signing/execution tests and doctests pass. Strict lint exposed an equivalent nested comparison; the preserved failure is corrected with a Rust2024 let-chain and the affected execution check/tests/lint pass.", + "Rc-local WASM all-target composition, signing WASM and execution no_std bare-metal compilation pass. Owner-generated signing/execution public API baselines and catalog/architecture/contract/API/dependency boundaries pass.", + "Actual session-enabled execution and signing coverage pass the unchanged ninety-percent line/function/region/branch policy. Concrete NativeConfig Client/provider composition, platform/browser runtime hosts, authenticated context, durable jobs, bindings and final acceptance remain separate obligations.", +] + + +[[deviation]] id = "RCRV1-DEV-049" date = "2026-10-17" status = "closed" diff --git a/contracts/coverage-profiles.toml b/contracts/coverage-profiles.toml @@ -5,7 +5,7 @@ test_threads = 1 [profiles.crates."radroots_execution"] no_default_features = false -features = ["session"] +features = ["session", "signer_session"] test_threads = 1 [profiles.crates."radroots_log"] diff --git a/contracts/crates/catalog.v2.toml b/contracts/crates/catalog.v2.toml @@ -90,7 +90,7 @@ license = "MIT OR Apache-2.0" platforms = ["any"] groups = ["coverage_required", "portable", "public_native"] owners = ["execution"] -permitted_dependency_tiers = ["domain"] +permitted_dependency_tiers = ["domain", "foundation", "spi"] provenance_kind = "native" introduction_tree_sha256 = "c3513293d70957c4ee2c93a722549573a8dc1bc9e893873a4f3e2dfdaa2881da" compatibility = ["rust_api", "features", "package"] diff --git a/contracts/crates/generated/package_groups.v1.toml b/contracts/crates/generated/package_groups.v1.toml @@ -1,5 +1,5 @@ schema = "radroots.workspace.package-groups.v1" -catalog_sha256 = "9c347e831bada40bd91e691aad9df2ba2573dc0ed1c76083939f47863f286d2c" +catalog_sha256 = "b405314962f9fe5212288580d6376d4af51af0d731f90ae417576a9e8b55c4e3" [[group]] id = "boundaries" diff --git a/contracts/crates/generated/platform_inventory.v1.toml b/contracts/crates/generated/platform_inventory.v1.toml @@ -1,5 +1,5 @@ schema = "radroots.workspace.platform-inventory.v1" -catalog_sha256 = "9c347e831bada40bd91e691aad9df2ba2573dc0ed1c76083939f47863f286d2c" +catalog_sha256 = "b405314962f9fe5212288580d6376d4af51af0d731f90ae417576a9e8b55c4e3" [[platform]] id = "any" diff --git a/contracts/crates/generated/release_inventory.v2.toml b/contracts/crates/generated/release_inventory.v2.toml @@ -1,5 +1,5 @@ schema = "radroots.workspace.release-inventory.v2" -catalog_sha256 = "9c347e831bada40bd91e691aad9df2ba2573dc0ed1c76083939f47863f286d2c" +catalog_sha256 = "b405314962f9fe5212288580d6376d4af51af0d731f90ae417576a9e8b55c4e3" architecture = "radroots.crates.release.v2" version = "0.1.0-alpha" public_packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_domain", "radroots_event", "radroots_event_codec", "radroots_execution", "radroots_geonames", "radroots_identity", "radroots_nostr", "radroots_nostr_connect", "radroots_protocol", "radroots_sdk", "radroots_secrets", "radroots_signing", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_trade", "radroots_transport", "radroots_transport_nostr"] diff --git a/contracts/execution/signer_session.v1.json b/contracts/execution/signer_session.v1.json @@ -0,0 +1,28 @@ +{ + "schema": "radroots.execution.signer_session.v1", + "state": "component_qualified_native_and_compile_only_wasm", + "feature": "signer_session", + "construction": "Own provider and its exact host callback scope without invoking either", + "first_observation": "Owning Client retains the scope before awaiting actual provider identity observation", + "identity": "First successful key is frozen; identity drift is latched until explicit replacement, even if the original key returns", + "capabilities": "Method observations may change for the same key; cached values grant no command, stock, replay or qualification authority", + "concurrent_observations": 1, + "close": [ + "Stop new resource admission", + "Quiesce host dispatch and unblock pending identity observations safely", + "Drain admitted Rust observations", + "Await resumable callback disposal", + "Release owned provider and callback roots outside bookkeeping locks" + ], + "lifecycle_owner": "Existing execution Session coordinator; no second engine, hidden runtime or Drop completion claim", + "host_contract": "Callback quiesce/close must own actual platform dispatch, retain partial progress and handle callbacks whose Rust observer was dropped", + "native": "Thread-safe handles and Send futures", + "browser": "Local Rc handles and futures; compile checks do not qualify browser runtime behavior", + "remaining": [ + "Actual NativeConfig Client resource opening and attachment composition", + "Authenticated workspace and captured command context", + "Durable commands and obtained-result retention", + "Concrete platform/browser callback host qualification", + "Generated bindings and final acceptance" + ] +} diff --git a/crates/execution/Cargo.toml b/crates/execution/Cargo.toml @@ -15,13 +15,16 @@ include = ["src/**", "tests/**", "Cargo.toml", "README.md", "LICENSE-APACHE", "L [features] default = [] session = ["dep:futures"] +signer_session = ["session", "dep:radroots_signing"] [dependencies] radroots_domain = { workspace = true, default-features = false } futures = { workspace = true, optional = true } +radroots_signing = { workspace = true, default-features = false, optional = true } [dev-dependencies] futures = { workspace = true } +radroots_identity = { workspace = true, default-features = false } [lints] workspace = true diff --git a/crates/execution/README.md b/crates/execution/README.md @@ -8,6 +8,14 @@ The optional `session` feature adds host resource ownership without creating an async runtime or detached tasks. Native handles and futures are thread safe; WASM handles use `Rc` and accept thread-local host futures. +The optional `signer_session` feature owns a provider together with its scoped +host callbacks. Construction is inert. Explicit observation freezes the first +participant key and rejects later identity drift; cached capabilities supply +no workspace grant or stock authority. Close stops admission, quiesces callback +dispatch, drains observations, awaits host disposal and releases roots. Failed +or cancelled disposal must be resumed. The Client must retain this scope before +awaiting first observation, including when attachment fails or loses its waiter. + A proposed operation ID is not durable admission. Unknown signing or commit outcomes keep the original identity and require exact-operation continuation or manual reconciliation. Uncertain initial admission remains explicitly diff --git a/crates/execution/src/error.rs b/crates/execution/src/error.rs @@ -191,6 +191,19 @@ pub struct Error { } impl Error { + #[cfg(feature = "signer_session")] + pub(crate) const fn signer_unavailable() -> Self { + Self { + code: Code::SignerUnavailable, + context: OperationContext::proposed(None), + retry: RetryClass::Never, + detail: Some(Detail::new( + crate::Field::Signer, + crate::Reason::Unavailable, + )), + } + } + #[cfg(feature = "session")] pub(crate) const fn session_unavailable(reason: crate::Reason) -> Self { Self { diff --git a/crates/execution/src/session/mod.rs b/crates/execution/src/session/mod.rs @@ -6,6 +6,12 @@ mod host; +#[cfg(feature = "signer_session")] +mod signer; + +#[cfg(feature = "signer_session")] +pub use signer::SignerSession; + pub use host::{HostBound, HostFuture, SessionHost}; use core::{ diff --git a/crates/execution/src/session/signer.rs b/crates/execution/src/session/signer.rs @@ -0,0 +1,198 @@ +use core::num::NonZeroU16; +use radroots_signing::provider::{ + ParticipantProvider, ProviderError, ProviderState, SignerCallbacks, SignerHandle, +}; +use std::{ + boxed::Box, + sync::{Mutex, MutexGuard}, +}; + +use super::{HostFuture, Session, SessionHost, SessionState, host::Shared}; + +struct Binding { + provider: Shared<dyn ParticipantProvider>, + callbacks: Shared<dyn SignerCallbacks>, +} + +impl Binding { + fn shared_copy(&self) -> Self { + Self { + provider: self.provider.clone(), + callbacks: self.callbacks.clone(), + } + } +} + +struct ResourceInner { + binding: Mutex<Option<Binding>>, + observed: Mutex<Observation>, +} + +#[derive(Clone, Copy)] +enum Observation { + None, + Current(ProviderState), + IdentityChanged(ProviderState), +} + +impl ResourceInner { + fn binding(&self) -> MutexGuard<'_, Option<Binding>> { + self.binding + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + fn observed(&self) -> MutexGuard<'_, Observation> { + self.observed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + fn retain_binding(&self) -> Option<Binding> { + self.binding().as_ref().map(Binding::shared_copy) + } +} + +struct Resources(Shared<ResourceInner>); + +impl SessionHost for Resources { + fn start(&self) -> HostFuture<'_, crate::Result<()>> { + // This scope owns callbacks, not workers or a transport connection. + Box::pin(async { Ok(()) }) + } + + fn quiesce(&self) -> HostFuture<'_, crate::Result<()>> { + Box::pin(async move { + let binding = self.0.retain_binding(); + if let Some(binding) = binding { + binding + .callbacks + .quiesce() + .await + .map_err(|_| crate::Error::signer_unavailable())?; + } + Ok(()) + }) + } + + fn disconnect(&self) -> HostFuture<'_, crate::Result<()>> { + Box::pin(async { Ok(()) }) + } + + fn dispose_callbacks(&self) -> HostFuture<'_, crate::Result<()>> { + Box::pin(async move { + let binding = self.0.retain_binding(); + if let Some(binding) = binding { + binding + .callbacks + .close() + .await + .map_err(|_| crate::Error::signer_unavailable())?; + let retired = { self.0.binding().take() }; + // Host-owned destructors and callback code never run under + // our bookkeeping mutex, including after successful closure. + drop(retired); + } + Ok(()) + }) + } + + fn close_storage(&self) -> HostFuture<'_, crate::Result<()>> { + Box::pin(async { Ok(()) }) + } +} + +/// A revocable provider observation scope with one frozen participant identity. +/// +/// It supplies no workspace grant, command context, stock authority or provider +/// qualification. The owning Client must retain this scope before awaiting its +/// first observation so cancellation cannot lose callback cleanup ownership. +pub struct SignerSession { + resources: Shared<ResourceInner>, + session: Session<Resources>, +} + +impl Clone for SignerSession { + fn clone(&self) -> Self { + Self { + resources: self.resources.clone(), + session: self.session.clone(), + } + } +} + +impl SignerSession { + /// Owns the handle without invoking it. Observations serialize through a + /// single admitted resource permit; excess concurrent observations refuse. + pub fn new(handle: SignerHandle) -> Self { + let (provider, callbacks) = handle.into_parts(); + let resources = Shared::new(ResourceInner { + binding: Mutex::new(Some(Binding { + provider, + callbacks, + })), + observed: Mutex::new(Observation::None), + }); + Self { + session: Session::new(Resources(resources.clone()), NonZeroU16::MIN), + resources, + } + } + + /// Returns resource state without invoking a provider or claiming authority. + pub fn state(&self) -> SessionState { + self.session.state() + } + + /// Returns the last identity-bound observation. Cached capabilities may be + /// stale and never authorize a later effect or override retained uncertainty. + pub fn observed(&self) -> Option<ProviderState> { + match *self.resources.observed() { + Observation::None => None, + Observation::Current(state) | Observation::IdentityChanged(state) => Some(state), + } + } + + /// Reports a latched identity change. Returning to the original key does + /// not reauthorize this scope; explicit replacement is required. + pub fn identity_changed(&self) -> bool { + matches!(*self.resources.observed(), Observation::IdentityChanged(_)) + } + + /// Invokes the actual provider and freezes its first successfully observed + /// key. Later capability changes may be observed; another key is refused. + pub async fn observe(&self) -> Result<ProviderState, ProviderError> { + self.session + .start() + .await + .map_err(|_| ProviderError::CapabilityUnavailable)?; + let _permit = self + .session + .admit() + .map_err(|_| ProviderError::CapabilityUnavailable)?; + if self.identity_changed() { + return Err(ProviderError::IdentityChanged); + } + let binding = self + .resources + .retain_binding() + .ok_or(ProviderError::CapabilityUnavailable)?; + let current = binding.provider.provider_state().await?; + let mut observed = self.resources.observed(); + if let Observation::Current(old) = *observed + && old.identity() != current.identity() + { + *observed = Observation::IdentityChanged(old); + return Err(ProviderError::IdentityChanged); + } + *observed = Observation::Current(current); + Ok(current) + } + + /// Permanently stops observation admission, drains admitted observations, + /// revokes/drains host callbacks and releases provider roots. Failed or + /// cancelled close retains its unfinished stage and must be resumed. + pub async fn close(&self) -> crate::Result<()> { + self.session.close().await + } +} diff --git a/crates/execution/tests/signer_session.rs b/crates/execution/tests/signer_session.rs @@ -0,0 +1,375 @@ +#![cfg(feature = "signer_session")] + +use core::task::Poll; +#[cfg(not(target_arch = "wasm32"))] +use core::{future::Future, pin::pin, task::Context}; +#[cfg(not(target_arch = "wasm32"))] +use futures::task::noop_waker_ref; +use futures::{channel::oneshot, executor::block_on, task::AtomicWaker}; +use radroots_execution::session::{SessionState, SignerSession}; +use radroots_identity::PublicKey; +use radroots_signing::host::Shared; +use radroots_signing::{ + SignReceipt, SignRequest, Signer, SignerStatus, + provider::{ + ParticipantProvider, PrivateCiphertext, PrivateCryptoCapability, PrivateText, ProviderCall, + ProviderError, ProviderState, SignerCallbacks, SignerHandle, + }, + recovery::ReplayCapability, + signer::BoxFuture, +}; +use std::sync::{ + Mutex, + atomic::{AtomicBool, AtomicUsize, Ordering}, +}; + +fn key(second: bool) -> PublicKey { + PublicKey::from_hex(if second { + "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5" + } else { + "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" + }) + .unwrap() +} + +fn state(second: bool, encrypt: bool) -> ProviderState { + ProviderState::new( + key(second), + if encrypt { + PrivateCryptoCapability::Nip44V2 + } else { + PrivateCryptoCapability::Unavailable + }, + PrivateCryptoCapability::Nip44V2, + ReplayCapability::NonReplayable, + ) +} + +struct Control { + current: Mutex<ProviderState>, + calls: AtomicUsize, + response: Mutex<Option<oneshot::Receiver<()>>>, + quiesces: AtomicUsize, + quiesced: AtomicBool, + close_attempts: AtomicUsize, + closes: AtomicUsize, + close_ready: AtomicBool, + fail_close_once: AtomicBool, + wake: AtomicWaker, + #[cfg(target_arch = "wasm32")] + _local: std::rc::Rc<std::cell::Cell<u8>>, +} + +struct Provider(Shared<Control>); +struct Callbacks(Shared<Control>); + +impl Signer for Provider { + fn status(&self) -> BoxFuture<'_, Result<SignerStatus, radroots_signing::Error>> { + Box::pin(async { Ok(SignerStatus::unavailable()) }) + } + fn sign(&self, _: SignRequest) -> BoxFuture<'_, Result<SignReceipt, radroots_signing::Error>> { + Box::pin(async { + Err(radroots_signing::Error::new( + radroots_signing::error::Kind::SignerUnavailable, + )) + }) + } +} + +impl ParticipantProvider for Provider { + fn provider_state(&self) -> BoxFuture<'_, Result<ProviderState, ProviderError>> { + Box::pin(async move { + self.0.calls.fetch_add(1, Ordering::SeqCst); + let response = self.0.response.lock().unwrap().take(); + if let Some(response) = response { + response.await.map_err(|_| ProviderError::Cancelled)?; + } + if self.0.quiesced.load(Ordering::SeqCst) { + return Err(ProviderError::Cancelled); + } + Ok(*self.0.current.lock().unwrap()) + }) + } + fn encrypt_private( + &self, + _: ProviderCall, + _: PublicKey, + _: PrivateText, + ) -> BoxFuture<'_, Result<PrivateCiphertext, ProviderError>> { + Box::pin(async { Err(ProviderError::CapabilityUnavailable) }) + } + fn decrypt_private( + &self, + _: ProviderCall, + _: PublicKey, + _: PrivateCiphertext, + ) -> BoxFuture<'_, Result<PrivateText, ProviderError>> { + Box::pin(async { Err(ProviderError::CapabilityUnavailable) }) + } +} + +impl SignerCallbacks for Callbacks { + fn quiesce(&self) -> BoxFuture<'_, Result<(), ProviderError>> { + Box::pin(async move { + self.0.quiesces.fetch_add(1, Ordering::SeqCst); + self.0.quiesced.store(true, Ordering::SeqCst); + Ok(()) + }) + } + fn close(&self) -> BoxFuture<'_, Result<(), ProviderError>> { + Box::pin(async move { + self.0.close_attempts.fetch_add(1, Ordering::SeqCst); + if self.0.fail_close_once.swap(false, Ordering::SeqCst) { + return Err(ProviderError::CapabilityUnavailable); + } + core::future::poll_fn(|cx| { + self.0.wake.register(cx.waker()); + if self.0.close_ready.load(Ordering::SeqCst) { + Poll::Ready(()) + } else { + Poll::Pending + } + }) + .await; + self.0.closes.fetch_add(1, Ordering::SeqCst); + Ok(()) + }) + } +} + +#[cfg(not(target_arch = "wasm32"))] +struct Fixture { + session: SignerSession, + control: Shared<Control>, + provider: std::sync::Weak<Provider>, + callbacks: std::sync::Weak<Callbacks>, +} + +#[cfg(not(target_arch = "wasm32"))] +fn scope() -> Fixture { + // Native weak handles make root release independently observable. + let control = control(); + let provider = Shared::new(Provider(control.clone())); + let callbacks = Shared::new(Callbacks(control.clone())); + let weak_provider = Shared::downgrade(&provider); + let weak_callbacks = Shared::downgrade(&callbacks); + Fixture { + session: SignerSession::new(SignerHandle::new(provider, callbacks)), + control, + provider: weak_provider, + callbacks: weak_callbacks, + } +} + +fn control() -> Shared<Control> { + Shared::new(Control { + current: Mutex::new(state(false, false)), + calls: AtomicUsize::new(0), + response: Mutex::new(None), + quiesces: AtomicUsize::new(0), + quiesced: AtomicBool::new(false), + close_attempts: AtomicUsize::new(0), + closes: AtomicUsize::new(0), + close_ready: AtomicBool::new(true), + fail_close_once: AtomicBool::new(false), + wake: AtomicWaker::new(), + #[cfg(target_arch = "wasm32")] + _local: std::rc::Rc::new(std::cell::Cell::new(0)), + }) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn construction_is_inert_and_clones_share_identity_and_revocation() { + let Fixture { + session, + control, + provider, + callbacks, + } = scope(); + assert_eq!(session.state(), SessionState::Ready); + assert!(session.observed().is_none()); + assert_eq!(control.calls.load(Ordering::SeqCst), 0); + assert_eq!(control.quiesces.load(Ordering::SeqCst), 0); + let close = session.close(); + drop(close); + assert_eq!(session.state(), SessionState::Ready); + let clone = session.clone(); + assert_eq!(block_on(session.observe()).unwrap().identity(), key(false)); + *control.current.lock().unwrap() = state(false, true); + assert_eq!( + block_on(clone.observe()).unwrap().encryption(), + PrivateCryptoCapability::Nip44V2 + ); + *control.current.lock().unwrap() = state(true, false); + assert_eq!( + block_on(session.observe()), + Err(ProviderError::IdentityChanged) + ); + assert_eq!(session.observed().unwrap().identity(), key(false)); + assert!(session.identity_changed()); + *control.current.lock().unwrap() = state(false, false); + assert_eq!( + block_on(session.observe()), + Err(ProviderError::IdentityChanged) + ); + assert_eq!(control.calls.load(Ordering::SeqCst), 3); + block_on(clone.close()).unwrap(); + assert_eq!(session.state(), SessionState::Closed); + assert!(provider.upgrade().is_none() && callbacks.upgrade().is_none()); + assert_eq!( + block_on(session.observe()), + Err(ProviderError::CapabilityUnavailable) + ); + block_on(session.close()).unwrap(); + assert_eq!(control.quiesces.load(Ordering::SeqCst), 1); + assert_eq!(control.closes.load(Ordering::SeqCst), 1); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn close_before_observation_disposes_roots_without_querying_identity() { + let Fixture { + session, + control, + provider, + callbacks, + } = scope(); + block_on(session.close()).unwrap(); + assert_eq!(control.calls.load(Ordering::SeqCst), 0); + assert_eq!(control.quiesces.load(Ordering::SeqCst), 1); + assert_eq!(control.closes.load(Ordering::SeqCst), 1); + assert!(provider.upgrade().is_none() && callbacks.upgrade().is_none()); + assert!(session.observed().is_none()); + assert_eq!(session.state(), SessionState::Closed); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn close_quiesces_before_draining_and_retains_inflight_roots() { + let Fixture { + session, + control, + provider, + .. + } = scope(); + let (send, receive) = oneshot::channel(); + *control.response.lock().unwrap() = Some(receive); + let mut observe = pin!(session.observe()); + let mut cx = Context::from_waker(noop_waker_ref()); + assert!(observe.as_mut().poll(&mut cx).is_pending()); + assert_eq!( + block_on(session.observe()), + Err(ProviderError::CapabilityUnavailable) + ); + assert_eq!(control.calls.load(Ordering::SeqCst), 1); + let mut close = pin!(session.close()); + assert!(close.as_mut().poll(&mut cx).is_pending()); + assert_eq!(control.quiesces.load(Ordering::SeqCst), 1); + assert_eq!(control.close_attempts.load(Ordering::SeqCst), 0); + assert!(provider.upgrade().is_some()); + send.send(()).unwrap(); + assert_eq!( + observe.as_mut().poll(&mut cx), + Poll::Ready(Err(ProviderError::Cancelled)) + ); + assert!(matches!(close.as_mut().poll(&mut cx), Poll::Ready(Ok(())))); + assert!(provider.upgrade().is_none()); + assert!(session.observed().is_none()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn failed_and_cancelled_callback_disposal_keep_the_unfinished_stage() { + for fail in [false, true] { + let Fixture { + session, + control, + provider, + callbacks, + } = scope(); + block_on(session.observe()).unwrap(); + if fail { + control.fail_close_once.store(true, Ordering::SeqCst); + assert!(block_on(session.close()).is_err()); + } else { + control.close_ready.store(false, Ordering::SeqCst); + let mut close = Box::pin(session.close()); + assert!( + close + .as_mut() + .poll(&mut Context::from_waker(noop_waker_ref())) + .is_pending() + ); + drop(close); + } + assert_eq!(session.state(), SessionState::Closing); + assert!(provider.upgrade().is_some() && callbacks.upgrade().is_some()); + control.close_ready.store(true, Ordering::SeqCst); + control.wake.wake(); + block_on(session.close()).unwrap(); + assert!(provider.upgrade().is_none() && callbacks.upgrade().is_none()); + assert_eq!(control.quiesces.load(Ordering::SeqCst), 1); + assert_eq!(control.close_attempts.load(Ordering::SeqCst), 2); + assert_eq!(control.closes.load(Ordering::SeqCst), 1); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn failed_observation_does_not_freeze_a_key_and_lost_observer_keeps_host_roots() { + let Fixture { + session, + control, + provider, + callbacks, + } = scope(); + let (send, receive) = oneshot::channel(); + drop(send); + *control.response.lock().unwrap() = Some(receive); + assert_eq!(block_on(session.observe()), Err(ProviderError::Cancelled)); + assert!(session.observed().is_none()); + *control.current.lock().unwrap() = state(true, false); + assert_eq!(block_on(session.observe()).unwrap().identity(), key(true)); + + let (send, receive) = oneshot::channel(); + *control.response.lock().unwrap() = Some(receive); + let mut observe = Box::pin(session.observe()); + let mut cx = Context::from_waker(noop_waker_ref()); + assert!(observe.as_mut().poll(&mut cx).is_pending()); + drop(observe); + control.close_ready.store(false, Ordering::SeqCst); + let mut close = Box::pin(session.close()); + assert!(close.as_mut().poll(&mut cx).is_pending()); + assert_eq!(control.close_attempts.load(Ordering::SeqCst), 1); + assert!(provider.upgrade().is_some() && callbacks.upgrade().is_some()); + assert!(send.send(()).is_err()); + control.close_ready.store(true, Ordering::SeqCst); + control.wake.wake(); + assert!(matches!(close.as_mut().poll(&mut cx), Poll::Ready(Ok(())))); + assert!(provider.upgrade().is_none() && callbacks.upgrade().is_none()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_scope_and_owned_futures_retain_thread_guarantees() { + fn send_sync<T: Send + Sync>() {} + fn send<T: Send>(_: T) {} + send_sync::<SignerHandle>(); + send_sync::<SignerSession>(); + let Fixture { session, .. } = scope(); + send(session.observe()); + send(session.close()); +} + +#[cfg(target_arch = "wasm32")] +#[test] +fn browser_scope_accepts_rc_local_provider_and_callbacks() { + let control = control(); + let session = SignerSession::new(SignerHandle::new( + Shared::new(Provider(control.clone())), + Shared::new(Callbacks(control)), + )); + assert_eq!(block_on(session.observe()).unwrap().identity(), key(false)); + block_on(session.close()).unwrap(); +} diff --git a/crates/signing/README.md b/crates/signing/README.md @@ -98,6 +98,12 @@ 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. +`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, +await callback closure and release roots on the required host thread. Neither +construction nor an identity observation grants a workspace or command role. + ```compile_fail use radroots_signing::provider::PrivateText; let text = PrivateText::new("private inquiry").unwrap(); diff --git a/crates/signing/src/provider.rs b/crates/signing/src/provider.rs @@ -13,7 +13,12 @@ use radroots_identity::PublicKey; use std::string::String; use zeroize::Zeroizing; -use crate::{Signer, host::HostBound, request::CancellationSignal, signer::BoxFuture}; +use crate::{ + Signer, + host::{HostBound, Shared}, + request::CancellationSignal, + signer::BoxFuture, +}; /// Maximum bytes in one crypto boundary input or output. Profile budgets are /// independently enforced before invoking this lower-level capability. @@ -273,3 +278,45 @@ pub trait ParticipantProvider: Signer { ciphertext: PrivateCiphertext, ) -> BoxFuture<'_, Result<PrivateText, ProviderError>>; } + +/// Host callback roots belonging to one scoped participant-provider handle. +/// Host implementations must dispatch on their required thread and retain +/// partial progress across cancellation and known failure. These methods do +/// not revoke another session or erase already obtained signing evidence. +pub trait SignerCallbacks: HostBound { + /// Stops new dispatch and safely unblocks pending identity observations. + /// Keep roots and every already obtained signing result until retained. + fn quiesce(&self) -> BoxFuture<'_, Result<(), ProviderError>>; + + /// Drains dispatched callbacks, including callbacks whose Rust observer + /// was dropped. Success permits releasing this scope's callback roots. + fn close(&self) -> BoxFuture<'_, Result<(), ProviderError>>; +} + +/// Owned provider and its exact host callback scope. Construction invokes +/// neither object and grants no workspace, command or stock authority. +/// The host must pair these capabilities from the same actual dispatch scope. +pub struct SignerHandle { + provider: Shared<dyn ParticipantProvider>, + callbacks: Shared<dyn SignerCallbacks>, +} + +impl SignerHandle { + /// Takes ownership of one explicitly constructed provider scope. + pub fn new( + provider: Shared<dyn ParticipantProvider>, + callbacks: Shared<dyn SignerCallbacks>, + ) -> Self { + Self { + provider, + callbacks, + } + } + + /// Transfers both owned capabilities to the composing lifecycle owner. + /// This exposes no private key and supplies no authorization or proof of + /// provider qualification. The owner must retain roots through closure. + pub fn into_parts(self) -> (Shared<dyn ParticipantProvider>, Shared<dyn SignerCallbacks>) { + (self.provider, self.callbacks) + } +} diff --git a/crates/signing/tests/package_boundary.rs b/crates/signing/tests/package_boundary.rs @@ -262,7 +262,8 @@ fn production_sources_publish_only_the_approved_traits_and_no_host_stack() { "NonceSource", "ParticipantProvider", "ProgressObserver", - "Signer" + "Signer", + "SignerCallbacks" ] .into_iter() .map(str::to_owned)