lib

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

signer.rs (13923B)


      1 use core::num::NonZeroU16;
      2 use radroots_signing::provider::{
      3     ParticipantProvider, PrivateCiphertext, PrivateCryptoCapability, PrivateText, ProviderCall,
      4     ProviderError, ProviderState, SignerCallbacks, SignerHandle,
      5 };
      6 use std::{
      7     boxed::Box,
      8     sync::{Mutex, MutexGuard},
      9 };
     10 
     11 use super::{HostFuture, Session, SessionHost, SessionState, host::Shared};
     12 #[cfg(feature = "commerce")]
     13 #[path = "signer_commerce.rs"]
     14 mod commerce;
     15 
     16 struct Binding {
     17     provider: Shared<dyn ParticipantProvider>,
     18     callbacks: Shared<dyn SignerCallbacks>,
     19 }
     20 
     21 impl radroots_signing::issuance::ExactIssuer for SignerSession {
     22     fn issue_exact(
     23         &self,
     24         intent: radroots_signing::issuance::SigningIntent,
     25     ) -> radroots_signing::signer::BoxFuture<'_, radroots_signing::issuance::SigningOutcome> {
     26         Box::pin(self.sign_exact(intent))
     27     }
     28 }
     29 
     30 impl Binding {
     31     fn shared_copy(&self) -> Self {
     32         Self {
     33             provider: self.provider.clone(),
     34             callbacks: self.callbacks.clone(),
     35         }
     36     }
     37 }
     38 
     39 struct ResourceInner {
     40     binding: Mutex<Option<Binding>>,
     41     observed: Mutex<Observation>,
     42 }
     43 
     44 #[derive(Clone, Copy)]
     45 enum Observation {
     46     None,
     47     Current(ProviderState),
     48     IdentityChanged(ProviderState),
     49 }
     50 
     51 impl ResourceInner {
     52     fn binding(&self) -> MutexGuard<'_, Option<Binding>> {
     53         self.binding
     54             .lock()
     55             .unwrap_or_else(std::sync::PoisonError::into_inner)
     56     }
     57 
     58     fn observed(&self) -> MutexGuard<'_, Observation> {
     59         self.observed
     60             .lock()
     61             .unwrap_or_else(std::sync::PoisonError::into_inner)
     62     }
     63 
     64     fn retain_binding(&self) -> Option<Binding> {
     65         self.binding().as_ref().map(Binding::shared_copy)
     66     }
     67 }
     68 
     69 struct Resources(Shared<ResourceInner>);
     70 
     71 impl SessionHost for Resources {
     72     fn start(&self) -> HostFuture<'_, crate::Result<()>> {
     73         // This scope owns callbacks, not workers or a transport connection.
     74         Box::pin(async { Ok(()) })
     75     }
     76 
     77     fn quiesce(&self) -> HostFuture<'_, crate::Result<()>> {
     78         Box::pin(async move {
     79             let binding = self.0.retain_binding();
     80             if let Some(binding) = binding {
     81                 binding
     82                     .callbacks
     83                     .quiesce()
     84                     .await
     85                     .map_err(|_| crate::Error::signer_unavailable())?;
     86             }
     87             Ok(())
     88         })
     89     }
     90 
     91     fn disconnect(&self) -> HostFuture<'_, crate::Result<()>> {
     92         Box::pin(async { Ok(()) })
     93     }
     94 
     95     fn dispose_callbacks(&self) -> HostFuture<'_, crate::Result<()>> {
     96         Box::pin(async move {
     97             let binding = self.0.retain_binding();
     98             if let Some(binding) = binding {
     99                 binding
    100                     .callbacks
    101                     .close()
    102                     .await
    103                     .map_err(|_| crate::Error::signer_unavailable())?;
    104                 let retired = { self.0.binding().take() };
    105                 // Host-owned destructors and callback code never run under
    106                 // our bookkeeping mutex, including after successful closure.
    107                 drop(retired);
    108             }
    109             Ok(())
    110         })
    111     }
    112 
    113     fn close_storage(&self) -> HostFuture<'_, crate::Result<()>> {
    114         Box::pin(async { Ok(()) })
    115     }
    116 }
    117 
    118 /// A revocable provider observation scope with one frozen participant identity.
    119 ///
    120 /// It supplies no workspace grant, command context, stock authority or provider
    121 /// qualification. The owning Client must retain this scope before awaiting its
    122 /// first observation so cancellation cannot lose callback cleanup ownership.
    123 pub struct SignerSession {
    124     resources: Shared<ResourceInner>,
    125     session: Session<Resources>,
    126 }
    127 
    128 impl Clone for SignerSession {
    129     fn clone(&self) -> Self {
    130         Self {
    131             resources: self.resources.clone(),
    132             session: self.session.clone(),
    133         }
    134     }
    135 }
    136 
    137 impl SignerSession {
    138     /// Recovers an original intent only through the current qualified method.
    139     /// This scope supplies no store authority or captured replay policy. Its
    140     /// caller must own the complete task and durable capture after observer loss.
    141     /// Refusal leaves original issuance indeterminate and renews no deadline.
    142     pub async fn recover_exact(
    143         &self,
    144         request: radroots_signing::issuance::ExactRecoveryRequest,
    145     ) -> radroots_signing::issuance::ExactRecoveryOutcome {
    146         use radroots_signing::issuance::{ExactRecoveryCapability, ExactRecoveryOutcome};
    147         let binding = request.binding();
    148         let refuse = |reason| ExactRecoveryOutcome::indeterminate(binding, reason);
    149         if self.state() != SessionState::Running {
    150             return refuse(ProviderError::CapabilityUnavailable);
    151         }
    152         if self.identity_changed() {
    153             return refuse(ProviderError::IdentityChanged);
    154         }
    155         let Some(observed) = self.observed() else {
    156             return refuse(ProviderError::CapabilityUnavailable);
    157         };
    158         if observed.identity() != request.original().author() {
    159             return refuse(ProviderError::IdentityChanged);
    160         }
    161         if observed.exact_recovery() != ExactRecoveryCapability::LocalExactReplay {
    162             return refuse(ProviderError::CapabilityUnavailable);
    163         }
    164         let observed = match self.observe().await {
    165             Ok(observed) => observed,
    166             Err(error) => return refuse(error),
    167         };
    168         if observed.identity() != request.original().author() {
    169             return refuse(ProviderError::IdentityChanged);
    170         }
    171         if observed.exact_recovery() != ExactRecoveryCapability::LocalExactReplay {
    172             return refuse(ProviderError::CapabilityUnavailable);
    173         }
    174         let Ok(_permit) = self.session.admit() else {
    175             return refuse(ProviderError::CapabilityUnavailable);
    176         };
    177         let Some(provider) = self.resources.retain_binding() else {
    178             return refuse(ProviderError::CapabilityUnavailable);
    179         };
    180         provider
    181             .provider
    182             .recover_exact(request)
    183             .await
    184             .enforce_binding(binding)
    185     }
    186 
    187     async fn private_provider(
    188         &self,
    189         call: &ProviderCall,
    190         encrypt: bool,
    191     ) -> Result<Binding, ProviderError> {
    192         if self.state() != SessionState::Running || self.observed().is_none() {
    193             return Err(ProviderError::CapabilityUnavailable);
    194         }
    195         let observed = self.observe().await?;
    196         if observed.identity() != call.identity() {
    197             return Err(ProviderError::IdentityChanged);
    198         }
    199         let capability = if encrypt {
    200             observed.encryption()
    201         } else {
    202             observed.decryption()
    203         };
    204         if capability != PrivateCryptoCapability::Nip44V2 {
    205             return Err(ProviderError::CapabilityUnavailable);
    206         }
    207         self.resources
    208             .retain_binding()
    209             .ok_or(ProviderError::CapabilityUnavailable)
    210     }
    211 
    212     /// Encrypts only with the already attached participant's current NIP-44 v2
    213     /// provider. It reobserves identity/capability before dispatch and retains
    214     /// the callback scope through the call. No signing or persistence occurs.
    215     pub async fn encrypt_private(
    216         &self,
    217         call: ProviderCall,
    218         recipient: radroots_domain::PublicKey,
    219         plaintext: PrivateText,
    220     ) -> Result<PrivateCiphertext, ProviderError> {
    221         let provider = self.private_provider(&call, true).await?;
    222         let _permit = self
    223             .session
    224             .admit()
    225             .map_err(|_| ProviderError::CapabilityUnavailable)?;
    226         provider
    227             .provider
    228             .encrypt_private(call, recipient, plaintext)
    229             .await
    230     }
    231 
    232     /// Decrypts through the current attached NIP-44 v2 provider. The composing
    233     /// executor must first authenticate the carrier and bind its actual author.
    234     /// Plaintext remains zeroizing and grants no history/command authority.
    235     pub async fn decrypt_private(
    236         &self,
    237         call: ProviderCall,
    238         sender: radroots_domain::PublicKey,
    239         ciphertext: PrivateCiphertext,
    240     ) -> Result<PrivateText, ProviderError> {
    241         let provider = self.private_provider(&call, false).await?;
    242         let _permit = self
    243             .session
    244             .admit()
    245             .map_err(|_| ProviderError::CapabilityUnavailable)?;
    246         provider
    247             .provider
    248             .decrypt_private(call, sender, ciphertext)
    249             .await
    250     }
    251     /// Issues only through an already observed, live exact-intent provider.
    252     /// The executor must retain its own work permit through durable capture;
    253     /// this scoped future owns resources but supplies no admission receipt.
    254     pub async fn sign_exact(
    255         &self,
    256         intent: radroots_signing::issuance::SigningIntent,
    257     ) -> radroots_signing::issuance::SigningOutcome {
    258         use radroots_signing::issuance::SigningOutcome;
    259         let binding = intent.binding();
    260         if self.state() != SessionState::Running {
    261             return SigningOutcome::not_dispatched(binding, ProviderError::CapabilityUnavailable);
    262         }
    263         if self.identity_changed() {
    264             return SigningOutcome::not_dispatched(binding, ProviderError::IdentityChanged);
    265         }
    266         let Some(observed) = self.observed() else {
    267             return SigningOutcome::not_dispatched(binding, ProviderError::CapabilityUnavailable);
    268         };
    269         if observed.identity() != intent.author() {
    270             return SigningOutcome::not_dispatched(binding, ProviderError::IdentityChanged);
    271         }
    272         if observed.exact_issuance().is_none() {
    273             return SigningOutcome::not_dispatched(binding, ProviderError::CapabilityUnavailable);
    274         }
    275         let observed = match self.observe().await {
    276             Ok(observed) => observed,
    277             Err(error) => return SigningOutcome::not_dispatched(binding, error),
    278         };
    279         if observed.identity() != intent.author() || observed.exact_issuance().is_none() {
    280             return SigningOutcome::not_dispatched(binding, ProviderError::CapabilityUnavailable);
    281         }
    282         let Ok(_permit) = self.session.admit() else {
    283             return SigningOutcome::not_dispatched(binding, ProviderError::CapabilityUnavailable);
    284         };
    285         let Some(provider) = self.resources.retain_binding() else {
    286             return SigningOutcome::not_dispatched(binding, ProviderError::CapabilityUnavailable);
    287         };
    288         provider
    289             .provider
    290             .sign_exact(intent)
    291             .await
    292             .enforce_binding(binding)
    293     }
    294 
    295     /// Owns the handle without invoking it. Observations serialize through a
    296     /// single admitted resource permit; excess concurrent observations refuse.
    297     pub fn new(handle: SignerHandle) -> Self {
    298         let (provider, callbacks) = handle.into_parts();
    299         let resources = Shared::new(ResourceInner {
    300             binding: Mutex::new(Some(Binding {
    301                 provider,
    302                 callbacks,
    303             })),
    304             observed: Mutex::new(Observation::None),
    305         });
    306         Self {
    307             session: Session::new(Resources(resources.clone()), NonZeroU16::MIN),
    308             resources,
    309         }
    310     }
    311 
    312     /// Returns resource state without invoking a provider or claiming authority.
    313     pub fn state(&self) -> SessionState {
    314         self.session.state()
    315     }
    316 
    317     /// Returns the last identity-bound observation. Cached capabilities may be
    318     /// stale and never authorize a later effect or override retained uncertainty.
    319     pub fn observed(&self) -> Option<ProviderState> {
    320         match *self.resources.observed() {
    321             Observation::None => None,
    322             Observation::Current(state) | Observation::IdentityChanged(state) => Some(state),
    323         }
    324     }
    325 
    326     /// Reports a latched identity change. Returning to the original key does
    327     /// not reauthorize this scope; explicit replacement is required.
    328     pub fn identity_changed(&self) -> bool {
    329         matches!(*self.resources.observed(), Observation::IdentityChanged(_))
    330     }
    331 
    332     /// Invokes the actual provider and freezes its first successfully observed
    333     /// key. Later capability changes may be observed; another key is refused.
    334     pub async fn observe(&self) -> Result<ProviderState, ProviderError> {
    335         self.session
    336             .start()
    337             .await
    338             .map_err(|_| ProviderError::CapabilityUnavailable)?;
    339         let _permit = self
    340             .session
    341             .admit()
    342             .map_err(|_| ProviderError::CapabilityUnavailable)?;
    343         if self.identity_changed() {
    344             return Err(ProviderError::IdentityChanged);
    345         }
    346         let binding = self
    347             .resources
    348             .retain_binding()
    349             .ok_or(ProviderError::CapabilityUnavailable)?;
    350         let current = binding.provider.provider_state().await?;
    351         let mut observed = self.resources.observed();
    352         if let Observation::Current(old) = *observed
    353             && old.identity() != current.identity()
    354         {
    355             *observed = Observation::IdentityChanged(old);
    356             return Err(ProviderError::IdentityChanged);
    357         }
    358         *observed = Observation::Current(current);
    359         Ok(current)
    360     }
    361 
    362     /// Permanently stops observation admission, drains admitted observations,
    363     /// revokes/drains host callbacks and releases provider roots. Failed or
    364     /// cancelled close retains its unfinished stage and must be resumed.
    365     pub async fn close(&self) -> crate::Result<()> {
    366         self.session.close().await
    367     }
    368 
    369     /// Stops observation admission and host dispatch without releasing roots.
    370     /// The composing Client drains its work and transports before awaiting
    371     /// close, which disposes these callbacks. Cancellation is resumable.
    372     pub async fn quiesce(&self) -> crate::Result<()> {
    373         self.session.quiesce().await
    374     }
    375 }