lib

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

issuance.rs (25136B)


      1 //! Real S claims and append-only obtained output; no signer runs under storage.
      2 use super::journal::{OperationChange, Records, mutations, storage_error};
      3 use super::{BrowserWorkspace, Mutation, State, WorkspaceError, address, crypto, owned};
      4 use crate::ReadSnapshot;
      5 use radroots_domain::{CommandDigest, OperationId, SigningAttemptId, TransactionId};
      6 use radroots_secrets::context::{
      7     EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId,
      8 };
      9 use radroots_storage::{
     10     command::{
     11         ArtifactEvidence, BoundSigningPlan, CapturedArtifact, ClaimAttemptOutcome,
     12         ClaimAttemptRequest, CommitAttempt, EvidenceCaptureOutcome, EvidenceReceipt,
     13         OperationError, SigningAttempt, SigningTarget,
     14         protected::{
     15             self,
     16             issuance::{ClaimRecord, EvidenceManifest},
     17             plan::PART_BYTES,
     18         },
     19     },
     20     workspace::{AttachmentInput, AttachmentProof},
     21 };
     22 use sha2::{Digest, Sha256};
     23 use zeroize::Zeroizing;
     24 
     25 pub(super) enum Claim {
     26     Absent(BoundSigningPlan, u8),
     27     Present(Box<SigningAttempt>),
     28 }
     29 pub(super) fn position(
     30     bound: &BoundSigningPlan,
     31     target: SigningTarget,
     32 ) -> Result<Option<u8>, OperationError> {
     33     if target == SigningTarget::PublicEvent {
     34         return Ok(bound.plan().listing().map(|_| 2));
     35     }
     36     let Some(chat) = bound.plan().chat() else {
     37         return Ok(None);
     38     };
     39     Ok(chat
     40         .seals()
     41         .iter()
     42         .position(|seal| Some(seal.recipient()) == target.recipient())
     43         .and_then(|i| u8::try_from(i).ok()))
     44 }
     45 pub(super) fn target(bound: &BoundSigningPlan, index: u8) -> Result<SigningTarget, OperationError> {
     46     if index == 2 && bound.plan().listing().is_some() {
     47         return Ok(SigningTarget::PublicEvent);
     48     }
     49     let chat = bound.chat_plan()?;
     50     chat.seals()
     51         .get(index as usize)
     52         .map(|seal| SigningTarget::BusinessSeal(seal.recipient()))
     53         .ok_or(OperationError::RecoveryRequired)
     54 }
     55 fn base(state: &State, bound: &BoundSigningPlan, index: u8) -> Result<Sha256, OperationError> {
     56     let identity = bound.prepared().identity();
     57     let target = target(bound, index)?;
     58     if target == SigningTarget::PublicEvent {
     59         return Ok(Sha256::new()
     60             .chain_update(b"radroots.browser.local_outbox.public_issuance.context.v1\0")
     61             .chain_update(state.selected.workspace_id().as_bytes())
     62             .chain_update(identity.operation_id().as_bytes())
     63             .chain_update(bound.plan().digest())
     64             .chain_update([index]));
     65     }
     66     Ok(Sha256::new()
     67         .chain_update(b"radroots.browser.local_outbox.issuance.context.v2\0")
     68         .chain_update(state.selected.workspace_id().as_bytes())
     69         .chain_update(identity.operation_id().as_bytes())
     70         .chain_update(bound.plan().digest())
     71         .chain_update(
     72             target
     73                 .recipient()
     74                 .ok_or(OperationError::RecoveryRequired)?
     75                 .as_bytes(),
     76         )
     77         .chain_update([index]))
     78 }
     79 fn finish(hash: Sha256, schema: &str) -> Result<EnvelopeContext, OperationError> {
     80     let subject = hash
     81         .finalize()
     82         .iter()
     83         .map(|b| format!("{b:02x}"))
     84         .collect::<String>();
     85     Ok(EnvelopeContext::new(
     86         EnvelopePurpose::parse("radroots.browser.workspace.issuance")
     87             .map_err(|_| OperationError::InvalidCommand)?,
     88         EnvelopeSubject::parse("workspace_issuance", subject)
     89             .map_err(|_| OperationError::InvalidCommand)?,
     90         PayloadSchemaId::parse(schema).map_err(|_| OperationError::InvalidCommand)?,
     91     ))
     92 }
     93 fn claim_context(
     94     state: &State,
     95     bound: &BoundSigningPlan,
     96     index: u8,
     97 ) -> Result<EnvelopeContext, OperationError> {
     98     finish(
     99         base(state, bound, index)?.chain_update(b"claim\0"),
    100         "radroots.browser.workspace.claim.v2",
    101     )
    102 }
    103 fn evidence_context(
    104     state: &State,
    105     attempt: &SigningAttempt,
    106     index: u8,
    107     part: u8,
    108     digest: Option<&[u8; 32]>,
    109 ) -> Result<EnvelopeContext, OperationError> {
    110     let mut hash = base(state, attempt.bound_plan(), index)?
    111         .chain_update(b"evidence\0")
    112         .chain_update(attempt.attempt_id().as_bytes())
    113         .chain_update([part]);
    114     if let Some(digest) = digest {
    115         hash.update(digest);
    116     }
    117     finish(hash, "radroots.browser.workspace.evidence.v2")
    118 }
    119 impl State {
    120     async fn bound(
    121         &self,
    122         view: &ReadSnapshot,
    123         operation: OperationId,
    124         digest: CommandDigest,
    125         t0: &Records,
    126     ) -> Result<Option<BoundSigningPlan>, OperationError> {
    127         match super::retained::header(self, view, operation, Some(digest), t0).await? {
    128             Some(radroots_storage::command::RetainedOperation::Planned(bound)) => Ok(Some(*bound)),
    129             _ => Ok(None),
    130         }
    131     }
    132     pub(super) async fn claim(
    133         &self,
    134         view: &ReadSnapshot,
    135         bound: BoundSigningPlan,
    136         recipient: SigningTarget,
    137         index: u8,
    138     ) -> Result<Claim, OperationError> {
    139         let operation = bound.prepared().identity().operation_id();
    140         let key = address::key(operation, address::CLAIM, index, 0);
    141         let Some(protected) = self.read_view_key(view, key).await? else {
    142             if view.keys().any(|key| matches!(address::fields(key), Ok((address::EVIDENCE, found, _)) if found == index)) { return Err(OperationError::RecoveryRequired); }
    143             return Ok(Claim::Absent(bound, index));
    144         };
    145         let clear = crypto::open_bound(
    146             self.provider.as_ref(),
    147             &self.reference,
    148             claim_context(self, &bound, index)?,
    149             &protected,
    150         )
    151         .await?;
    152         let attempt = clear.expose_secret(|raw| ClaimRecord::decode(raw, bound, recipient))?;
    153         Ok(Claim::Present(Box::new(attempt)))
    154     }
    155     pub(super) async fn evidence(
    156         &self,
    157         view: &ReadSnapshot,
    158         attempt: &SigningAttempt,
    159         index: u8,
    160     ) -> Result<Option<(ArtifactEvidence, EvidenceReceipt)>, OperationError> {
    161         let operation = attempt.bound_plan().prepared().identity().operation_id();
    162         let mut records = Vec::with_capacity(5);
    163         for part in 0..=4 {
    164             records.push(
    165                 self.read_view_key(
    166                     view,
    167                     address::key(operation, address::EVIDENCE, index, part),
    168                 )
    169                 .await?,
    170             );
    171         }
    172         let Some(manifest) = &records[0] else {
    173             if records.iter().any(Option::is_some) {
    174                 return Err(OperationError::RecoveryRequired);
    175             }
    176             return Ok(None);
    177         };
    178         let raw = crypto::open_bound(
    179             self.provider.as_ref(),
    180             &self.reference,
    181             evidence_context(self, attempt, index, 0, None)?,
    182             manifest,
    183         )
    184         .await?;
    185         let manifest = raw.expose_secret(|raw| EvidenceManifest::decode(raw, attempt))?;
    186         let mut clear = Zeroizing::new(Vec::with_capacity(manifest.byte_count()));
    187         for (part, bytes) in records.iter().enumerate().skip(1) {
    188             if part > manifest.part_count() {
    189                 if bytes.is_some() {
    190                     return Err(OperationError::RecoveryRequired);
    191                 }
    192                 continue;
    193             }
    194             let bytes = bytes.as_ref().ok_or(OperationError::RecoveryRequired)?;
    195             let raw = crypto::open_bound(
    196                 self.provider.as_ref(),
    197                 &self.reference,
    198                 evidence_context(
    199                     self,
    200                     attempt,
    201                     index,
    202                     part as u8,
    203                     Some(manifest.evidence_digest()),
    204                 )?,
    205                 bytes,
    206             )
    207             .await?;
    208             let expected = (manifest.byte_count() - (part - 1) * PART_BYTES).min(PART_BYTES);
    209             raw.expose_secret(|raw| {
    210                 if raw.len() != expected {
    211                     return Err(OperationError::RecoveryRequired);
    212                 }
    213                 clear.extend_from_slice(raw);
    214                 Ok(())
    215             })?;
    216         }
    217         let evidence = manifest.verify(
    218             attempt,
    219             core::str::from_utf8(&clear).map_err(|_| OperationError::RecoveryRequired)?,
    220         )?;
    221         let receipt = EvidenceReceipt::from_committed_store(&evidence, manifest.transaction_id());
    222         Ok(Some((evidence, receipt)))
    223     }
    224     async fn protect_evidence(
    225         &self,
    226         attempt: &SigningAttempt,
    227         index: u8,
    228         supplied: &ArtifactEvidence,
    229         transaction: TransactionId,
    230     ) -> Result<Vec<Mutation>, OperationError> {
    231         let manifest = EvidenceManifest::capture(attempt, supplied, transaction)?;
    232         let operation = supplied.operation_id();
    233         let encoded = manifest.encode()?;
    234         let protected = crypto::seal_bound(
    235             self.provider.as_ref(),
    236             &self.reference,
    237             evidence_context(self, attempt, index, 0, None)?,
    238             &encoded,
    239         )
    240         .await?;
    241         let mut changes = vec![
    242             Mutation::new(
    243                 address::key(operation, address::EVIDENCE, index, 0),
    244                 None,
    245                 Some(protected),
    246             )
    247             .map_err(storage_error)?,
    248         ];
    249         for (part, raw) in supplied
    250             .raw_json()
    251             .as_bytes()
    252             .chunks(PART_BYTES)
    253             .enumerate()
    254         {
    255             let part = part as u8 + 1;
    256             let protected = crypto::seal_bound(
    257                 self.provider.as_ref(),
    258                 &self.reference,
    259                 evidence_context(self, attempt, index, part, Some(supplied.digest()))?,
    260                 raw,
    261             )
    262             .await?;
    263             changes.push(
    264                 Mutation::new(
    265                     address::key(operation, address::EVIDENCE, index, part),
    266                     None,
    267                     Some(protected),
    268                 )
    269                 .map_err(storage_error)?,
    270             );
    271         }
    272         Ok(changes)
    273     }
    274 }
    275 impl BrowserWorkspace {
    276     /// Only an actual newly committed claim reports Claimed. Retained claims
    277     /// are potential prior issuance and must not be dispatched again.
    278     pub async fn claim_attempt(
    279         &self,
    280         request: ClaimAttemptRequest,
    281         proof: AttachmentProof,
    282     ) -> Result<ClaimAttemptOutcome, OperationError> {
    283         let fallback = request.identity();
    284         let work = self.state.admit()?;
    285         let state = self.state.clone();
    286         let result = owned(work, async move {
    287             let access = state.operation_access(request.binding(), proof).await?;
    288             let operation = request.operation_id();
    289             let view = state.read_view(operation).await?;
    290             let t0 = state.operation_records(&view, operation).await?;
    291             let bound = state
    292                 .bound(&view, operation, request.command_digest(), &t0)
    293                 .await?
    294                 .ok_or(OperationError::RecoveryRequired)?;
    295             protected::same_binding(bound.prepared().request().binding(), request.binding())?;
    296             if bound.plan().digest() != request.plan_digest() {
    297                 return Err(OperationError::IdempotencyConflict);
    298             }
    299             let index =
    300                 position(&bound, request.target())?.ok_or(OperationError::InvalidCommand)?;
    301             let (attempt, fresh, extra) =
    302                 match state.claim(&view, bound, request.target(), index).await? {
    303                     Claim::Present(attempt) => (*attempt, false, Vec::new()),
    304                     Claim::Absent(bound, index) => {
    305                         state
    306                             .check_claim_absence(
    307                                 &view,
    308                                 operation,
    309                                 request.command_digest(),
    310                                 &t0,
    311                                 access.binding.observed_at(),
    312                             )
    313                             .await?;
    314                         let now = access.binding.observed_at();
    315                         if now < bound.bound_at() {
    316                             return Err(WorkspaceError::Unavailable.into());
    317                         }
    318                         if now >= bound.prepared().issuance_window().first_issue_not_after() {
    319                             return Err(OperationError::DeadlineExceeded);
    320                         }
    321                         let attempt = SigningAttempt::from_committed_store(
    322                             bound,
    323                             request.target(),
    324                             SigningAttemptId::from_bytes(*crypto::random::<32>()?),
    325                             TransactionId::from_bytes(*crypto::random::<32>()?),
    326                             now,
    327                         )?;
    328                         let encoded = ClaimRecord::capture(&attempt)?.encode()?;
    329                         let protected = crypto::seal_bound(
    330                             state.provider.as_ref(),
    331                             &state.reference,
    332                             claim_context(&state, attempt.bound_plan(), index)?,
    333                             &encoded,
    334                         )
    335                         .await?;
    336                         let extra = vec![
    337                             Mutation::new(
    338                                 address::key(operation, address::CLAIM, index, 0),
    339                                 None,
    340                                 Some(protected),
    341                             )
    342                             .map_err(storage_error)?,
    343                         ];
    344                         (attempt, true, extra)
    345                     }
    346                 };
    347             let anchor = attempt.identity();
    348             let change = OperationChange {
    349                 before: t0,
    350                 after: None,
    351                 window: fresh.then(|| attempt.bound_plan().prepared().issuance_window()),
    352                 delivery_deadline: None,
    353                 extra,
    354             };
    355             match state.check_operation(access, operation, change, view).await {
    356                 Ok(()) => Ok(if fresh {
    357                     ClaimAttemptOutcome::Claimed(attempt)
    358                 } else {
    359                     ClaimAttemptOutcome::Retained(attempt)
    360                 }),
    361                 Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => {
    362                     state.mark_unknown();
    363                     Ok(ClaimAttemptOutcome::Unknown(anchor))
    364                 }
    365                 Err(error) => Err(error),
    366             }
    367         })
    368         .await;
    369         match result {
    370             Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => {
    371                 self.state.mark_unknown();
    372                 Ok(ClaimAttemptOutcome::Unknown(fallback))
    373             }
    374             other => other,
    375         }
    376     }
    377     /// Current-access original claim query; finding a claim authorizes no replay.
    378     pub async fn signing_attempt(
    379         &self,
    380         request: ClaimAttemptRequest,
    381         proof: AttachmentProof,
    382     ) -> Result<Option<SigningAttempt>, OperationError> {
    383         let work = self.state.admit()?;
    384         let state = self.state.clone();
    385         owned(work, async move {
    386             let access = state.operation_access(request.binding(), proof).await?;
    387             let operation = request.operation_id();
    388             let view = state.read_view(operation).await?;
    389             let t0 = state.operation_records(&view, operation).await?;
    390             let result = if let Some(bound) = state
    391                 .bound(&view, operation, request.command_digest(), &t0)
    392                 .await?
    393             {
    394                 protected::same_binding(bound.prepared().request().binding(), request.binding())?;
    395                 if bound.plan().digest() != request.plan_digest() {
    396                     return Err(OperationError::IdempotencyConflict);
    397                 }
    398                 if let Some(index) = position(&bound, request.target())? {
    399                     match state.claim(&view, bound, request.target(), index).await? {
    400                         Claim::Present(attempt) => Some(*attempt),
    401                         Claim::Absent(_, _) => {
    402                             state
    403                                 .check_claim_absence(
    404                                     &view,
    405                                     operation,
    406                                     request.command_digest(),
    407                                     &t0,
    408                                     access.binding.observed_at(),
    409                                 )
    410                                 .await?;
    411                             None
    412                         }
    413                     }
    414                 } else {
    415                     None
    416                 }
    417             } else {
    418                 None
    419             };
    420             state
    421                 .check_operation(access, operation, OperationChange::observe(t0), view)
    422                 .await?;
    423             Ok(result)
    424         })
    425         .await
    426     }
    427     /// Appends already obtained exact output to an actual original claim.
    428     /// No current clock or grant revocation can discard that retained fact.
    429     /// Borrowed original input remains caller-owned through error or lost wait;
    430     /// an accepted driver retains only its bounded protected-work copy.
    431     pub async fn capture_evidence(
    432         &self,
    433         input: AttachmentInput,
    434         proof: &AttachmentProof,
    435         supplied: &ArtifactEvidence,
    436     ) -> Result<EvidenceCaptureOutcome, OperationError> {
    437         let capture_identity = super::recovery::CaptureIdentity::artifact(supplied);
    438         let owned_identity = capture_identity.clone();
    439         let fallback = CommitAttempt::new(
    440             supplied.workspace_id(),
    441             supplied.operation_id(),
    442             supplied.command_digest(),
    443             None,
    444         );
    445         let work = self.state.admit_capture()?;
    446         let state = self.state.clone();
    447         let proof = proof.with_secret(|raw| AttachmentProof::from_protected_input(raw))?;
    448         let supplied = supplied.retained_copy();
    449         let result = owned(work, async move {
    450             let (grant, protected) = state.capture_retained(&input, &proof).await?;
    451             if supplied.workspace_id() != state.selected.workspace_id() {
    452                 return Err(OperationError::InvalidEvidence);
    453             }
    454             let operation = supplied.operation_id();
    455             let view = state.read_view(operation).await?;
    456             let t0 = state.operation_records(&view, operation).await?;
    457             let bound = state
    458                 .bound(&view, operation, supplied.command_digest(), &t0)
    459                 .await?
    460                 .ok_or(OperationError::RecoveryRequired)?;
    461             let index =
    462                 position(&bound, supplied.target())?.ok_or(OperationError::InvalidEvidence)?;
    463             let attempt = match state.claim(&view, bound, supplied.target(), index).await? {
    464                 Claim::Present(attempt) => attempt,
    465                 Claim::Absent(_, _) => return Err(OperationError::RecoveryRequired),
    466             };
    467             if !supplied.matches_attempt(&attempt) {
    468                 return Err(OperationError::InvalidEvidence);
    469             }
    470             let checked = ArtifactEvidence::verify(
    471                 &attempt,
    472                 supplied.raw_json(),
    473                 supplied.observed_at_unix_ms(),
    474             )?;
    475             drop(supplied);
    476             let coordinate = state
    477                 .coordinate_guard(attempt.bound_plan().prepared())
    478                 .await?;
    479             let (receipt, mut extra) = match state.evidence(&view, &attempt, index).await? {
    480                 Some((original, receipt)) => {
    481                     if original.raw_json() != checked.raw_json()
    482                         || original.digest() != checked.digest()
    483                     {
    484                         return Err(OperationError::IdempotencyConflict);
    485                     }
    486                     (receipt, Vec::new())
    487                 }
    488                 None => {
    489                     let transaction = TransactionId::from_bytes(*crypto::random::<32>()?);
    490                     let extra = state
    491                         .protect_evidence(&attempt, index, &checked, transaction)
    492                         .await?;
    493                     (
    494                         EvidenceReceipt::from_committed_store(&checked, transaction),
    495                         extra,
    496                     )
    497                 }
    498             };
    499             let anchor = CommitAttempt::new(
    500                 receipt.workspace_id(),
    501                 operation,
    502                 receipt.command_digest(),
    503                 Some(receipt.transaction_id()),
    504             );
    505             extra.extend(coordinate);
    506             let batch = mutations(protected, operation, t0, None, extra)?;
    507             let active = state.active()?;
    508             match state
    509                 .checked_batch(batch, view, move || {
    510                     if !active.get() {
    511                         return Err(WorkspaceError::Closed.into());
    512                     }
    513                     grant.authenticate_retained_capture(&input, &proof)?;
    514                     Ok(())
    515                 })
    516                 .await
    517             {
    518                 Ok(()) => {
    519                     state.capture_confirmed(&owned_identity);
    520                     Ok(EvidenceCaptureOutcome::Committed(receipt))
    521                 }
    522                 Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => {
    523                     state.mark_capture_unknown(owned_identity);
    524                     Ok(EvidenceCaptureOutcome::Unknown(anchor))
    525                 }
    526                 Err(error) => Err(error),
    527             }
    528         })
    529         .await;
    530         match result {
    531             Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => {
    532                 self.state.mark_capture_unknown(capture_identity);
    533                 Ok(EvidenceCaptureOutcome::Unknown(fallback))
    534             }
    535             other => other,
    536         }
    537     }
    538     /// Reads original verified output under current access; no issuance occurs.
    539     pub async fn obtained_evidence(
    540         &self,
    541         request: ClaimAttemptRequest,
    542         proof: AttachmentProof,
    543     ) -> Result<Option<CapturedArtifact>, OperationError> {
    544         let work = self.state.admit()?;
    545         let state = self.state.clone();
    546         owned(work, async move {
    547             let access = state.operation_access(request.binding(), proof).await?;
    548             let operation = request.operation_id();
    549             let view = state.read_view(operation).await?;
    550             let t0 = state.operation_records(&view, operation).await?;
    551             let result = if let Some(bound) = state
    552                 .bound(&view, operation, request.command_digest(), &t0)
    553                 .await?
    554             {
    555                 protected::same_binding(bound.prepared().request().binding(), request.binding())?;
    556                 if bound.plan().digest() != request.plan_digest() {
    557                     return Err(OperationError::IdempotencyConflict);
    558                 }
    559                 if let Some(index) = position(&bound, request.target())? {
    560                     match state.claim(&view, bound, request.target(), index).await? {
    561                         Claim::Present(attempt) => {
    562                             let obtained = state.evidence(&view, &attempt, index).await?;
    563                             if obtained.is_none() {
    564                                 state
    565                                     .check_claim_absence(
    566                                         &view,
    567                                         operation,
    568                                         request.command_digest(),
    569                                         &t0,
    570                                         access.binding.observed_at(),
    571                                     )
    572                                     .await?;
    573                             }
    574                             obtained
    575                                 .map(|(evidence, receipt)| {
    576                                     CapturedArtifact::from_committed_store(
    577                                         *attempt,
    578                                         evidence,
    579                                         receipt.transaction_id(),
    580                                     )
    581                                 })
    582                                 .transpose()?
    583                         }
    584                         Claim::Absent(_, _) => {
    585                             state
    586                                 .check_claim_absence(
    587                                     &view,
    588                                     operation,
    589                                     request.command_digest(),
    590                                     &t0,
    591                                     access.binding.observed_at(),
    592                                 )
    593                                 .await?;
    594                             None
    595                         }
    596                     }
    597                 } else {
    598                     None
    599                 }
    600             } else {
    601                 None
    602             };
    603             state
    604                 .check_operation(access, operation, OperationChange::observe(t0), view)
    605                 .await?;
    606             Ok(result)
    607         })
    608         .await
    609     }
    610 }