lib

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

provider.rs (14968B)


      1 //! Participant identity and custody-preserving private-message capabilities.
      2 //!
      3 //! Crypto primitives do not authorize a participant, verify a message carrier,
      4 //! admit a command or establish durable execution. The composing executor must
      5 //! authenticate the signed carrier before decryption and enforce its stricter
      6 //! record/rumor/event budgets. Obtained results remain owned by that executor.
      7 
      8 #[cfg(not(feature = "std"))]
      9 use alloc::{boxed::Box, string::String};
     10 use core::{fmt, num::NonZeroU64};
     11 use radroots_identity::PublicKey;
     12 #[cfg(feature = "std")]
     13 use std::string::String;
     14 use zeroize::Zeroizing;
     15 
     16 use crate::{
     17     Signer,
     18     host::{HostBound, Shared},
     19     request::CancellationSignal,
     20     signer::BoxFuture,
     21 };
     22 
     23 /// Maximum bytes in one crypto boundary input or output. Profile budgets are
     24 /// independently enforced before invoking this lower-level capability.
     25 pub const PRIVATE_CRYPTO_MAX_BYTES: usize = 65_536;
     26 
     27 /// Fixed, source-redacted private-provider failures.
     28 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
     29 #[non_exhaustive]
     30 pub enum ProviderError {
     31     /// Input representation is invalid.
     32     InvalidInput,
     33     /// The bounded crypto boundary cannot represent the input or output.
     34     LimitExceeded,
     35     /// The payload's encryption version is unsupported.
     36     UnsupportedVersion,
     37     /// Required provider support or entropy is unavailable.
     38     CapabilityUnavailable,
     39     /// The selected participant differs from this provider's current key.
     40     IdentityChanged,
     41     /// Authentication of the encrypted payload failed.
     42     AuthenticationFailed,
     43     /// Cancellation was observed before beginning work.
     44     Cancelled,
     45     /// The call's deadline expired before work began.
     46     DeadlineExceeded,
     47     /// A provider failed without returning private dependency diagnostics.
     48     ProviderFailure,
     49 }
     50 
     51 impl ProviderError {
     52     /// Returns a stable diagnostic without private input or dependency prose.
     53     pub const fn as_str(self) -> &'static str {
     54         match self {
     55             Self::InvalidInput => "invalid_input",
     56             Self::LimitExceeded => "limit_exceeded",
     57             Self::UnsupportedVersion => "unsupported_version",
     58             Self::CapabilityUnavailable => "capability_unavailable",
     59             Self::IdentityChanged => "identity_changed",
     60             Self::AuthenticationFailed => "authentication_failed",
     61             Self::Cancelled => "cancelled",
     62             Self::DeadlineExceeded => "deadline_exceeded",
     63             Self::ProviderFailure => "provider_failure",
     64         }
     65     }
     66 }
     67 impl fmt::Display for ProviderError {
     68     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     69         f.write_str(self.as_str())
     70     }
     71 }
     72 impl core::error::Error for ProviderError {}
     73 
     74 /// Owned private UTF-8 text with bounded construction and cleared storage on
     75 /// drop. It has no serialization, cloning or input-bearing diagnostic surface.
     76 pub struct PrivateText(Zeroizing<String>);
     77 
     78 impl PrivateText {
     79     /// Checks the byte budget before copying borrowed input.
     80     pub fn new(value: &str) -> Result<Self, ProviderError> {
     81         if value.is_empty() {
     82             return Err(ProviderError::InvalidInput);
     83         }
     84         if value.len() > PRIVATE_CRYPTO_MAX_BYTES {
     85             return Err(ProviderError::LimitExceeded);
     86         }
     87         Ok(Self(Zeroizing::new(String::from(value))))
     88     }
     89 
     90     /// Takes already obtained private text without copying it. Failure also
     91     /// clears the owned buffer; no rejected text is retained in an error.
     92     pub fn from_owned(value: String) -> Result<Self, ProviderError> {
     93         let value = Zeroizing::new(value);
     94         if value.is_empty() {
     95             return Err(ProviderError::InvalidInput);
     96         }
     97         if value.len() > PRIVATE_CRYPTO_MAX_BYTES {
     98             return Err(ProviderError::LimitExceeded);
     99         }
    100         Ok(Self(value))
    101     }
    102 
    103     /// Explicitly borrows protected plaintext for its authorized consumer.
    104     pub fn expose(&self) -> &str {
    105         self.0.as_str()
    106     }
    107 }
    108 
    109 impl fmt::Debug for PrivateText {
    110     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    111         f.write_str("PrivateText([redacted])")
    112     }
    113 }
    114 
    115 /// Owned bounded encoded ciphertext. Construction is structural only; it does
    116 /// not verify its MAC, encryption version, author or signed-event carrier.
    117 pub struct PrivateCiphertext(String);
    118 
    119 impl PrivateCiphertext {
    120     /// Checks bounds before copying an untrusted provider or event payload.
    121     pub fn parse(value: &str) -> Result<Self, ProviderError> {
    122         if value.len() > PRIVATE_CRYPTO_MAX_BYTES {
    123             return Err(ProviderError::LimitExceeded);
    124         }
    125         if value.starts_with('#') {
    126             return Err(ProviderError::UnsupportedVersion);
    127         }
    128         if value.len() < 132
    129             || !value
    130                 .bytes()
    131                 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'='))
    132         {
    133             return Err(ProviderError::InvalidInput);
    134         }
    135         Ok(Self(String::from(value)))
    136     }
    137 
    138     /// Borrows encoded private evidence for storage or its authenticated carrier.
    139     pub fn as_str(&self) -> &str {
    140         &self.0
    141     }
    142 }
    143 
    144 impl fmt::Debug for PrivateCiphertext {
    145     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    146         f.write_str("PrivateCiphertext([redacted])")
    147     }
    148 }
    149 
    150 /// One observed private-crypto method capability, not evidence of qualification.
    151 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    152 pub enum PrivateCryptoCapability {
    153     /// This provider cannot perform this method in its current configuration.
    154     Unavailable,
    155     /// The provider implements the bounded NIP-44 version-2 method.
    156     Nip44V2,
    157 }
    158 
    159 /// An identity/capability observation. It supplies neither a scoped grant nor
    160 /// permission to sign, allocate stock or reinterpret a later identity change.
    161 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    162 pub struct ProviderState {
    163     identity: PublicKey,
    164     encryption: PrivateCryptoCapability,
    165     decryption: PrivateCryptoCapability,
    166     signing_replay: crate::recovery::ReplayCapability,
    167     exact_issuance: Option<crate::recovery::ReplayCapability>,
    168     exact_recovery: crate::issuance::ExactRecoveryCapability,
    169 }
    170 impl ProviderState {
    171     /// Reports capabilities actually implemented by the observing provider.
    172     pub const fn new(
    173         identity: PublicKey,
    174         encryption: PrivateCryptoCapability,
    175         decryption: PrivateCryptoCapability,
    176         signing_replay: crate::recovery::ReplayCapability,
    177     ) -> Self {
    178         Self {
    179             identity,
    180             encryption,
    181             decryption,
    182             signing_replay,
    183             exact_issuance: None,
    184             exact_recovery: crate::issuance::ExactRecoveryCapability::Unavailable,
    185         }
    186     }
    187     /// Returns the observed participant key, independently of any hosted principal.
    188     pub const fn identity(self) -> PublicKey {
    189         self.identity
    190     }
    191     /// Returns current encryption support.
    192     pub const fn encryption(self) -> PrivateCryptoCapability {
    193         self.encryption
    194     }
    195     /// Returns current decryption support.
    196     pub const fn decryption(self) -> PrivateCryptoCapability {
    197         self.decryption
    198     }
    199     /// Returns signer replay behavior for this identity observation. This never
    200     /// overrides retained uncertainty or permits blind signing reissue.
    201     pub const fn signing_replay(self) -> crate::recovery::ReplayCapability {
    202         self.signing_replay
    203     }
    204 
    205     /// Reports support for the exact-intent issuance contract separately from
    206     /// the retained legacy signing API. Absence means unavailable.
    207     pub const fn exact_issuance(self) -> Option<crate::recovery::ReplayCapability> {
    208         self.exact_issuance
    209     }
    210 
    211     /// Reports separately implemented original-intent recovery. This metadata
    212     /// alone cannot authorize replay or qualify an adapter.
    213     pub const fn exact_recovery(self) -> crate::issuance::ExactRecoveryCapability {
    214         self.exact_recovery
    215     }
    216     /// Reports actual adapter support, independently of legacy replay and the
    217     /// first-dispatch method. Current access and captured T1 policy still apply.
    218     pub const fn with_exact_recovery(
    219         mut self,
    220         value: crate::issuance::ExactRecoveryCapability,
    221     ) -> Self {
    222         self.exact_recovery = value;
    223         self
    224     }
    225 
    226     /// Records the actual provider's qualified exact-intent support. This
    227     /// observation alone never authorizes replay or business execution.
    228     pub const fn with_exact_issuance(
    229         mut self,
    230         replay: Option<crate::recovery::ReplayCapability>,
    231     ) -> Self {
    232         self.exact_issuance = replay;
    233         self
    234     }
    235 }
    236 
    237 /// Explicit per-call identity, deadline and cooperative cancellation binding.
    238 /// This value is not an authenticated command context or durable admission.
    239 #[derive(Clone)]
    240 pub struct ProviderCall {
    241     identity: PublicKey,
    242     deadline_unix_ms: NonZeroU64,
    243     cancellation: CancellationSignal,
    244 }
    245 impl ProviderCall {
    246     /// Freezes the identity observed by the owning session and its call budget.
    247     pub const fn new(
    248         identity: PublicKey,
    249         deadline_unix_ms: NonZeroU64,
    250         cancellation: CancellationSignal,
    251     ) -> Self {
    252         Self {
    253             identity,
    254             deadline_unix_ms,
    255             cancellation,
    256         }
    257     }
    258     /// Returns the participant key frozen by the owning session.
    259     pub const fn identity(&self) -> PublicKey {
    260         self.identity
    261     }
    262 
    263     /// Returns this invocation's captured scheduling deadline without a clock.
    264     pub const fn deadline_unix_ms(&self) -> NonZeroU64 {
    265         self.deadline_unix_ms
    266     }
    267     /// Validates admission before an effect; never discard an obtained result
    268     /// by repeating this check after the effect.
    269     pub fn check_before_effect(
    270         &self,
    271         current_identity: PublicKey,
    272         now_unix_ms: u64,
    273     ) -> Result<(), ProviderError> {
    274         if current_identity != self.identity {
    275             return Err(ProviderError::IdentityChanged);
    276         }
    277         if self.cancellation.is_cancelled() {
    278             return Err(ProviderError::Cancelled);
    279         }
    280         if now_unix_ms == 0 {
    281             return Err(ProviderError::ProviderFailure);
    282         }
    283         if now_unix_ms >= self.deadline_unix_ms.get() {
    284             return Err(ProviderError::DeadlineExceeded);
    285         }
    286         Ok(())
    287     }
    288 }
    289 
    290 /// Injected nonce entropy. Production implementations must supply fresh,
    291 /// uniformly random 32-byte output from a qualified CSPRNG. The trait and a
    292 /// returned array do not themselves prove entropy quality or uniqueness.
    293 pub trait NonceSource: HostBound {
    294     /// Obtains one nonce or reports failure before encryption begins.
    295     fn next_nonce(&self) -> Result<[u8; 32], ProviderError>;
    296 }
    297 
    298 /// Custody-preserving participant provider. Native futures/handles retain their
    299 /// thread guarantees; browser implementations may retain local UI/key handles.
    300 /// No method exposes a private key or implicitly publishes a message.
    301 pub trait ParticipantProvider: Signer {
    302     /// Issues one exact captured intent. Unsupported adapters do not delegate
    303     /// to the legacy method, which may discard already obtained results.
    304     /// A result is not durable until the executor confirms its capture.
    305     fn sign_exact(
    306         &self,
    307         intent: crate::issuance::SigningIntent,
    308     ) -> BoxFuture<'_, crate::issuance::SigningOutcome> {
    309         Box::pin(async move {
    310             crate::issuance::SigningOutcome::not_dispatched(
    311                 intent.binding(),
    312                 ProviderError::CapabilityUnavailable,
    313             )
    314         })
    315     }
    316 
    317     /// Recovers only the complete original intent according to this adapter's
    318     /// qualified method and the executor's retained T1 policy/current access.
    319     /// Unsupported adapters preserve original uncertainty without invoking any
    320     /// signing method. Refusal of this call proves no original nonissuance.
    321     fn recover_exact(
    322         &self,
    323         request: crate::issuance::ExactRecoveryRequest,
    324     ) -> BoxFuture<'_, crate::issuance::ExactRecoveryOutcome> {
    325         Box::pin(async move {
    326             crate::issuance::ExactRecoveryOutcome::indeterminate(
    327                 request.binding(),
    328                 ProviderError::CapabilityUnavailable,
    329             )
    330         })
    331     }
    332 
    333     /// Observes the actual key and currently available methods without signing.
    334     fn provider_state(&self) -> BoxFuture<'_, Result<ProviderState, ProviderError>>;
    335     /// Encrypts private text using provider-owned custody and qualified entropy.
    336     /// The executor retains the returned preimage before any signing request.
    337     fn encrypt_private(
    338         &self,
    339         call: ProviderCall,
    340         recipient: PublicKey,
    341         plaintext: PrivateText,
    342     ) -> BoxFuture<'_, Result<PrivateCiphertext, ProviderError>>;
    343     /// Decrypts an authenticated carrier's ciphertext. The executor must verify
    344     /// its event ID/signature and bind its author before invoking this primitive.
    345     fn decrypt_private(
    346         &self,
    347         call: ProviderCall,
    348         sender: PublicKey,
    349         ciphertext: PrivateCiphertext,
    350     ) -> BoxFuture<'_, Result<PrivateText, ProviderError>>;
    351 }
    352 
    353 /// Host callback roots belonging to one scoped participant-provider handle.
    354 /// Host implementations must dispatch on their required thread and retain
    355 /// partial progress across cancellation and known failure. These methods do
    356 /// not revoke another session or erase already obtained signing evidence.
    357 pub trait SignerCallbacks: HostBound {
    358     /// Stops new dispatch and safely unblocks pending identity observations.
    359     /// Keep roots and every already obtained signing result until retained.
    360     fn quiesce(&self) -> BoxFuture<'_, Result<(), ProviderError>>;
    361 
    362     /// Drains dispatched callbacks, including callbacks whose Rust observer
    363     /// was dropped. Success permits releasing this scope's callback roots.
    364     fn close(&self) -> BoxFuture<'_, Result<(), ProviderError>>;
    365 }
    366 
    367 /// Owned provider and its exact host callback scope. Construction invokes
    368 /// neither object and grants no workspace, command or stock authority.
    369 /// The host must pair these capabilities from the same actual dispatch scope.
    370 pub struct SignerHandle {
    371     provider: Shared<dyn ParticipantProvider>,
    372     callbacks: Shared<dyn SignerCallbacks>,
    373 }
    374 
    375 impl SignerHandle {
    376     /// Takes ownership of one explicitly constructed provider scope.
    377     pub fn new(
    378         provider: Shared<dyn ParticipantProvider>,
    379         callbacks: Shared<dyn SignerCallbacks>,
    380     ) -> Self {
    381         Self {
    382             provider,
    383             callbacks,
    384         }
    385     }
    386 
    387     /// Transfers both owned capabilities to the composing lifecycle owner.
    388     /// This exposes no private key and supplies no authorization or proof of
    389     /// provider qualification. The owner must retain roots through closure.
    390     pub fn into_parts(self) -> (Shared<dyn ParticipantProvider>, Shared<dyn SignerCallbacks>) {
    391         (self.provider, self.callbacks)
    392     }
    393 }