lib

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

recovery.rs (7210B)


      1 //! Qualified local replay authorization over an existing protected claim.
      2 use super::super::{
      3     inventory::{Turn, acceptance},
      4     order_state,
      5 };
      6 use super::{
      7     StockClaimRequest, StockReplayAdmissionReceipt, StockSigningAttempt, claim, replay_admission,
      8     signing_plan,
      9 };
     10 use crate::workspace::{AttachmentProof, NativeWorkspace, WorkspaceError};
     11 use radroots_domain::UnixSeconds;
     12 use radroots_protocol::intent::SigningReplay;
     13 use radroots_signing::{
     14     issuance::{ExactRecoveryRequest, SigningIntent},
     15     provider::ProviderCall,
     16     request::CancellationSignal,
     17 };
     18 use radroots_storage::command::OperationError;
     19 use sqlx::Connection;
     20 
     21 /// Single-use current authorization for qualified exact local replay only.
     22 /// This is never a new first-dispatch claim, proof of issuance or nonissuance.
     23 pub struct StockExactReplayPermit {
     24     report: StockSigningAttempt,
     25     at: UnixSeconds,
     26     admission: Option<StockReplayAdmissionReceipt>,
     27 }
     28 impl StockExactReplayPermit {
     29     /// Confirmed first replay admission in tracked catalogs15–16. Retained13/14
     30     /// permits are explicitly untracked and return None; no report authorizes
     31     /// stock release, a fresh first dispatch or another replay invocation.
     32     pub const fn admission(&self) -> Option<StockReplayAdmissionReceipt> {
     33         self.admission
     34     }
     35 
     36     /// Borrows the original protected attempt; this report cannot mint a permit.
     37     pub const fn report(&self) -> &StockSigningAttempt {
     38         &self.report
     39     }
     40     /// Returns the final checked workspace authorization observation.
     41     pub const fn authorized_at(&self) -> UnixSeconds {
     42         self.at
     43     }
     44     /// Transfers exact original intent data to the separately qualified provider.
     45     /// The owner must retain obtained S through durable capture after observer
     46     /// loss. The actual local adapter checks both original and call windows.
     47     pub fn into_recovery_request(
     48         self,
     49         call: ProviderCall,
     50     ) -> Result<(ExactRecoveryRequest, StockSigningAttempt), OperationError> {
     51         let intent: SigningIntent = claim::intent(
     52             self.report.bound_plan(),
     53             self.report.recipient(),
     54             CancellationSignal::new(),
     55         )?;
     56         if intent.binding() != self.report.binding() {
     57             return Err(OperationError::RecoveryRequired);
     58         }
     59         let request =
     60             ExactRecoveryRequest::new(intent, call).map_err(|_| OperationError::InvalidCommand)?;
     61         Ok((request, self.report))
     62     }
     63 }
     64 impl core::fmt::Debug for StockExactReplayPermit {
     65     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
     66         f.write_str("StockExactReplayPermit(<redacted>)")
     67     }
     68 }
     69 
     70 pub(in crate::workspace) async fn authorize(
     71     turn: &mut Turn<'_>,
     72     request: StockClaimRequest,
     73     proof: AttachmentProof,
     74 ) -> Result<StockExactReplayPermit, OperationError> {
     75     let auth = Box::pin(signing_plan::load(
     76         turn,
     77         &request.binding,
     78         request.minimum,
     79         request.operation,
     80         request.digest,
     81         &proof,
     82     ))
     83     .await?;
     84     if !matches!(auth.access.authority.catalog, 13..=20) {
     85         return Err(OperationError::UnsupportedOperation);
     86     }
     87     let plan = auth.plan.as_ref().ok_or(OperationError::StaleState)?;
     88     // Later provider capabilities cannot upgrade the retained T1 policy.
     89     if plan.bound.plan().replay() != SigningReplay::LocalReplaySafe {
     90         return Err(OperationError::UnsupportedOperation);
     91     }
     92     let intent = claim::intent(&plan.bound, request.recipient, CancellationSignal::new())?;
     93     let (retained, witness) = Box::pin(claim::existing(
     94         turn,
     95         &auth,
     96         request.operation,
     97         request.recipient,
     98     ))
     99     .await?;
    100     let retained = retained.ok_or(OperationError::StaleState)?;
    101     if intent.binding() != retained.report.binding() {
    102         return Err(OperationError::RecoveryRequired);
    103     }
    104     let at = auth.access.current.observed_at();
    105     acceptance::check_consent(&auth.access, &auth.consent, &auth.command, true, at)?;
    106     if at < plan.bound.bound_at()
    107         || at < retained.report.claimed_at()
    108         || at >= plan.bound.preparation().first_issue_deadline()
    109     {
    110         return Err(OperationError::DeadlineExceeded);
    111     }
    112     let order = Box::pin(order_state::signing_state(
    113         turn,
    114         &auth.access,
    115         auth.original.receipt.order_id(),
    116         request.operation,
    117         true,
    118     ))
    119     .await?;
    120     let backing = Box::pin(super::super::inventory::backing::read(
    121         turn,
    122         &auth.access,
    123         auth.original.receipt.held_pools(),
    124     ))
    125     .await?;
    126     let pending = if auth.access.authority.catalog >= 15 {
    127         Some(Box::pin(replay_admission::prepare(turn, &auth, &retained, at)).await?)
    128     } else {
    129         None
    130     };
    131     let mut tx = turn
    132         .connection
    133         .begin_with("BEGIN IMMEDIATE")
    134         .await
    135         .map_err(|_| OperationError::StorageFailure)?;
    136     let checked: Result<UnixSeconds, OperationError> = async {
    137         Box::pin(witness.confirm(&mut tx)).await?;
    138         retained.confirm(&mut tx).await?;
    139         if let Some(order) = &order {
    140             order.confirm(&mut tx).await?;
    141         }
    142         for pool in &backing {
    143             pool.confirm(&mut tx).await?;
    144         }
    145         let current =
    146             Box::pin(auth.confirm(&mut tx, turn.namespace, turn.clock, &proof, true)).await?;
    147         if current.observed_at() < at || current.observed_at() < retained.report.claimed_at() {
    148             return Err(WorkspaceError::Unavailable.into());
    149         }
    150         if let Some(pending) = &pending {
    151             pending.apply(&mut tx, turn.selected, &auth).await?;
    152         }
    153         turn.namespace.validate()?;
    154         Ok(current.observed_at())
    155     }
    156     .await;
    157     let authorized_at = match checked {
    158         Ok(value) => value,
    159         Err(error) => {
    160             if tx.rollback().await.is_err() {
    161                 *turn.uncertain = true;
    162                 return Err(OperationError::RecoveryRequired);
    163             }
    164             return Err(error);
    165         }
    166     };
    167     // A current fresh marker must be committed before a permit can escape.
    168     // Existing markers and retained13/14 authorization require no new write.
    169     let done = if pending.as_ref().is_some_and(|v| v.writes()) {
    170         tx.commit().await
    171     } else {
    172         tx.rollback().await
    173     };
    174     if done.is_err() {
    175         *turn.uncertain = true;
    176         return Err(OperationError::RecoveryRequired);
    177     }
    178     Ok(StockExactReplayPermit {
    179         report: retained.report,
    180         at: authorized_at,
    181         admission: pending.as_ref().map(|v| v.receipt()),
    182     })
    183 }
    184 
    185 impl NativeWorkspace {
    186     /// Authenticates current first-capable local replay rights for an existing
    187     /// original claim. Unsupported/expired/recovery-only state dispatches nothing.
    188     pub async fn authorize_stock_exact_replay(
    189         &self,
    190         request: StockClaimRequest,
    191         proof: &AttachmentProof,
    192     ) -> Result<StockExactReplayPermit, OperationError> {
    193         self.worker
    194             .authorize_stock_exact_replay(
    195                 request,
    196                 proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?,
    197             )
    198             .await
    199     }
    200 }