lib

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

snapshot.rs (16824B)


      1 //! One authenticated coherent observation of the complete retained T0/T1/S graph.
      2 use super::{
      3     AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceCrypto,
      4     admission::{Journal, recheck, same_binding},
      5     attempt,
      6     crypto::IssuanceScope,
      7     delivery::{graph::Graph as DeliveryGraph, observation::Observations},
      8     evidence::{self, ProtectedEvidence},
      9     installation::Records,
     10     issuance::absent_claim,
     11     operation, plan,
     12     plan::ProtectedPlan,
     13 };
     14 use radroots_domain::{CommandDigest, EnvelopeEventId, OperationId, PublicKey, UnixSeconds};
     15 use radroots_storage::command::SigningTarget;
     16 use radroots_storage::command::{
     17     ArtifactEvidence, ArtifactSnapshot, BoundSigningPlan, ClaimSnapshot, DeliveryAttemptSummary,
     18     OperationError, OperationSnapshot, RetainedOperation, SigningAttempt,
     19 };
     20 use sqlx::{Connection, SqliteConnection};
     21 
     22 struct SeenArtifact {
     23     report: ArtifactSnapshot,
     24     claim: Option<Vec<u8>>,
     25     evidence: Option<ProtectedEvidence>,
     26     obtained: Option<ArtifactEvidence>,
     27 }
     28 pub(super) struct RetainedGraph {
     29     retained: Option<(RetainedOperation, operation::ProtectedOperation)>,
     30     protected_plan: Option<ProtectedPlan>,
     31     artifacts: Vec<SeenArtifact>,
     32 }
     33 impl RetainedGraph {
     34     pub(super) fn obtained_artifact(&self, target: SigningTarget) -> Option<&ArtifactEvidence> {
     35         self.artifacts
     36             .iter()
     37             .find(|v| v.report.target() == target)
     38             .and_then(|v| v.obtained.as_ref())
     39     }
     40     pub(super) fn obtained(&self, recipient: PublicKey) -> Option<&ArtifactEvidence> {
     41         self.artifacts
     42             .iter()
     43             .find(|seen| seen.report.target().recipient() == Some(recipient))
     44             .and_then(|seen| seen.obtained.as_ref())
     45     }
     46     pub(super) fn bound_plan(&self) -> Option<&BoundSigningPlan> {
     47         self.retained
     48             .as_ref()
     49             .and_then(|(value, _)| value.bound_plan())
     50     }
     51     pub(super) fn reports(&self) -> impl Iterator<Item = ArtifactSnapshot> + '_ {
     52         self.artifacts.iter().map(|value| value.report)
     53     }
     54     pub(super) async fn read(
     55         connection: &mut SqliteConnection,
     56         selected: &AttachmentInput,
     57         binding: &WorkspaceBinding,
     58         operation_id: OperationId,
     59         expected_digest: Option<CommandDigest>,
     60         crypto: &WorkspaceCrypto,
     61     ) -> Result<Self, OperationError> {
     62         let original = operation::read(connection, selected, operation_id, crypto).await?;
     63         let mut artifacts = Vec::new();
     64         let mut protected_plan = None;
     65         let retained = if let Some((prepared, protected)) = original {
     66             operation::check_digest(&prepared, binding.actor(), expected_digest)?;
     67             same_binding(prepared.request().binding(), binding)?;
     68             let (prepared, bound) = plan::read(connection, selected, prepared, crypto).await?;
     69             let source = if let Some((plan, transaction, time, protected)) = bound {
     70                 protected_plan = Some(protected);
     71                 let mut bound =
     72                     BoundSigningPlan::from_committed_store(prepared, plan, transaction, time)?;
     73                 let keys = match bound.plan().chat() {
     74                     Some(plan) => plan
     75                         .seals()
     76                         .iter()
     77                         .map(|seal| SigningTarget::BusinessSeal(seal.recipient()))
     78                         .collect::<Vec<_>>(),
     79                     None => vec![SigningTarget::PublicEvent],
     80                 };
     81                 for recipient in keys {
     82                     let (returned, claim) =
     83                         attempt::read(connection, selected, bound, recipient, crypto).await?;
     84                     let expected = EnvelopeEventId::from_bytes(
     85                         returned
     86                             .plan()
     87                             .artifact(recipient)
     88                             .map_err(|_| OperationError::RecoveryRequired)?
     89                             .event_id(),
     90                     );
     91                     if let Some((id, transaction, time, protected)) = claim {
     92                         let attempt = SigningAttempt::from_committed_store(
     93                             returned,
     94                             recipient,
     95                             id,
     96                             transaction,
     97                             time,
     98                         )?;
     99                         let captured = evidence::read(connection, &attempt, crypto).await?;
    100                         let claim = ClaimSnapshot::from_store_report(&attempt)?;
    101                         let (obtained, evidence, original) = match captured {
    102                             Some((value, protected)) => {
    103                                 (Some(protected.receipt), Some(protected), Some(value))
    104                             }
    105                             None => (None, None, None),
    106                         };
    107                         artifacts.push(SeenArtifact {
    108                             report: ArtifactSnapshot::from_store_report(
    109                                 recipient,
    110                                 Some(expected),
    111                                 Some(claim),
    112                                 obtained,
    113                             ),
    114                             claim: Some(protected),
    115                             evidence,
    116                             obtained: original,
    117                         });
    118                         bound = attempt.into_bound_plan();
    119                     } else {
    120                         artifacts.push(SeenArtifact {
    121                             report: ArtifactSnapshot::from_store_report(
    122                                 recipient,
    123                                 Some(expected),
    124                                 None,
    125                                 None,
    126                             ),
    127                             claim: None,
    128                             evidence: None,
    129                             obtained: None,
    130                         });
    131                         bound = returned;
    132                     }
    133                 }
    134                 RetainedOperation::Planned(Box::new(bound))
    135             } else {
    136                 let mut keys = match prepared.request().command().chat() {
    137                     Some(command) => vec![
    138                         SigningTarget::BusinessSeal(command.context().actor().participant()),
    139                         SigningTarget::BusinessSeal(command.peer()),
    140                     ],
    141                     None => vec![SigningTarget::PublicEvent],
    142                 };
    143                 keys.sort_unstable_by_key(|target| target.key());
    144                 keys.dedup();
    145                 for recipient in keys {
    146                     artifacts.push(SeenArtifact {
    147                         report: ArtifactSnapshot::from_store_report(recipient, None, None, None),
    148                         claim: None,
    149                         evidence: None,
    150                         obtained: None,
    151                     });
    152                 }
    153                 RetainedOperation::Prepared(prepared)
    154             };
    155             Some((source, protected))
    156         } else {
    157             None
    158         };
    159         Ok(Self {
    160             retained,
    161             protected_plan,
    162             artifacts,
    163         })
    164     }
    165     pub(super) async fn unchanged(
    166         &self,
    167         connection: &mut SqliteConnection,
    168         selected: &AttachmentInput,
    169         operation_id: OperationId,
    170     ) -> Result<(), OperationError> {
    171         if let Some((source, protected)) = &self.retained {
    172             operation::unchanged(connection, source.prepared(), protected).await?;
    173             plan::unchanged(connection, source.prepared(), self.protected_plan.as_ref()).await?;
    174             for seen in &self.artifacts {
    175                 if let (Some(claim), Some(protected)) = (seen.report.claim(), &seen.claim) {
    176                     attempt::unchanged_snapshot(connection, claim, protected).await?;
    177                     let scope = IssuanceScope {
    178                         workspace: claim.workspace_id(),
    179                         operation: claim.operation_id(),
    180                         plan_digest: *claim.plan_digest(),
    181                         attempt: claim.attempt_id(),
    182                         target: claim.target(),
    183                     };
    184                     evidence::unchanged_scope(connection, scope, seen.evidence.as_ref()).await?;
    185                 } else {
    186                     absent_claim(connection, selected, operation_id, seen.report.target()).await?;
    187                 }
    188             }
    189             graph_counts(
    190                 connection,
    191                 selected.workspace_id().as_bytes(),
    192                 operation_id.as_bytes(),
    193                 &self.artifacts,
    194             )
    195             .await?;
    196         } else {
    197             let count:i64=sqlx::query_scalar(attempt::sql(connection, "SELECT EXISTS(SELECT 1 FROM operations WHERE workspace=?1 AND operation_id=?2)+EXISTS(SELECT 1 FROM signing_plans WHERE workspace=?1 AND operation_id=?2)+EXISTS(SELECT 1 FROM signing_plan_parts WHERE workspace=?1 AND operation_id=?2)+EXISTS(SELECT 1 FROM signing_attempts WHERE workspace=?1 AND operation_id=?2)+EXISTS(SELECT 1 FROM seal_evidence WHERE workspace=?1 AND operation_id=?2)+EXISTS(SELECT 1 FROM seal_evidence_parts WHERE workspace=?1 AND operation_id=?2)").await?)
    198                     .bind(selected.workspace_id().as_bytes().as_slice()).bind(operation_id.as_bytes().as_slice()).fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?;
    199             if count != 0 {
    200                 return Err(OperationError::RecoveryRequired);
    201             }
    202         }
    203         Ok(())
    204     }
    205     pub(super) fn into_snapshot(
    206         self,
    207         observed: UnixSeconds,
    208     ) -> Result<Option<OperationSnapshot>, OperationError> {
    209         match self.retained {
    210             Some((source, _)) => OperationSnapshot::from_store_report(
    211                 source,
    212                 self.artifacts.into_iter().map(|seen| seen.report).collect(),
    213                 observed,
    214             )
    215             .map(Some),
    216             None => Ok(None),
    217         }
    218     }
    219 }
    220 /// Complete authenticated retained facts, read outside a transaction and
    221 /// compared together inside it. Absence of an earlier phase is not safe to
    222 /// report or replace while any later phase still depends on that history.
    223 pub(super) struct RetainedFacts {
    224     graph: RetainedGraph,
    225     records: Records,
    226     listing: super::listing_installation::Records,
    227     deliveries: DeliveryGraph,
    228     observations: Observations,
    229 }
    230 impl RetainedFacts {
    231     pub(super) fn graph(&self) -> &RetainedGraph {
    232         &self.graph
    233     }
    234     pub(super) fn listing(&self) -> &super::listing_installation::Records {
    235         &self.listing
    236     }
    237 
    238     pub(super) async fn read(
    239         connection: &mut SqliteConnection,
    240         selected: &AttachmentInput,
    241         binding: &WorkspaceBinding,
    242         operation: OperationId,
    243         digest: Option<CommandDigest>,
    244         crypto: &WorkspaceCrypto,
    245     ) -> Result<Self, OperationError> {
    246         let graph =
    247             RetainedGraph::read(connection, selected, binding, operation, digest, crypto).await?;
    248         Self::from_graph(connection, selected, operation, graph, crypto).await
    249     }
    250     pub(super) async fn from_graph(
    251         connection: &mut SqliteConnection,
    252         selected: &AttachmentInput,
    253         operation: OperationId,
    254         graph: RetainedGraph,
    255         crypto: &WorkspaceCrypto,
    256     ) -> Result<Self, OperationError> {
    257         let records = Records::read(connection, selected, operation, &graph, crypto).await?;
    258         let listing = super::listing_installation::Records::read(
    259             connection, selected, operation, &graph, crypto,
    260         )
    261         .await?;
    262         let deliveries = DeliveryGraph::read(
    263             connection, selected, operation, &graph, &records, &listing, crypto,
    264         )
    265         .await?;
    266         let observations =
    267             Observations::read(connection, &deliveries, selected, operation, crypto).await?;
    268         Ok(Self {
    269             graph,
    270             records,
    271             listing,
    272             deliveries,
    273             observations,
    274         })
    275     }
    276     pub(super) async fn unchanged(
    277         &self,
    278         connection: &mut SqliteConnection,
    279         selected: &AttachmentInput,
    280         operation: OperationId,
    281     ) -> Result<(), OperationError> {
    282         self.graph
    283             .unchanged(connection, selected, operation)
    284             .await?;
    285         self.records
    286             .unchanged(connection, selected, operation)
    287             .await?;
    288         self.listing
    289             .unchanged(connection, selected, operation)
    290             .await?;
    291         self.deliveries
    292             .unchanged(connection, selected, operation)
    293             .await?;
    294         self.observations
    295             .unchanged(connection, selected, operation)
    296             .await
    297     }
    298     fn into_snapshot(
    299         self,
    300         observed: UnixSeconds,
    301     ) -> Result<Option<OperationSnapshot>, OperationError> {
    302         self.graph
    303             .into_snapshot(observed)?
    304             .map(|snapshot| {
    305                 snapshot
    306                     .with_installation(
    307                         self.records.message.map(|value| value.report),
    308                         self.records
    309                             .work
    310                             .into_iter()
    311                             .map(|value| value.report)
    312                             .collect(),
    313                     )?
    314                     .with_public_installation(
    315                         self.listing.installation(),
    316                         self.listing.work().into_iter().collect(),
    317                     )?
    318                     .with_delivery(
    319                         self.deliveries
    320                             .attempts
    321                             .iter()
    322                             .map(DeliveryAttemptSummary::from_attempt)
    323                             .collect(),
    324                         self.observations.reports,
    325                     )
    326             })
    327             .transpose()
    328     }
    329 }
    330 impl Journal<'_> {
    331     pub(super) async fn query_snapshot(
    332         &mut self,
    333         binding: WorkspaceBinding,
    334         operation_id: OperationId,
    335         expected_digest: Option<CommandDigest>,
    336         proof: AttachmentProof,
    337     ) -> Result<Option<OperationSnapshot>, OperationError> {
    338         let (record, grant, _) = self.access(&binding, &proof).await?;
    339         let facts = RetainedFacts::read(
    340             self.connection,
    341             self.selected,
    342             &binding,
    343             operation_id,
    344             expected_digest,
    345             self.crypto,
    346         )
    347         .await?;
    348         // Provider and signature verification work precedes the transaction.
    349         let mut transaction = self
    350             .connection
    351             .begin_with("BEGIN IMMEDIATE")
    352             .await
    353             .map_err(|_| OperationError::StorageFailure)?;
    354         let checked = async {
    355             let observed = recheck(
    356                 &mut transaction,
    357                 self.namespace,
    358                 self.selected,
    359                 &grant,
    360                 &record,
    361                 &binding,
    362                 &proof,
    363                 self.clock,
    364             )
    365             .await?;
    366             facts
    367                 .unchanged(&mut transaction, self.selected, operation_id)
    368                 .await?;
    369             Ok::<_, OperationError>(observed.observed_at())
    370         }
    371         .await;
    372         if transaction.rollback().await.is_err() {
    373             *self.uncertain = true;
    374             return Err(OperationError::RecoveryRequired);
    375         }
    376         facts.into_snapshot(checked?)
    377     }
    378 }
    379 async fn graph_counts(
    380     connection: &mut SqliteConnection,
    381     workspace: &[u8; 32],
    382     operation: &[u8; 32],
    383     artifacts: &[SeenArtifact],
    384 ) -> Result<(), OperationError> {
    385     // The valid graph has at most two claims, two obtained manifests and eight
    386     // data parts. One excess sentinel is sufficient to reject arbitrary extras.
    387     let counts:(i64,i64,i64)=sqlx::query_as(attempt::sql(connection, "SELECT (SELECT count(*) FROM (SELECT 1 FROM signing_attempts WHERE workspace=?1 AND operation_id=?2 LIMIT 3)),(SELECT count(*) FROM (SELECT 1 FROM seal_evidence WHERE workspace=?1 AND operation_id=?2 LIMIT 3)),(SELECT count(*) FROM (SELECT 1 FROM seal_evidence_parts WHERE workspace=?1 AND operation_id=?2 LIMIT 9))").await?)
    388         .bind(workspace.as_slice()).bind(operation.as_slice()).fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?;
    389     let claims = artifacts.iter().filter(|seen| seen.claim.is_some()).count() as i64;
    390     let evidence = artifacts
    391         .iter()
    392         .filter(|seen| seen.evidence.is_some())
    393         .count() as i64;
    394     let parts = artifacts
    395         .iter()
    396         .filter_map(|seen| seen.evidence.as_ref())
    397         .map(|value| value.parts.len() as i64)
    398         .sum::<i64>();
    399     if counts != (claims, evidence, parts) {
    400         return Err(OperationError::RecoveryRequired);
    401     }
    402     Ok(())
    403 }