lib

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

issuance.rs (22571B)


      1 //! First-claim and append-only obtained-evidence turns on the existing owner.
      2 //! This layer never invokes a signer or network capability.
      3 use super::{
      4     AttachmentInput, AttachmentProof, WorkspaceError,
      5     admission::{Journal, recheck, same_binding},
      6     attempt, evidence, operation, plan,
      7     record::GrantRecord,
      8     snapshot::RetainedFacts,
      9     worker,
     10 };
     11 use radroots_domain::{CommandDigest, OperationId, SigningAttemptId, TransactionId};
     12 use radroots_storage::command::SigningTarget;
     13 use radroots_storage::command::{
     14     ArtifactEvidence, BoundSigningPlan, CapturedArtifact, ClaimAttemptOutcome, ClaimAttemptRequest,
     15     CommitAttempt, EvidenceCaptureOutcome, OperationError, SigningAttempt,
     16 };
     17 use sqlx::{Connection, SqliteConnection};
     18 
     19 struct Loaded {
     20     bound: BoundSigningPlan,
     21     operation: operation::ProtectedOperation,
     22     plan: plan::ProtectedPlan,
     23 }
     24 impl Journal<'_> {
     25     async fn load_issuance_plan(
     26         &mut self,
     27         operation_id: OperationId,
     28         digest: CommandDigest,
     29     ) -> Result<Option<Loaded>, OperationError> {
     30         let Some((prepared, operation)) =
     31             operation::read(self.connection, self.selected, operation_id, self.crypto).await?
     32         else {
     33             return Ok(None);
     34         };
     35         if prepared.request().command().context().actor().participant()
     36             != self.selected.participant()
     37         {
     38             return Err(OperationError::Unauthorized);
     39         }
     40         operation::check_digest(
     41             &prepared,
     42             prepared.request().command().context().actor(),
     43             Some(digest),
     44         )?;
     45         let (prepared, value) =
     46             plan::read(self.connection, self.selected, prepared, self.crypto).await?;
     47         let Some((plan, transaction, time, protected)) = value else {
     48             return Ok(None);
     49         };
     50         let bound = BoundSigningPlan::from_committed_store(prepared, plan, transaction, time)?;
     51         Ok(Some(Loaded {
     52             bound,
     53             operation,
     54             plan: protected,
     55         }))
     56     }
     57     pub(super) async fn claim_issuance(
     58         &mut self,
     59         request: ClaimAttemptRequest,
     60         proof: AttachmentProof,
     61     ) -> Result<ClaimAttemptOutcome, OperationError> {
     62         let (grant_record, grant, current) = self.access(request.binding(), &proof).await?;
     63         attempt::require_target(self.connection, request.target()).await?;
     64         let loaded = self
     65             .load_issuance_plan(request.operation_id(), request.command_digest())
     66             .await?
     67             .ok_or(OperationError::RecoveryRequired)?;
     68         same_binding(
     69             loaded.bound.prepared().request().binding(),
     70             request.binding(),
     71         )?;
     72         if loaded.bound.plan().digest() != request.plan_digest() {
     73             return Err(OperationError::IdempotencyConflict);
     74         }
     75         let Loaded {
     76             bound,
     77             operation,
     78             plan,
     79         } = loaded;
     80         let (bound, existing) = attempt::read(
     81             self.connection,
     82             self.selected,
     83             bound,
     84             request.target(),
     85             self.crypto,
     86         )
     87         .await?;
     88         let absence = if existing.is_none() {
     89             Some(
     90                 RetainedFacts::read(
     91                     self.connection,
     92                     self.selected,
     93                     request.binding(),
     94                     request.operation_id(),
     95                     Some(request.command_digest()),
     96                     self.crypto,
     97                 )
     98                 .await?,
     99             )
    100         } else {
    101             None
    102         };
    103         let (snapshot, protected, fresh) = if let Some((id, transaction, time, protected)) =
    104             existing
    105         {
    106             (
    107                 SigningAttempt::from_committed_store(
    108                     bound,
    109                     request.target(),
    110                     id,
    111                     transaction,
    112                     time,
    113                 )?,
    114                 protected,
    115                 false,
    116             )
    117         } else {
    118             if request.target() == SigningTarget::PublicEvent
    119                 && !super::listing::current(self.connection).await?
    120             {
    121                 return Err(OperationError::UnsupportedOperation);
    122             }
    123             if current.observed_at() < bound.bound_at() {
    124                 return Err(WorkspaceError::Unavailable.into());
    125             }
    126             if current.observed_at() >= bound.prepared().issuance_window().first_issue_not_after() {
    127                 return Err(OperationError::DeadlineExceeded);
    128             }
    129             let snapshot = SigningAttempt::from_committed_store(
    130                 bound,
    131                 request.target(),
    132                 SigningAttemptId::from_bytes(super::random()?),
    133                 TransactionId::from_bytes(super::random()?),
    134                 current.observed_at(),
    135             )?;
    136             let protected = attempt::protect(&snapshot, self.crypto).await?;
    137             (snapshot, protected, true)
    138         };
    139         let anchor = snapshot.identity();
    140         let mut transaction = self
    141             .connection
    142             .begin_with("BEGIN IMMEDIATE")
    143             .await
    144             .map_err(|_| OperationError::StorageFailure)?;
    145         let checked: Result<(), OperationError> = async {
    146             let now = recheck(
    147                 &mut transaction,
    148                 self.namespace,
    149                 self.selected,
    150                 &grant,
    151                 &grant_record,
    152                 request.binding(),
    153                 &proof,
    154                 self.clock,
    155             )
    156             .await?;
    157             operation::unchanged(
    158                 &mut transaction,
    159                 snapshot.bound_plan().prepared(),
    160                 &operation,
    161             )
    162             .await?;
    163             plan::unchanged(
    164                 &mut transaction,
    165                 snapshot.bound_plan().prepared(),
    166                 Some(&plan),
    167             )
    168             .await?;
    169             if fresh {
    170                 absence
    171                     .as_ref()
    172                     .ok_or(OperationError::RecoveryRequired)?
    173                     .unchanged(&mut transaction, self.selected, request.operation_id())
    174                     .await?;
    175                 if now.observed_at() < snapshot.claimed_at() {
    176                     return Err(WorkspaceError::Unavailable.into());
    177                 }
    178                 if now.observed_at()
    179                     >= snapshot
    180                         .bound_plan()
    181                         .prepared()
    182                         .issuance_window()
    183                         .first_issue_not_after()
    184                 {
    185                     return Err(OperationError::DeadlineExceeded);
    186                 }
    187                 absent_claim(
    188                     &mut transaction,
    189                     self.selected,
    190                     request.operation_id(),
    191                     request.target(),
    192                 )
    193                 .await?;
    194                 attempt::insert(&mut transaction, &snapshot, &protected).await?;
    195             } else {
    196                 attempt::unchanged(&mut transaction, &snapshot, &protected).await?;
    197             }
    198             Ok(())
    199         }
    200         .await;
    201         if let Err(error) = checked {
    202             if transaction.rollback().await.is_err() {
    203                 *self.uncertain = true;
    204                 return Ok(ClaimAttemptOutcome::Unknown(anchor));
    205             }
    206             return Err(error);
    207         }
    208         let completed = if fresh {
    209             transaction.commit().await
    210         } else {
    211             transaction.rollback().await
    212         };
    213         if completed.is_err() {
    214             *self.uncertain = true;
    215             return Ok(ClaimAttemptOutcome::Unknown(anchor));
    216         }
    217         Ok(if fresh {
    218             ClaimAttemptOutcome::Claimed(snapshot)
    219         } else {
    220             ClaimAttemptOutcome::Retained(snapshot)
    221         })
    222     }
    223     pub(super) async fn query_issuance(
    224         &mut self,
    225         request: ClaimAttemptRequest,
    226         proof: AttachmentProof,
    227     ) -> Result<Option<SigningAttempt>, OperationError> {
    228         let (record, grant, _) = self.access(request.binding(), &proof).await?;
    229         let loaded = self
    230             .load_issuance_plan(request.operation_id(), request.command_digest())
    231             .await?;
    232         let retained = if let Some(loaded) = loaded {
    233             same_binding(
    234                 loaded.bound.prepared().request().binding(),
    235                 request.binding(),
    236             )?;
    237             if loaded.bound.plan().digest() != request.plan_digest() {
    238                 return Err(OperationError::IdempotencyConflict);
    239             }
    240             let (bound, value) = attempt::read(
    241                 self.connection,
    242                 self.selected,
    243                 loaded.bound,
    244                 request.target(),
    245                 self.crypto,
    246             )
    247             .await?;
    248             match value {
    249                 Some((id, transaction, time, protected)) => Some((
    250                     SigningAttempt::from_committed_store(
    251                         bound,
    252                         request.target(),
    253                         id,
    254                         transaction,
    255                         time,
    256                     )?,
    257                     protected,
    258                     loaded.operation,
    259                     loaded.plan,
    260                 )),
    261                 None => None,
    262             }
    263         } else {
    264             None
    265         };
    266         let absence = if retained.is_none() {
    267             Some(
    268                 RetainedFacts::read(
    269                     self.connection,
    270                     self.selected,
    271                     request.binding(),
    272                     request.operation_id(),
    273                     Some(request.command_digest()),
    274                     self.crypto,
    275                 )
    276                 .await?,
    277             )
    278         } else {
    279             None
    280         };
    281         let mut transaction = self
    282             .connection
    283             .begin_with("BEGIN IMMEDIATE")
    284             .await
    285             .map_err(|_| OperationError::StorageFailure)?;
    286         let checked: Result<(), OperationError> = async {
    287             recheck(
    288                 &mut transaction,
    289                 self.namespace,
    290                 self.selected,
    291                 &grant,
    292                 &record,
    293                 request.binding(),
    294                 &proof,
    295                 self.clock,
    296             )
    297             .await?;
    298             if let Some((snapshot, protected, operation, plan)) = &retained {
    299                 operation::unchanged(
    300                     &mut transaction,
    301                     snapshot.bound_plan().prepared(),
    302                     operation,
    303                 )
    304                 .await?;
    305                 plan::unchanged(
    306                     &mut transaction,
    307                     snapshot.bound_plan().prepared(),
    308                     Some(plan),
    309                 )
    310                 .await?;
    311                 attempt::unchanged(&mut transaction, snapshot, protected).await?;
    312             } else {
    313                 absence
    314                     .as_ref()
    315                     .ok_or(OperationError::RecoveryRequired)?
    316                     .unchanged(&mut transaction, self.selected, request.operation_id())
    317                     .await?;
    318                 absent_claim(
    319                     &mut transaction,
    320                     self.selected,
    321                     request.operation_id(),
    322                     request.target(),
    323                 )
    324                 .await?;
    325             }
    326             Ok(())
    327         }
    328         .await;
    329         if transaction.rollback().await.is_err() {
    330             *self.uncertain = true;
    331             return Err(OperationError::RecoveryRequired);
    332         }
    333         checked?;
    334         Ok(retained.map(|value| value.0))
    335     }
    336     /// Original-scope append admission deliberately does not consult a clock,
    337     /// revocation flag or fresh command permission. The actual existing claim,
    338     /// immutable plan and authenticated exact bytes are independently required.
    339     pub(super) async fn capture_access(
    340         &mut self,
    341         input: &AttachmentInput,
    342         proof: &AttachmentProof,
    343     ) -> Result<(GrantRecord, Vec<u8>), OperationError> {
    344         if *self.uncertain {
    345             return Err(OperationError::RecoveryRequired);
    346         }
    347         if input != self.selected {
    348             return Err(OperationError::Unauthorized);
    349         }
    350         self.namespace.validate()?;
    351         let protected = worker::read(self.connection, self.selected).await?;
    352         let plaintext = self
    353             .crypto
    354             .open(
    355                 self.selected.workspace_id(),
    356                 self.selected.grant_id(),
    357                 &protected,
    358             )
    359             .await?;
    360         let record = plaintext.expose_secret(GrantRecord::decode_outbox)?;
    361         record.authenticate_retained_capture(input, proof)?;
    362         self.namespace.validate()?;
    363         Ok((record, protected))
    364     }
    365     pub(super) async fn capture_issuance(
    366         &mut self,
    367         input: AttachmentInput,
    368         proof: AttachmentProof,
    369         supplied: ArtifactEvidence,
    370     ) -> Result<EvidenceCaptureOutcome, OperationError> {
    371         let (record, grant) = self.capture_access(&input, &proof).await?;
    372         if supplied.workspace_id() != self.selected.workspace_id() {
    373             return Err(OperationError::InvalidEvidence);
    374         }
    375         let Loaded {
    376             bound,
    377             operation,
    378             plan,
    379         } = self
    380             .load_issuance_plan(supplied.operation_id(), supplied.command_digest())
    381             .await?
    382             .ok_or(OperationError::RecoveryRequired)?;
    383         let (bound, claim) = attempt::read(
    384             self.connection,
    385             self.selected,
    386             bound,
    387             supplied.target(),
    388             self.crypto,
    389         )
    390         .await?;
    391         let (id, claim_transaction, claimed_at, claim_protected) =
    392             claim.ok_or(OperationError::RecoveryRequired)?;
    393         let snapshot = SigningAttempt::from_committed_store(
    394             bound,
    395             supplied.target(),
    396             id,
    397             claim_transaction,
    398             claimed_at,
    399         )?;
    400         if !supplied.matches_attempt(&snapshot) {
    401             return Err(OperationError::InvalidEvidence);
    402         }
    403         // The supplied typed value was already independently verified. Recheck
    404         // it against the backend's actual immutable claim, not its descriptor.
    405         let checked = ArtifactEvidence::verify(
    406             &snapshot,
    407             supplied.raw_json(),
    408             supplied.observed_at_unix_ms(),
    409         )?;
    410         let existing = evidence::read(self.connection, &snapshot, self.crypto).await?;
    411         let (protected, fresh) = if let Some((original, protected)) = existing {
    412             if original.raw_json() != checked.raw_json() || original.digest() != checked.digest() {
    413                 return Err(OperationError::IdempotencyConflict);
    414             }
    415             (protected, false)
    416         } else {
    417             (
    418                 evidence::protect(
    419                     &snapshot,
    420                     &checked,
    421                     TransactionId::from_bytes(super::random()?),
    422                     self.crypto,
    423                 )
    424                 .await?,
    425                 true,
    426             )
    427         };
    428         let receipt = protected.receipt;
    429         let anchor = CommitAttempt::new(
    430             receipt.workspace_id(),
    431             receipt.operation_id(),
    432             receipt.command_digest(),
    433             Some(receipt.transaction_id()),
    434         );
    435         let mut transaction = self
    436             .connection
    437             .begin_with("BEGIN IMMEDIATE")
    438             .await
    439             .map_err(|_| OperationError::StorageFailure)?;
    440         let captured = async {
    441             self.namespace.validate()?;
    442             if worker::read(&mut transaction, self.selected).await? != grant {
    443                 return Err(OperationError::RecoveryRequired);
    444             }
    445             record.authenticate_retained_capture(&input, &proof)?;
    446             operation::unchanged(
    447                 &mut transaction,
    448                 snapshot.bound_plan().prepared(),
    449                 &operation,
    450             )
    451             .await?;
    452             plan::unchanged(
    453                 &mut transaction,
    454                 snapshot.bound_plan().prepared(),
    455                 Some(&plan),
    456             )
    457             .await?;
    458             attempt::unchanged(&mut transaction, &snapshot, &claim_protected).await?;
    459             if fresh {
    460                 evidence::unchanged(&mut transaction, &snapshot, None).await?;
    461                 evidence::insert(&mut transaction, &protected).await?;
    462             } else {
    463                 evidence::unchanged(&mut transaction, &snapshot, Some(&protected)).await?;
    464             }
    465             Ok(())
    466         }
    467         .await;
    468         if let Err(error) = captured {
    469             if transaction.rollback().await.is_err() {
    470                 *self.uncertain = true;
    471                 return Ok(EvidenceCaptureOutcome::Unknown(anchor));
    472             }
    473             return Err(error);
    474         }
    475         let completed = if fresh {
    476             transaction.commit().await
    477         } else {
    478             transaction.rollback().await
    479         };
    480         if completed.is_err() {
    481             *self.uncertain = true;
    482             return Ok(EvidenceCaptureOutcome::Unknown(anchor));
    483         }
    484         Ok(EvidenceCaptureOutcome::Committed(receipt))
    485     }
    486     pub(super) async fn query_captured(
    487         &mut self,
    488         request: ClaimAttemptRequest,
    489         proof: AttachmentProof,
    490     ) -> Result<Option<CapturedArtifact>, OperationError> {
    491         let (record, grant, _) = self.access(request.binding(), &proof).await?;
    492         let loaded = self
    493             .load_issuance_plan(request.operation_id(), request.command_digest())
    494             .await?;
    495         let retained = if let Some(loaded) = loaded {
    496             same_binding(
    497                 loaded.bound.prepared().request().binding(),
    498                 request.binding(),
    499             )?;
    500             if loaded.bound.plan().digest() != request.plan_digest() {
    501                 return Err(OperationError::IdempotencyConflict);
    502             }
    503             let (bound, value) = attempt::read(
    504                 self.connection,
    505                 self.selected,
    506                 loaded.bound,
    507                 request.target(),
    508                 self.crypto,
    509             )
    510             .await?;
    511             if let Some((id, transaction, time, protected)) = value {
    512                 let snapshot = SigningAttempt::from_committed_store(
    513                     bound,
    514                     request.target(),
    515                     id,
    516                     transaction,
    517                     time,
    518                 )?;
    519                 let captured = evidence::read(self.connection, &snapshot, self.crypto).await?;
    520                 Some((snapshot, protected, loaded.operation, loaded.plan, captured))
    521             } else {
    522                 None
    523             }
    524         } else {
    525             None
    526         };
    527         let absence = if retained.as_ref().is_none_or(|value| value.4.is_none()) {
    528             Some(
    529                 RetainedFacts::read(
    530                     self.connection,
    531                     self.selected,
    532                     request.binding(),
    533                     request.operation_id(),
    534                     Some(request.command_digest()),
    535                     self.crypto,
    536                 )
    537                 .await?,
    538             )
    539         } else {
    540             None
    541         };
    542         let mut transaction = self
    543             .connection
    544             .begin_with("BEGIN IMMEDIATE")
    545             .await
    546             .map_err(|_| OperationError::StorageFailure)?;
    547         let checked: Result<(), OperationError> = async {
    548             recheck(
    549                 &mut transaction,
    550                 self.namespace,
    551                 self.selected,
    552                 &grant,
    553                 &record,
    554                 request.binding(),
    555                 &proof,
    556                 self.clock,
    557             )
    558             .await?;
    559             if let Some(absence) = &absence {
    560                 absence
    561                     .unchanged(&mut transaction, self.selected, request.operation_id())
    562                     .await?;
    563             }
    564             if let Some((snapshot, protected, operation, plan, captured)) = &retained {
    565                 operation::unchanged(
    566                     &mut transaction,
    567                     snapshot.bound_plan().prepared(),
    568                     operation,
    569                 )
    570                 .await?;
    571                 plan::unchanged(
    572                     &mut transaction,
    573                     snapshot.bound_plan().prepared(),
    574                     Some(plan),
    575                 )
    576                 .await?;
    577                 attempt::unchanged(&mut transaction, snapshot, protected).await?;
    578                 evidence::unchanged(
    579                     &mut transaction,
    580                     snapshot,
    581                     captured.as_ref().map(|value| &value.1),
    582                 )
    583                 .await?;
    584             } else {
    585                 absent_claim(
    586                     &mut transaction,
    587                     self.selected,
    588                     request.operation_id(),
    589                     request.target(),
    590                 )
    591                 .await?;
    592             }
    593             Ok(())
    594         }
    595         .await;
    596         if transaction.rollback().await.is_err() {
    597             *self.uncertain = true;
    598             return Err(OperationError::RecoveryRequired);
    599         }
    600         checked?;
    601         match retained {
    602             Some((attempt, _, _, _, Some((evidence, protected)))) => {
    603                 Ok(Some(CapturedArtifact::from_committed_store(
    604                     attempt,
    605                     evidence,
    606                     protected.receipt.transaction_id(),
    607                 )?))
    608             }
    609             _ => Ok(None),
    610         }
    611     }
    612 }
    613 pub(super) async fn absent_claim(
    614     connection: &mut SqliteConnection,
    615     selected: &AttachmentInput,
    616     operation: OperationId,
    617     target: impl Into<SigningTarget>,
    618 ) -> Result<(), OperationError> {
    619     let target = target.into();
    620     let count:i64=sqlx::query_scalar(attempt::sql(connection, "SELECT (SELECT count(*) FROM signing_attempts WHERE workspace=?1 AND operation_id=?2 AND recipient=?3)+(SELECT count(*) FROM seal_evidence WHERE workspace=?1 AND operation_id=?2 AND recipient=?3)+(SELECT count(*) FROM seal_evidence_parts WHERE workspace=?1 AND operation_id=?2 AND recipient=?3)").await?)
    621         .bind(selected.workspace_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(target.key().as_slice()).fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?;
    622     if count != 0 {
    623         return Err(OperationError::RecoveryRequired);
    624     }
    625     Ok(())
    626 }