lib

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

request.rs (13944B)


      1 //! Validated authored-plan signing requests.
      2 
      3 use core::{
      4     fmt,
      5     sync::atomic::{AtomicBool, Ordering},
      6 };
      7 use radroots_event_codec::authoring::{AuthoredEventPlan, BlossomAuthorizationPlan, PlanDigest};
      8 use radroots_identity::PublicKey;
      9 use radroots_protocol::runtime::v1::OperationId;
     10 
     11 #[cfg(not(feature = "std"))]
     12 use alloc::sync::Arc;
     13 #[cfg(feature = "std")]
     14 use std::sync::Arc;
     15 
     16 use crate::{
     17     Actor, Error, SignerRequestId, SigningIntentId,
     18     authorization::{
     19         CurrentAuthoringAuthority, CurrentAuthoringDecision, CurrentRegistryAuthority,
     20         DeprecatedPlanPolicy, ManagedSigningPolicy, current_authoring_contract,
     21     },
     22     error::Kind,
     23     status::SignProgress,
     24 };
     25 
     26 /// How a signer must interpret cancellation around remote publication.
     27 #[non_exhaustive]
     28 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
     29 #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
     30 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
     31 pub enum CancellationPolicy {
     32     PreservePublishedRequest,
     33     LocalCooperative,
     34 }
     35 
     36 /// Runtime-local cooperative cancellation shared by caller and signer.
     37 #[derive(Clone, Debug, Default)]
     38 pub struct CancellationSignal(Arc<AtomicBool>);
     39 
     40 impl CancellationSignal {
     41     #[must_use]
     42     pub fn new() -> Self {
     43         Self::default()
     44     }
     45 
     46     pub fn cancel(&self) {
     47         self.0.store(true, Ordering::Release);
     48     }
     49 
     50     #[must_use]
     51     pub fn is_cancelled(&self) -> bool {
     52         self.0.load(Ordering::Acquire)
     53     }
     54 }
     55 
     56 /// Explicit millisecond deadline and authorization/cancellation policy.
     57 #[non_exhaustive]
     58 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
     59 #[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
     60 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
     61 pub struct SignPolicy {
     62     deadline_unix_ms: u64,
     63     cancellation: CancellationPolicy,
     64     deprecated_plan: DeprecatedPlanPolicy,
     65     managed_signing: ManagedSigningPolicy,
     66 }
     67 
     68 impl SignPolicy {
     69     pub const fn new(
     70         deadline_unix_ms: u64,
     71         cancellation: CancellationPolicy,
     72     ) -> Result<Self, Error> {
     73         if deadline_unix_ms == 0 {
     74             return Err(Error::new(Kind::InvalidArgument));
     75         }
     76         Ok(Self {
     77             deadline_unix_ms,
     78             cancellation,
     79             deprecated_plan: DeprecatedPlanPolicy::Deny,
     80             managed_signing: ManagedSigningPolicy::AnyValidatedSource,
     81         })
     82     }
     83 
     84     #[must_use]
     85     pub const fn allowing_deprecated(mut self) -> Self {
     86         self.deprecated_plan = DeprecatedPlanPolicy::Allow;
     87         self
     88     }
     89 
     90     #[must_use]
     91     pub const fn with_managed_signing_policy(mut self, policy: ManagedSigningPolicy) -> Self {
     92         self.managed_signing = policy;
     93         self
     94     }
     95 
     96     #[must_use]
     97     pub const fn deadline_unix_ms(self) -> u64 {
     98         self.deadline_unix_ms
     99     }
    100 
    101     #[must_use]
    102     pub const fn cancellation(self) -> CancellationPolicy {
    103         self.cancellation
    104     }
    105 
    106     #[must_use]
    107     pub const fn deprecated_plan(self) -> DeprecatedPlanPolicy {
    108         self.deprecated_plan
    109     }
    110 
    111     #[must_use]
    112     pub const fn managed_signing(self) -> ManagedSigningPolicy {
    113         self.managed_signing
    114     }
    115 }
    116 
    117 #[cfg(feature = "serde")]
    118 impl<'de> serde::Deserialize<'de> for SignPolicy {
    119     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    120     where
    121         D: serde::Deserializer<'de>,
    122     {
    123         #[derive(serde::Deserialize)]
    124         #[serde(deny_unknown_fields)]
    125         struct Repr {
    126             deadline_unix_ms: u64,
    127             cancellation: CancellationPolicy,
    128             deprecated_plan: DeprecatedPlanPolicy,
    129             managed_signing: ManagedSigningPolicy,
    130         }
    131 
    132         let value = Repr::deserialize(deserializer)?;
    133         let mut policy = Self::new(value.deadline_unix_ms, value.cancellation)
    134             .map_err(serde::de::Error::custom)?;
    135         policy.deprecated_plan = value.deprecated_plan;
    136         policy.managed_signing = value.managed_signing;
    137         Ok(policy)
    138     }
    139 }
    140 
    141 /// Runtime-local observer for signing progress.
    142 pub trait ProgressObserver: crate::host::HostBound {
    143     fn on_progress(&self, progress: &SignProgress);
    144 }
    145 
    146 /// Domain-separated reason an exact Nostr event is being signed.
    147 #[non_exhaustive]
    148 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    149 #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
    150 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    151 pub enum SigningPurpose {
    152     /// A registry-authorized event that may enter the durable relay pipeline.
    153     AuthoredEvent,
    154     /// A short-lived BUD-11 upload credential for an HTTP request only.
    155     BlossomUploadAuthorization,
    156 }
    157 
    158 #[derive(Clone)]
    159 enum SigningPlan {
    160     Authored(AuthoredEventPlan),
    161     BlossomUpload(BlossomAuthorizationPlan),
    162 }
    163 
    164 impl SigningPlan {
    165     const fn purpose(&self) -> SigningPurpose {
    166         match self {
    167             Self::Authored(_) => SigningPurpose::AuthoredEvent,
    168             Self::BlossomUpload(_) => SigningPurpose::BlossomUploadAuthorization,
    169         }
    170     }
    171 
    172     const fn author(&self) -> &PublicKey {
    173         match self {
    174             Self::Authored(plan) => plan.author(),
    175             Self::BlossomUpload(plan) => plan.author(),
    176         }
    177     }
    178 
    179     const fn created_at(&self) -> u64 {
    180         match self {
    181             Self::Authored(plan) => plan.created_at(),
    182             Self::BlossomUpload(plan) => plan.created_at(),
    183         }
    184     }
    185 
    186     const fn kind(&self) -> u32 {
    187         match self {
    188             Self::Authored(plan) => plan.body().kind(),
    189             Self::BlossomUpload(plan) => plan.kind(),
    190         }
    191     }
    192 
    193     fn tags(&self) -> &[alloc_or_std::Vec<alloc_or_std::String>] {
    194         match self {
    195             Self::Authored(plan) => plan.body().tags(),
    196             Self::BlossomUpload(plan) => plan.tags(),
    197         }
    198     }
    199 
    200     fn content(&self) -> &str {
    201         match self {
    202             Self::Authored(plan) => plan.body().content(),
    203             Self::BlossomUpload(plan) => plan.content(),
    204         }
    205     }
    206 
    207     const fn expected_event_id(&self) -> &radroots_event::EventId {
    208         match self {
    209             Self::Authored(plan) => plan.expected_event_id(),
    210             Self::BlossomUpload(plan) => plan.expected_event_id(),
    211         }
    212     }
    213 
    214     const fn digest(&self) -> PlanDigest {
    215         match self {
    216             Self::Authored(plan) => plan.digest(),
    217             Self::BlossomUpload(plan) => plan.digest(),
    218         }
    219     }
    220 }
    221 
    222 #[cfg(not(feature = "std"))]
    223 mod alloc_or_std {
    224     pub use alloc::{string::String, vec::Vec};
    225 }
    226 #[cfg(feature = "std")]
    227 mod alloc_or_std {
    228     pub use std::{string::String, vec::Vec};
    229 }
    230 
    231 /// One currently authorized exact plan and bounded signer invocation.
    232 #[derive(Clone)]
    233 pub struct SignRequest {
    234     operation_kind: OperationId,
    235     intent_id: SigningIntentId,
    236     signer_request_id: SignerRequestId,
    237     actor: Actor,
    238     plan: SigningPlan,
    239     authorization: Option<CurrentAuthoringDecision>,
    240     policy: SignPolicy,
    241     cancellation_signal: CancellationSignal,
    242     progress_observer: Option<crate::host::Shared<dyn ProgressObserver>>,
    243 }
    244 
    245 impl SignRequest {
    246     pub fn new(
    247         operation_kind: OperationId,
    248         intent_id: SigningIntentId,
    249         actor: Actor,
    250         plan: AuthoredEventPlan,
    251         policy: SignPolicy,
    252     ) -> Result<Self, Error> {
    253         Self::new_with_authority(
    254             operation_kind,
    255             intent_id,
    256             actor,
    257             plan,
    258             policy,
    259             &CurrentRegistryAuthority,
    260         )
    261     }
    262 
    263     pub fn new_with_authority(
    264         operation_kind: OperationId,
    265         intent_id: SigningIntentId,
    266         actor: Actor,
    267         plan: AuthoredEventPlan,
    268         policy: SignPolicy,
    269         authority: &dyn CurrentAuthoringAuthority,
    270     ) -> Result<Self, Error> {
    271         let authorization = authority.evaluate(&plan);
    272         authorize(&actor, &plan, policy, authorization)?;
    273         let plan = SigningPlan::Authored(plan);
    274         let signer_request_id = SignerRequestId::derive(intent_id.artifact_id(), plan.digest());
    275         Ok(Self {
    276             operation_kind,
    277             intent_id,
    278             signer_request_id,
    279             actor,
    280             plan,
    281             authorization: Some(authorization),
    282             policy,
    283             cancellation_signal: CancellationSignal::new(),
    284             progress_observer: None,
    285         })
    286     }
    287 
    288     /// Creates a bounded HTTP-only BUD-11 upload authorization request.
    289     pub fn blossom_upload(
    290         operation_kind: OperationId,
    291         intent_id: SigningIntentId,
    292         actor: Actor,
    293         plan: BlossomAuthorizationPlan,
    294         policy: SignPolicy,
    295     ) -> Result<Self, Error> {
    296         if actor.public_key() != *plan.author() || !policy.managed_signing().permits(&actor) {
    297             return Err(Error::new(Kind::AuthorizationDenied));
    298         }
    299         let plan = SigningPlan::BlossomUpload(plan);
    300         let signer_request_id = SignerRequestId::derive(intent_id.artifact_id(), plan.digest());
    301         Ok(Self {
    302             operation_kind,
    303             intent_id,
    304             signer_request_id,
    305             actor,
    306             plan,
    307             authorization: None,
    308             policy,
    309             cancellation_signal: CancellationSignal::new(),
    310             progress_observer: None,
    311         })
    312     }
    313 
    314     #[must_use]
    315     pub fn with_cancellation_signal(mut self, signal: CancellationSignal) -> Self {
    316         self.cancellation_signal = signal;
    317         self
    318     }
    319 
    320     #[must_use]
    321     pub fn with_progress_observer(
    322         mut self,
    323         observer: crate::host::Shared<dyn ProgressObserver>,
    324     ) -> Self {
    325         self.progress_observer = Some(observer);
    326         self
    327     }
    328 
    329     #[must_use]
    330     pub const fn operation_kind(&self) -> OperationId {
    331         self.operation_kind
    332     }
    333 
    334     #[must_use]
    335     pub const fn intent_id(&self) -> SigningIntentId {
    336         self.intent_id
    337     }
    338 
    339     #[must_use]
    340     pub const fn signer_request_id(&self) -> SignerRequestId {
    341         self.signer_request_id
    342     }
    343 
    344     #[must_use]
    345     pub const fn actor(&self) -> &Actor {
    346         &self.actor
    347     }
    348 
    349     #[must_use]
    350     pub const fn purpose(&self) -> SigningPurpose {
    351         self.plan.purpose()
    352     }
    353 
    354     /// Returns the registry-authored plan, if this is a relay-event request.
    355     #[must_use]
    356     pub const fn authored_plan(&self) -> Option<&AuthoredEventPlan> {
    357         match &self.plan {
    358             SigningPlan::Authored(plan) => Some(plan),
    359             SigningPlan::BlossomUpload(_) => None,
    360         }
    361     }
    362 
    363     /// Returns the HTTP-only upload-authorization plan, when applicable.
    364     #[must_use]
    365     pub const fn blossom_authorization_plan(&self) -> Option<&BlossomAuthorizationPlan> {
    366         match &self.plan {
    367             SigningPlan::Authored(_) => None,
    368             SigningPlan::BlossomUpload(plan) => Some(plan),
    369         }
    370     }
    371 
    372     #[must_use]
    373     pub const fn expected_author(&self) -> &PublicKey {
    374         self.plan.author()
    375     }
    376 
    377     #[must_use]
    378     pub const fn created_at(&self) -> u64 {
    379         self.plan.created_at()
    380     }
    381 
    382     #[must_use]
    383     pub const fn kind(&self) -> u32 {
    384         self.plan.kind()
    385     }
    386 
    387     #[must_use]
    388     pub fn tags(&self) -> &[alloc_or_std::Vec<alloc_or_std::String>] {
    389         self.plan.tags()
    390     }
    391 
    392     #[must_use]
    393     pub fn content(&self) -> &str {
    394         self.plan.content()
    395     }
    396 
    397     #[must_use]
    398     pub const fn expected_event_id(&self) -> &radroots_event::EventId {
    399         self.plan.expected_event_id()
    400     }
    401 
    402     #[must_use]
    403     pub const fn plan_digest(&self) -> PlanDigest {
    404         self.plan.digest()
    405     }
    406 
    407     #[must_use]
    408     pub const fn authorization(&self) -> Option<CurrentAuthoringDecision> {
    409         self.authorization
    410     }
    411 
    412     #[must_use]
    413     pub const fn policy(&self) -> SignPolicy {
    414         self.policy
    415     }
    416 
    417     #[must_use]
    418     pub const fn cancellation_signal(&self) -> &CancellationSignal {
    419         &self.cancellation_signal
    420     }
    421 
    422     pub fn ensure_active(&self, now_unix_ms: u64) -> Result<(), Error> {
    423         if self.cancellation_signal.is_cancelled() {
    424             return Err(Error::new(Kind::SignerCancelled));
    425         }
    426         if now_unix_ms >= self.policy.deadline_unix_ms {
    427             return Err(Error::new(Kind::DeadlineExceeded));
    428         }
    429         Ok(())
    430     }
    431 
    432     pub fn report_progress(&self, progress: &SignProgress) {
    433         if let Some(observer) = &self.progress_observer {
    434             observer.on_progress(progress);
    435         }
    436     }
    437 }
    438 
    439 fn authorize(
    440     actor: &Actor,
    441     plan: &AuthoredEventPlan,
    442     policy: SignPolicy,
    443     decision: CurrentAuthoringDecision,
    444 ) -> Result<(), Error> {
    445     match decision {
    446         CurrentAuthoringDecision::Allowed => {}
    447         CurrentAuthoringDecision::AllowedDeprecated { .. }
    448             if policy.deprecated_plan() == DeprecatedPlanPolicy::Allow => {}
    449         CurrentAuthoringDecision::AllowedDeprecated { .. }
    450         | CurrentAuthoringDecision::Blocked { .. }
    451         | CurrentAuthoringDecision::Revoked { .. } => {
    452             return Err(Error::new(Kind::AuthorizationDenied));
    453         }
    454     }
    455     let contract =
    456         current_authoring_contract(plan).ok_or_else(|| Error::new(Kind::AuthorizationDenied))?;
    457     if !actor.satisfies(contract.required_author_role())
    458         || actor.public_key() != *plan.author()
    459         || !policy.managed_signing().permits(actor)
    460     {
    461         return Err(Error::new(Kind::AuthorizationDenied));
    462     }
    463     Ok(())
    464 }
    465 
    466 impl fmt::Debug for SignRequest {
    467     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    468         formatter
    469             .debug_struct("SignRequest")
    470             .field("operation_kind", &self.operation_kind)
    471             .field("intent_id", &self.intent_id)
    472             .field("signer_request_id", &self.signer_request_id)
    473             .field("actor", &self.actor)
    474             .field("purpose", &self.purpose())
    475             .field("plan", &"[redacted exact event plan]")
    476             .field("authorization", &self.authorization)
    477             .field("policy", &self.policy)
    478             .finish_non_exhaustive()
    479     }
    480 }