lib

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

issuance.rs (9714B)


      1 //! Opaque original claim and obtained-evidence metadata for protecting hosts.
      2 //! Decoding supplies no current access, actual commit or dispatch permission.
      3 use super::plan::PART_BYTES;
      4 use crate::command::{ArtifactEvidence, BoundSigningPlan, OperationError, SigningAttempt};
      5 use core::num::NonZeroU64;
      6 use radroots_domain::{
      7     CommandDigest, EnvelopeEventId, GrantId, OperationId, PublicKey, SigningAttemptId,
      8     TransactionId, UnixSeconds, WorkspaceId,
      9 };
     10 use radroots_protocol::plan::SigningTarget;
     11 use serde::{Deserialize, Serialize};
     12 use zeroize::Zeroizing;
     13 
     14 #[derive(Serialize, Deserialize, Eq, PartialEq)]
     15 #[serde(deny_unknown_fields)]
     16 struct ClaimWire {
     17     version: u8,
     18     workspace: WorkspaceId,
     19     operation_id: OperationId,
     20     command_digest: CommandDigest,
     21     plan_digest: [u8; 32],
     22     #[serde(deserialize_with = "required_recipient")]
     23     recipient: Option<PublicKey>,
     24     #[serde(
     25         default,
     26         skip_serializing_if = "Option::is_none",
     27         deserialize_with = "present_role"
     28     )]
     29     role: Option<u8>,
     30     attempt_id: SigningAttemptId,
     31     transaction_id: TransactionId,
     32     claimed_at: UnixSeconds,
     33     intent_digest: [u8; 32],
     34     deadline_unix_ms: u64,
     35     preparation_transaction: TransactionId,
     36     plan_transaction: TransactionId,
     37     grant_id: GrantId,
     38     expected_event: EnvelopeEventId,
     39 }
     40 impl ClaimWire {
     41     fn new(attempt: &SigningAttempt) -> Result<Self, OperationError> {
     42         let plan = attempt.bound_plan();
     43         let prepared = plan.prepared();
     44         let identity = prepared.identity();
     45         Ok(Self {
     46             version: version(attempt.target()),
     47             workspace: identity.workspace_id(),
     48             operation_id: identity.operation_id(),
     49             command_digest: identity.command_digest(),
     50             plan_digest: *plan.plan().digest(),
     51             recipient: attempt.target().recipient(),
     52             role: role(attempt.target()),
     53             attempt_id: attempt.attempt_id(),
     54             transaction_id: attempt.transaction_id(),
     55             claimed_at: attempt.claimed_at(),
     56             intent_digest: *attempt.binding().digest(),
     57             deadline_unix_ms: attempt.deadline_unix_ms().get(),
     58             preparation_transaction: prepared.transaction_id(),
     59             plan_transaction: plan.transaction_id(),
     60             grant_id: prepared.request().binding().input().grant_id(),
     61             expected_event: EnvelopeEventId::from_bytes(attempt.artifact()?.event_id()),
     62         })
     63     }
     64 }
     65 /// Closed v1 claim codec. The concrete host still verifies its retained indexes
     66 /// and acknowledges actual completion before reporting a newly claimed attempt.
     67 pub struct ClaimRecord(ClaimWire);
     68 impl ClaimRecord {
     69     pub fn capture(attempt: &SigningAttempt) -> Result<Self, OperationError> {
     70         Ok(Self(ClaimWire::new(attempt)?))
     71     }
     72     pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>, OperationError> {
     73         encode(&self.0)
     74     }
     75     pub fn decode(
     76         raw: &[u8],
     77         bound: BoundSigningPlan,
     78         target: impl Into<SigningTarget>,
     79     ) -> Result<SigningAttempt, OperationError> {
     80         if raw.len() > PART_BYTES {
     81             return Err(OperationError::RecoveryRequired);
     82         }
     83         let wire: ClaimWire =
     84             serde_json::from_slice(raw).map_err(|_| OperationError::RecoveryRequired)?;
     85         let attempt = SigningAttempt::from_committed_store(
     86             bound,
     87             target,
     88             wire.attempt_id,
     89             wire.transaction_id,
     90             wire.claimed_at,
     91         )?;
     92         if wire != ClaimWire::new(&attempt)? {
     93             return Err(OperationError::RecoveryRequired);
     94         }
     95         Ok(attempt)
     96     }
     97 }
     98 #[derive(Serialize, Deserialize)]
     99 #[serde(deny_unknown_fields)]
    100 struct EvidenceWire {
    101     version: u8,
    102     workspace: WorkspaceId,
    103     operation_id: OperationId,
    104     command_digest: CommandDigest,
    105     plan_digest: [u8; 32],
    106     #[serde(deserialize_with = "required_recipient")]
    107     recipient: Option<PublicKey>,
    108     #[serde(
    109         default,
    110         skip_serializing_if = "Option::is_none",
    111         deserialize_with = "present_role"
    112     )]
    113     role: Option<u8>,
    114     attempt_id: SigningAttemptId,
    115     claim_transaction: TransactionId,
    116     intent_digest: [u8; 32],
    117     event_id: EnvelopeEventId,
    118     evidence_digest: [u8; 32],
    119     transaction_id: TransactionId,
    120     observed_at: Option<u64>,
    121     byte_count: usize,
    122     part_count: usize,
    123 }
    124 /// Complete authenticated obtained-seal metadata, preserving the original
    125 /// optional observation. Each clear part remains independently bounded.
    126 pub struct EvidenceManifest(EvidenceWire);
    127 impl EvidenceManifest {
    128     pub fn capture(
    129         attempt: &SigningAttempt,
    130         evidence: &ArtifactEvidence,
    131         transaction: TransactionId,
    132     ) -> Result<Self, OperationError> {
    133         if !evidence.matches_attempt(attempt) {
    134             return Err(OperationError::InvalidEvidence);
    135         }
    136         let result = Self(EvidenceWire {
    137             version: version(evidence.target()),
    138             workspace: evidence.workspace_id(),
    139             operation_id: evidence.operation_id(),
    140             command_digest: evidence.command_digest(),
    141             plan_digest: *evidence.plan_digest(),
    142             recipient: evidence.target().recipient(),
    143             role: role(evidence.target()),
    144             attempt_id: evidence.attempt_id(),
    145             claim_transaction: attempt.transaction_id(),
    146             intent_digest: *evidence.intent().digest(),
    147             event_id: evidence.event_id(),
    148             evidence_digest: *evidence.digest(),
    149             transaction_id: transaction,
    150             observed_at: evidence.observed_at_unix_ms().map(NonZeroU64::get),
    151             byte_count: evidence.raw_json().len(),
    152             part_count: evidence.raw_json().len().div_ceil(PART_BYTES),
    153         });
    154         result.validate(attempt)?;
    155         Ok(result)
    156     }
    157     pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>, OperationError> {
    158         encode(&self.0)
    159     }
    160     pub fn decode(raw: &[u8], attempt: &SigningAttempt) -> Result<Self, OperationError> {
    161         if raw.len() > PART_BYTES {
    162             return Err(OperationError::RecoveryRequired);
    163         }
    164         let result =
    165             Self(serde_json::from_slice(raw).map_err(|_| OperationError::RecoveryRequired)?);
    166         result.validate(attempt)?;
    167         Ok(result)
    168     }
    169     fn validate(&self, attempt: &SigningAttempt) -> Result<(), OperationError> {
    170         let w = &self.0;
    171         let bound = attempt.bound_plan();
    172         let identity = bound.prepared().identity();
    173         if w.version != version(attempt.target())
    174             || w.role != role(attempt.target())
    175             || w.workspace != identity.workspace_id()
    176             || w.operation_id != identity.operation_id()
    177             || w.command_digest != identity.command_digest()
    178             || &w.plan_digest != bound.plan().digest()
    179             || w.recipient != attempt.target().recipient()
    180             || w.attempt_id != attempt.attempt_id()
    181             || w.claim_transaction != attempt.transaction_id()
    182             || &w.intent_digest != attempt.binding().digest()
    183             || w.event_id.as_bytes() != &attempt.artifact()?.event_id()
    184             || !(1..=65536).contains(&w.byte_count)
    185             || !(1..=4).contains(&w.part_count)
    186             || w.byte_count.div_ceil(PART_BYTES) != w.part_count
    187             || w.observed_at
    188                 .is_some_and(|t| t == 0 || t > 253_402_300_799_999)
    189         {
    190             return Err(OperationError::RecoveryRequired);
    191         }
    192         Ok(())
    193     }
    194     pub const fn transaction_id(&self) -> TransactionId {
    195         self.0.transaction_id
    196     }
    197     pub const fn attempt_id(&self) -> SigningAttemptId {
    198         self.0.attempt_id
    199     }
    200     pub const fn event_id(&self) -> EnvelopeEventId {
    201         self.0.event_id
    202     }
    203     pub const fn evidence_digest(&self) -> &[u8; 32] {
    204         &self.0.evidence_digest
    205     }
    206     pub const fn byte_count(&self) -> usize {
    207         self.0.byte_count
    208     }
    209     pub const fn part_count(&self) -> usize {
    210         self.0.part_count
    211     }
    212     pub fn verify(
    213         &self,
    214         attempt: &SigningAttempt,
    215         raw: &str,
    216     ) -> Result<ArtifactEvidence, OperationError> {
    217         self.validate(attempt)?;
    218         if raw.len() != self.byte_count() {
    219             return Err(OperationError::RecoveryRequired);
    220         }
    221         let evidence =
    222             ArtifactEvidence::verify(attempt, raw, self.0.observed_at.and_then(NonZeroU64::new))
    223                 .map_err(|_| OperationError::RecoveryRequired)?;
    224         if evidence.digest() != self.evidence_digest() {
    225             return Err(OperationError::RecoveryRequired);
    226         }
    227         Ok(evidence)
    228     }
    229 }
    230 fn encode(value: &impl Serialize) -> Result<Zeroizing<Vec<u8>>, OperationError> {
    231     let raw =
    232         Zeroizing::new(serde_json::to_vec(value).map_err(|_| OperationError::RecoveryRequired)?);
    233     if raw.len() > PART_BYTES {
    234         return Err(OperationError::RecoveryRequired);
    235     }
    236     Ok(raw)
    237 }
    238 
    239 // Private v1 bytes remain unchanged. Public v2 explicitly carries role 0 and a
    240 // required null recipient; omitted/null roles never masquerade as public data.
    241 fn version(target: SigningTarget) -> u8 {
    242     match target {
    243         SigningTarget::PublicEvent => 2,
    244         SigningTarget::BusinessSeal(_) => 1,
    245     }
    246 }
    247 fn role(target: SigningTarget) -> Option<u8> {
    248     match target {
    249         SigningTarget::PublicEvent => Some(0),
    250         SigningTarget::BusinessSeal(_) => None,
    251     }
    252 }
    253 fn required_recipient<'de, D: serde::Deserializer<'de>>(
    254     d: D,
    255 ) -> Result<Option<PublicKey>, D::Error> {
    256     Option::<PublicKey>::deserialize(d)
    257 }
    258 fn present_role<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u8>, D::Error> {
    259     u8::deserialize(d).map(Some)
    260 }