Skip to main content

rusty_agent_runtime/
receipt.rs

1//! Signed run receipts (R0.9 Rusty Capsules, wave 3): an Ed25519-signed
2//! statement over evidence the Flight Recorder already keeps, and the
3//! verification API that re-walks that evidence.
4//!
5//! A [`RunReceipt`] signs:
6//!
7//! - the run id and the **journal head** ([`JournalRef`]) — the chained
8//!   SHA-256 every checkpoint stamps; signing the head signs every event
9//!   in the chain transitively, which is what hash chains are for;
10//! - the **run manifest** ([`RunManifest`]) — prompt, tool-schema, model,
11//!   and memory-schema digests — carried in full for the auditor and
12//!   committed to by `manifest_digest`, plus the **resolved capsule
13//!   content addresses** ([`CapsuleId`]) the journaled resolutions bound
14//!   the run's pins to;
15//! - the **effect ledger** — one digest per journaled
16//!   [`EffectReceipt`] over provider,
17//!   provider id, idempotency key, and effect id, so the receipt covers
18//!   what the run *did to the world*, not just what it computed;
19//! - the **policy versions** — the executor [`PolicyVersion`] the run's
20//!   checkpoint header pinned, plus the Cedar policy versions capsules
21//!   were admitted under;
22//! - the **denials ledger** — the [`RunEventKind::CapsuleDenied`] event
23//!   ids. A receipt over a run that attempted forbidden access says so;
24//!   the visibility of the denial survives into the signed statement;
25//! - `signer` (a content-addressed key id) and `signature` over the
26//!   canonical serialization of all of the above.
27//!
28//! # What a receipt proves, and what it does not
29//!
30//! A verified receipt proves which code, capsule builds, memory schema,
31//! policies, and permissions produced this run's actions — what Rusty
32//! received, authorized, and executed, with the denials attached. It does
33//! **not** prove that an external LLM's answer was truthful, that a tool's
34//! provider behaved honestly, or that a remote agent did what it claimed:
35//! those are claims about systems whose journals Rusty does not hold, and
36//! a signature over Rusty's evidence cannot witness them. The receipt is a
37//! statement about *this runtime's* conduct.
38//!
39//! # Cryptographic honesty
40//!
41//! Ed25519 over locally held keys gives **integrity and origin against a
42//! key the operator holds**: a receipt that verifies was minted by whoever
43//! controlled the signing key, over exactly the evidence named. It gives
44//! nothing more — no non-repudiation against the operator (they hold the
45//! key and can mint any statement), no transparency (a withheld receipt
46//! leaves no trace), no remote attestation (the key proves nothing about
47//! the machine it lives on). KMS integration, transparency-log witnessing,
48//! and attestation are R1.0+; the canonical form
49//! ([`RunReceipt::canonical_bytes`]) is the exact byte string a
50//! transparency log would witness, so that integration lands additively.
51//!
52//! # Verification reuses the journal's digests
53//!
54//! [`verify_receipt`] recomputes the head over the snapshot's event chain
55//! with the journal's own chain step (see
56//! [`crate::journal::Journal::from_snapshot`]), so a receipt's head and
57//! the journal's head are the same bytes by construction — the signature
58//! check is the only new machinery, not a new evidence pipeline. Every
59//! failure is a typed [`ReceiptRejection`] naming the component whose
60//! digest mismatched; verification never answers a bare `false`.
61
62use std::collections::BTreeMap;
63
64use chrono::{DateTime, Utc};
65use serde::{Deserialize, Serialize};
66
67use crate::capsule::{CapsuleId, CapsuleResolution};
68use crate::error::RustyError;
69use crate::journal::JournalSnapshot;
70use crate::record::{
71    canonicalize_value, sha256_hex, EffectReceipt, JournalRef, PayloadRef, PolicyVersion,
72    RunEventKind, RunManifest,
73};
74
75/// The receipt envelope version. Bump only on a breaking change to the
76/// signed statement; additive evolution uses serde defaults so receipts
77/// written by earlier builds keep verifying.
78pub const RECEIPT_FORMAT_VERSION: u32 = 1;
79
80// --------------------------------------------------------------------- //
81// Keys
82// --------------------------------------------------------------------- //
83
84/// A signing key for minting receipts: Ed25519 secret key material, held
85/// locally by the operator's server. The secret never enters the store
86/// abstraction — the server persists it as a `0600` file under
87/// `{store_path}/keys/` and keeps only the public half in the key history,
88/// so a database backend can never hold what it must not leak.
89pub struct SigningKey(ed25519_dalek::SigningKey);
90
91/// A verification key: the public half of a [`SigningKey`]. Key ids are
92/// content addresses of this key ([`derive_key_id`]), so a key id on a
93/// receipt commits to exactly one key.
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub struct PublicKey(ed25519_dalek::VerifyingKey);
96
97impl SigningKey {
98    /// A fresh keypair drawn from OS entropy (two v4 UUID draws — 32 bytes
99    /// of `getrandom` entropy, the same source the runtime's id minting
100    /// already trusts; `ed25519-dalek` carries no RNG feature here).
101    pub fn generate() -> Self {
102        let mut bytes = [0u8; 32];
103        bytes[..16].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
104        bytes[16..].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
105        Self::from_bytes(&bytes)
106    }
107
108    /// Wrap 32 bytes of secret key material (the stored secret-file form).
109    pub fn from_bytes(bytes: &[u8; 32]) -> Self {
110        Self(ed25519_dalek::SigningKey::from_bytes(bytes))
111    }
112
113    /// The 32 secret bytes — what the server's `0600` secret file holds.
114    pub fn to_bytes(&self) -> [u8; 32] {
115        self.0.to_bytes()
116    }
117
118    /// Rehydrate from the hex form ([`SigningKey::to_hex`]).
119    pub fn from_hex(hex: &str) -> Option<Self> {
120        let bytes = hex_decode(hex)?;
121        let bytes: [u8; 32] = bytes.try_into().ok()?;
122        Some(Self::from_bytes(&bytes))
123    }
124
125    /// Lowercase hex of the secret bytes.
126    pub fn to_hex(&self) -> String {
127        hex_encode(&self.0.to_bytes())
128    }
129
130    /// The public half.
131    pub fn public_key(&self) -> PublicKey {
132        PublicKey(self.0.verifying_key())
133    }
134
135    /// This key's content-addressed id ([`derive_key_id`]).
136    pub fn key_id(&self) -> String {
137        derive_key_id(&self.public_key())
138    }
139
140    /// Sign `message`, returning the lowercase-hex signature. Ed25519 is
141    /// deterministic: the same key over the same bytes mints the same
142    /// signature, which is what makes receipt goldens stable.
143    pub fn sign_hex(&self, message: &[u8]) -> String {
144        use ed25519_dalek::Signer as _;
145        hex_encode(&self.0.sign(message).to_bytes())
146    }
147}
148
149// The secret key's Debug prints the key id — a content address of the
150// public half — never the secret material.
151impl std::fmt::Debug for SigningKey {
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        write!(f, "SigningKey(key_id: {})", self.key_id())
154    }
155}
156
157impl Clone for SigningKey {
158    fn clone(&self) -> Self {
159        Self::from_bytes(&self.0.to_bytes())
160    }
161}
162
163impl PublicKey {
164    /// Wrap 32 bytes of public key material. Fails on bytes that are not a
165    /// valid compressed Edwards point — a malformed key is rejected here,
166    /// not at first verification.
167    pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self, RustyError> {
168        ed25519_dalek::VerifyingKey::from_bytes(bytes)
169            .map(Self)
170            .map_err(|e| invalid_key(format!("invalid Ed25519 public key: {e}")))
171    }
172
173    /// The 32 public bytes.
174    pub fn to_bytes(&self) -> [u8; 32] {
175        self.0.to_bytes()
176    }
177
178    /// Rehydrate from the hex form ([`PublicKey::to_hex`]). `None` on
179    /// malformed hex or wrong length; an invalid point is an error.
180    pub fn from_hex(hex: &str) -> Result<Self, RustyError> {
181        let bytes = hex_decode(hex)
182            .ok_or_else(|| invalid_key(format!("public key is not valid hex: `{hex}`")))?;
183        let bytes: [u8; 32] = bytes.try_into().map_err(|_| {
184            invalid_key(format!(
185                "public key must be 32 bytes, got {}",
186                hex.len() / 2
187            ))
188        })?;
189        Self::from_bytes(&bytes)
190    }
191
192    /// Lowercase hex of the public bytes — the form the key history holds.
193    pub fn to_hex(&self) -> String {
194        hex_encode(&self.0.to_bytes())
195    }
196
197    /// This key's content-addressed id ([`derive_key_id`]).
198    pub fn key_id(&self) -> String {
199        derive_key_id(self)
200    }
201}
202
203/// The content address of a public key: `sha256` over its 32 bytes, the
204/// one hashing primitive shared with artifact references, journal heads,
205/// and capsule ids. A receipt's `signer` naming this id commits to exactly
206/// one key, which is what makes "receipts signed after the compromise date
207/// are suspect" answerable from the key history alone.
208pub fn derive_key_id(public_key: &PublicKey) -> String {
209    sha256_hex(&public_key.0.to_bytes())
210}
211
212fn invalid_key(detail: String) -> RustyError {
213    RustyError::Serialization(serde_json::Error::io(std::io::Error::new(
214        std::io::ErrorKind::InvalidData,
215        detail,
216    )))
217}
218
219/// Lowercase hex of `bytes` (the [`sha256_hex`] formatting rule, for key
220/// material and signatures rather than digests).
221fn hex_encode(bytes: &[u8]) -> String {
222    let mut out = String::with_capacity(bytes.len() * 2);
223    for byte in bytes {
224        use std::fmt::Write as _;
225        let _ = write!(out, "{byte:02x}");
226    }
227    out
228}
229
230/// Decode lowercase or uppercase hex; `None` on odd length or non-hex
231/// input. Local to receipts: the crate hashes often but decodes hex only
232/// here, at the key/signature boundary.
233fn hex_decode(hex: &str) -> Option<Vec<u8>> {
234    if hex.len() % 2 != 0 {
235        return None;
236    }
237    (0..hex.len())
238        .step_by(2)
239        .map(|i| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok())
240        .collect()
241}
242
243// --------------------------------------------------------------------- //
244// The receipt
245// --------------------------------------------------------------------- //
246
247/// The signed statement over one run's evidence (R0.9 wave 3). Serde-
248/// versioned (`format_version`), golden-pinned
249/// (`rusty-core/tests/golden/run_receipt.json`), and additive like every
250/// other contract here: new fields arrive with serde defaults so receipts
251/// written by earlier builds keep verifying.
252///
253/// Two fields are evidence carried for the auditor rather than digests
254/// recomputed from the journal: `manifest` (which lives in checkpoint
255/// headers, not in the event chain) and `executor_policy` (likewise).
256/// Everything else — the head, the resolved capsules, the effect and
257/// denials ledgers, the Cedar policy versions — is recomputed from the
258/// journaled events at verification time, and `manifest_digest` commits
259/// the carried manifest into the signed statement so tampering with either
260/// half is caught by name ([`ReceiptRejection::ManifestDigest`]) before
261/// the signature is even checked.
262#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
263pub struct RunReceipt {
264    /// Receipt envelope version; [`RECEIPT_FORMAT_VERSION`] for anything
265    /// minted now.
266    pub format_version: u32,
267
268    /// The run this receipt attests.
269    pub run_id: String,
270
271    /// The journal head the signature covers: event count plus chained
272    /// SHA-256. Signing the head signs every event transitively;
273    /// verification recomputes it from the snapshot's event chain.
274    pub journal_head: JournalRef,
275
276    /// SHA-256 of the canonical serialization of `manifest` — the compact
277    /// commitment the canonical form covers. `None` exactly when the run
278    /// pinned no manifest.
279    #[serde(default, skip_serializing_if = "Option::is_none")]
280    pub manifest_digest: Option<String>,
281
282    /// The run manifest the server pinned into the run's checkpoint
283    /// headers: prompt hashes, tool schema hashes, model + parameters
284    /// digest, memory schema. Carried in full because the journal does not
285    /// hold it — the manifest is checkpoint-header evidence, and the
286    /// receipt is where it joins the signed statement.
287    #[serde(default, skip_serializing_if = "Option::is_none")]
288    pub manifest: Option<RunManifest>,
289
290    /// The capsule content addresses the run's pins resolved to (pin name
291    /// → [`CapsuleId`]), recomputed from the journaled
292    /// [`RunEventKind::CapsuleResolved`] events. When a pin resolved more
293    /// than once the latest resolution wins — the run's current binding,
294    /// the same rule mint and verify share.
295    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
296    pub capsules: BTreeMap<String, CapsuleId>,
297
298    /// The effect ledger: one digest per journaled
299    /// [`EffectReceipt`], in journal order,
300    /// over provider, provider id, idempotency key, and effect id — the
301    /// four fields the design names. `task_id` is deliberately outside the
302    /// digest: task linkage is dispatch bookkeeping, not effect identity.
303    #[serde(default, skip_serializing_if = "Vec::is_empty")]
304    pub effects: Vec<String>,
305
306    /// The executor policy version the run's checkpoint header pinned.
307    /// Carried evidence (like `manifest`): the header lives outside the
308    /// journal, so the signature covers it and no recompute can.
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    pub executor_policy: Option<PolicyVersion>,
311
312    /// The Cedar policy versions capsules were admitted under, distinct,
313    /// in first-use order — recomputed from the journaled resolutions.
314    #[serde(default, skip_serializing_if = "Vec::is_empty")]
315    pub capsule_policies: Vec<String>,
316
317    /// The denials ledger: the ids of the run's
318    /// [`RunEventKind::CapsuleDenied`] events, in journal order. Empty for
319    /// a run that never attempted forbidden access — which is itself a
320    /// statement the signature covers.
321    #[serde(default, skip_serializing_if = "Vec::is_empty")]
322    pub denials: Vec<String>,
323
324    /// The signer's content-addressed key id ([`derive_key_id`]).
325    /// Verification resolves the public key by this id from the
326    /// deployment's key history, which is what keeps receipts signed
327    /// before a rotation verifiable.
328    pub signer: String,
329
330    /// Lowercase-hex Ed25519 signature over [`RunReceipt::canonical_bytes`].
331    pub signature: String,
332}
333
334/// The signed statement, exactly as the canonical form covers it: every
335/// receipt field except `signature`. Borrowed, so canonicalization never
336/// clones the receipt.
337#[derive(Serialize)]
338struct ReceiptStatement<'a> {
339    format_version: u32,
340    run_id: &'a str,
341    journal_head: &'a JournalRef,
342    #[serde(skip_serializing_if = "Option::is_none")]
343    manifest_digest: &'a Option<String>,
344    #[serde(skip_serializing_if = "Option::is_none")]
345    manifest: &'a Option<RunManifest>,
346    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
347    capsules: &'a BTreeMap<String, CapsuleId>,
348    #[serde(skip_serializing_if = "<[_]>::is_empty")]
349    effects: &'a [String],
350    #[serde(skip_serializing_if = "Option::is_none")]
351    executor_policy: &'a Option<PolicyVersion>,
352    #[serde(skip_serializing_if = "<[_]>::is_empty")]
353    capsule_policies: &'a [String],
354    #[serde(skip_serializing_if = "<[_]>::is_empty")]
355    denials: &'a [String],
356    signer: &'a str,
357}
358
359impl RunReceipt {
360    fn statement(&self) -> ReceiptStatement<'_> {
361        ReceiptStatement {
362            format_version: self.format_version,
363            run_id: &self.run_id,
364            journal_head: &self.journal_head,
365            manifest_digest: &self.manifest_digest,
366            manifest: &self.manifest,
367            capsules: &self.capsules,
368            effects: &self.effects,
369            executor_policy: &self.executor_policy,
370            capsule_policies: &self.capsule_policies,
371            denials: &self.denials,
372            signer: &self.signer,
373        }
374    }
375
376    /// The canonical serialization the signature covers: the statement as
377    /// JSON with every object map key-sorted recursively — the same
378    /// canonicalization rule the journal's head chain applies
379    /// (`canonicalize_value`), so receipt digests and journal digests
380    /// are computed under one rule and can never drift apart across
381    /// serde_json map backends. These exact bytes are what a transparency
382    /// log would witness; the integration lands additively because the
383    /// form is already frozen.
384    pub fn canonical_bytes(&self) -> crate::error::Result<Vec<u8>> {
385        let value = serde_json::to_value(self.statement())?;
386        Ok(serde_json::to_vec(&canonicalize_value(&value))?)
387    }
388}
389
390/// The journaled record of a signing-key rotation (R0.9 wave 3): the
391/// output payload of a [`RunEventKind::SigningKeyRotated`] event in the
392/// deployment's receipts journal. Journaling the new key id is what makes
393/// "which key signed what, from when" a chained fact rather than a
394/// registry note; the public half travels with it so the lineage is
395/// self-describing.
396#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
397pub struct SigningKeyRotation {
398    /// The key id that signed until now. `None` on genesis — the first
399    /// key a deployment ever generated.
400    #[serde(default, skip_serializing_if = "Option::is_none")]
401    pub previous_key_id: Option<String>,
402
403    /// The new key id (content address of `public_key`).
404    pub new_key_id: String,
405
406    /// The new public key, lowercase hex.
407    pub public_key: String,
408
409    /// When the rotation happened, read from the server's clock.
410    pub rotated_at: DateTime<Utc>,
411}
412
413// --------------------------------------------------------------------- //
414// Minting
415// --------------------------------------------------------------------- //
416
417/// Mint and sign a receipt over `snapshot`.
418///
419/// `manifest` and `executor_policy` come from the run's checkpoint header
420/// (the journal does not hold them); everything else is derived from the
421/// journaled events by the same component-derivation walk verification
422/// uses, so mint and verify cannot drift apart.
423///
424/// Minting refuses evidence that fails its own integrity check — a
425/// snapshot whose event chain does not recompute to its claimed head is
426/// rejected before anything is signed, because a signature over
427/// unverifiable evidence would attest nothing. Externalized snapshots
428/// ([`JournalSnapshot::artifact_refs`]) are refused for the same reason
429/// verification rejects them: the ledger digests must cover payloads this
430/// process can resolve.
431pub fn mint_receipt(
432    snapshot: &JournalSnapshot,
433    manifest: Option<RunManifest>,
434    executor_policy: Option<PolicyVersion>,
435    signing_key: &SigningKey,
436) -> crate::error::Result<RunReceipt> {
437    let journal_head = verified_head(snapshot)?;
438    let components = derive_components(snapshot)?;
439    let manifest_digest = manifest_digest(manifest.as_ref())?;
440    let mut receipt = RunReceipt {
441        format_version: RECEIPT_FORMAT_VERSION,
442        run_id: snapshot.run_id.clone(),
443        journal_head,
444        manifest_digest,
445        manifest,
446        capsules: components.capsules,
447        effects: components.effects,
448        executor_policy,
449        capsule_policies: components.capsule_policies,
450        denials: components.denials,
451        signer: signing_key.key_id(),
452        // Filled below; the canonical form never covers it.
453        signature: String::new(),
454    };
455    let canonical = receipt.canonical_bytes()?;
456    receipt.signature = signing_key.sign_hex(&canonical);
457    Ok(receipt)
458}
459
460/// SHA-256 of the canonical serialization of `manifest` — the commitment
461/// [`RunReceipt::manifest_digest`] carries. The same canonical-digest
462/// convention the manifest's own pins use (object keys sort
463/// deterministically, so equal manifests commit equal).
464pub fn manifest_digest(manifest: Option<&RunManifest>) -> crate::error::Result<Option<String>> {
465    let Some(manifest) = manifest else {
466        return Ok(None);
467    };
468    let value = serde_json::to_value(manifest)?;
469    Ok(Some(sha256_hex(&serde_json::to_vec(&canonicalize_value(
470        &value,
471    ))?)))
472}
473
474/// The head the snapshot's event chain recomputes to, checked against the
475/// snapshot's claim — the integrity gate mint and verify share. Uses the
476/// journal's own chain step, so this can never disagree with
477/// [`crate::journal::Journal::from_snapshot`].
478fn verified_head(snapshot: &JournalSnapshot) -> crate::error::Result<JournalRef> {
479    if !snapshot.artifact_refs.is_empty() {
480        return Err(RustyError::Serialization(serde_json::Error::io(
481            std::io::Error::new(
482                std::io::ErrorKind::InvalidData,
483                "journal snapshot references an external artifact store; \
484                 receipts v1 mint and verify over embedded snapshots",
485            ),
486        )));
487    }
488    let recomputed = crate::journal::recompute_head_hash(&snapshot.events)?;
489    if recomputed != snapshot.head_hash {
490        return Err(RustyError::Serialization(serde_json::Error::io(
491            std::io::Error::new(
492                std::io::ErrorKind::InvalidData,
493                format!(
494                    "journal snapshot head hash mismatch: events recompute to \
495                     {recomputed}, snapshot claims {}",
496                    snapshot.head_hash
497                ),
498            ),
499        )));
500    }
501    Ok(JournalRef {
502        events: snapshot.events.len() as u64,
503        sha256: recomputed,
504    })
505}
506
507/// The journal-derived components of a receipt, recomputed identically at
508/// mint and at verify — one walk, so the two can never drift.
509struct ReceiptComponents {
510    capsules: BTreeMap<String, CapsuleId>,
511    effects: Vec<String>,
512    capsule_policies: Vec<String>,
513    denials: Vec<String>,
514}
515
516/// Walk the snapshot's events, deriving the resolved-capsule map, the
517/// effect ledger, the Cedar policy versions, and the denials ledger.
518///
519/// Malformed payloads (a hand-edited journal whose head was recomputed to
520/// match) are skipped rather than fatal — the same tolerance rule
521/// [`JournalSnapshot::find_effect_receipt`] documents. The skip cannot
522/// hide tampering: any byte flip in a journaled event changes the head,
523/// which fails verification first.
524fn derive_components(snapshot: &JournalSnapshot) -> crate::error::Result<ReceiptComponents> {
525    let mut capsules = BTreeMap::new();
526    let mut effects = Vec::new();
527    let mut capsule_policies = Vec::new();
528    let mut denials = Vec::new();
529    for event in &snapshot.events {
530        match event.kind {
531            RunEventKind::EffectReceipt => {
532                let Some(value) = resolve_output(snapshot, event) else {
533                    continue;
534                };
535                if let Ok(receipt) = serde_json::from_value::<EffectReceipt>(value) {
536                    effects.push(effect_ledger_digest(&receipt)?);
537                }
538            }
539            RunEventKind::CapsuleResolved => {
540                let Some(value) = resolve_output(snapshot, event) else {
541                    continue;
542                };
543                if let Ok(resolution) = serde_json::from_value::<CapsuleResolution>(value) {
544                    // Latest resolution wins: the run's current binding.
545                    capsules.insert(resolution.name, resolution.capsule_id);
546                    if let Some(version) = resolution.policy_version {
547                        if !capsule_policies.contains(&version) {
548                            capsule_policies.push(version);
549                        }
550                    }
551                }
552            }
553            RunEventKind::CapsuleDenied => denials.push(event.id.clone()),
554            _ => {}
555        }
556    }
557    Ok(ReceiptComponents {
558        capsules,
559        effects,
560        capsule_policies,
561        denials,
562    })
563}
564
565/// Resolve an event's output payload, looking through the snapshot's
566/// artifact map — the [`JournalSnapshot::find_effect_receipt`] rule.
567fn resolve_output(
568    snapshot: &JournalSnapshot,
569    event: &crate::record::RunEvent,
570) -> Option<serde_json::Value> {
571    match event.output.as_ref()? {
572        PayloadRef::Inline(value) => Some(value.clone()),
573        PayloadRef::Artifact(reference) => snapshot.artifacts.get(&reference.sha256).cloned(),
574    }
575}
576
577/// One effect-ledger entry, exactly as digested: the four fields the
578/// design names, in declaration order. A typed struct (no free-form maps),
579/// so its serialization is canonical under either serde_json map backend —
580/// the same rule the journal chain relies on for struct fields.
581#[derive(Serialize)]
582struct EffectLedgerEntry<'a> {
583    provider: &'a str,
584    provider_id: &'a str,
585    idempotency_key: &'a str,
586    #[serde(skip_serializing_if = "Option::is_none")]
587    effect_id: Option<&'a str>,
588}
589
590/// The ledger digest of one journaled effect receipt.
591fn effect_ledger_digest(receipt: &EffectReceipt) -> crate::error::Result<String> {
592    let entry = EffectLedgerEntry {
593        provider: &receipt.provider,
594        provider_id: &receipt.provider_id,
595        idempotency_key: &receipt.idempotency_key,
596        effect_id: receipt.effect_id.as_deref(),
597    };
598    Ok(sha256_hex(&serde_json::to_vec(&entry)?))
599}
600
601// --------------------------------------------------------------------- //
602// Verification
603// ---------------------------------------------------------------------//
604
605/// A verification failure, typed by the component whose digest mismatched.
606/// The Display text names the claimed and recomputed values; [`ReceiptRejection::component`]
607/// gives the stable machine-readable name the server's `POST
608/// /receipts/verify` reports. Verification never answers a bare `false`.
609#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
610pub enum ReceiptRejection {
611    /// The receipt was written by a newer (or older, breaking) format.
612    #[error("unsupported receipt format version {claimed} (this build verifies {supported})")]
613    FormatVersion {
614        /// The version the receipt claims.
615        claimed: u32,
616        /// The version this build verifies.
617        supported: u32,
618    },
619
620    /// The snapshot spills payloads to an external artifact store; v1
621    /// verifies embedded snapshots only.
622    #[error(
623        "the snapshot references an external artifact store; receipts v1 \
624             verifies embedded snapshots only"
625    )]
626    ExternalArtifacts,
627
628    /// The snapshot's own event chain does not recompute to its claimed
629    /// head — tampered evidence, caught before any receipt comparison.
630    #[error(
631        "journal head mismatch: the snapshot's events recompute to {recomputed}, \
632             the snapshot claims {claimed}"
633    )]
634    SnapshotHead {
635        /// The head the snapshot carries.
636        claimed: String,
637        /// The head the event chain recomputes to.
638        recomputed: String,
639    },
640
641    /// The receipt names a different run than the snapshot records.
642    #[error("run id mismatch: the receipt attests `{claimed}`, the snapshot records `{snapshot}`")]
643    RunId {
644        /// The run id in the receipt.
645        claimed: String,
646        /// The run id in the snapshot.
647        snapshot: String,
648    },
649
650    /// The receipt's signed head is not the head the snapshot's chain
651    /// recomputes to — the receipt covers a different journal state.
652    #[error(
653        "journal head mismatch: the receipt signs {claimed}, the snapshot's events \
654             recompute to {recomputed}"
655    )]
656    JournalHead {
657        /// The head the receipt signs.
658        claimed: String,
659        /// The head the event chain recomputes to.
660        recomputed: String,
661    },
662
663    /// The receipt's signed event count disagrees with the snapshot.
664    #[error(
665        "journal length mismatch: the receipt signs {claimed} events, the snapshot holds {actual}"
666    )]
667    JournalLength {
668        /// The event count the receipt signs.
669        claimed: u64,
670        /// The event count in the snapshot.
671        actual: u64,
672    },
673
674    /// The carried manifest does not re-hash to the committed digest.
675    #[error(
676        "manifest digest mismatch: the receipt commits {claimed:?}, the carried manifest \
677             re-hashes to {recomputed:?}"
678    )]
679    ManifestDigest {
680        /// The digest the receipt commits.
681        claimed: Option<String>,
682        /// The digest the carried manifest re-hashes to.
683        recomputed: Option<String>,
684    },
685
686    /// The resolved-capsule map disagrees with the journaled resolutions.
687    #[error("capsule resolution mismatch: {0}")]
688    CapsuleResolutions(String),
689
690    /// The effect ledger disagrees with the journaled effect receipts.
691    #[error("effect ledger mismatch: {0}")]
692    EffectLedger(String),
693
694    /// The Cedar policy versions disagree with the journaled resolutions.
695    #[error("capsule policy mismatch: {0}")]
696    CapsulePolicies(String),
697
698    /// The denials ledger disagrees with the journaled denials.
699    #[error("denials ledger mismatch: {0}")]
700    DenialsLedger(String),
701
702    /// The public key offered for verification is not the receipt's
703    /// signer — the key id is a content address, so this is a definitive
704    /// answer, not a guess.
705    #[error(
706        "signer mismatch: the receipt names signer {claimed}, the offered key derives {derived}"
707    )]
708    SignerKeyId {
709        /// The key id the receipt names.
710        claimed: String,
711        /// The key id the offered public key derives to.
712        derived: String,
713    },
714
715    /// The signature does not verify over the canonical bytes — either it
716    /// is malformed or the signed statement was altered.
717    #[error("signature invalid: {0}")]
718    Signature(String),
719}
720
721impl ReceiptRejection {
722    /// The stable machine-readable component name (the server's verify
723    /// endpoint reports it): which part of the evidence failed.
724    pub fn component(&self) -> &'static str {
725        match self {
726            ReceiptRejection::FormatVersion { .. } => "format_version",
727            ReceiptRejection::ExternalArtifacts => "external_artifacts",
728            ReceiptRejection::SnapshotHead { .. } => "journal_head",
729            ReceiptRejection::RunId { .. } => "run_id",
730            ReceiptRejection::JournalHead { .. } => "journal_head",
731            ReceiptRejection::JournalLength { .. } => "journal_head",
732            ReceiptRejection::ManifestDigest { .. } => "manifest_digest",
733            ReceiptRejection::CapsuleResolutions(_) => "capsule_resolutions",
734            ReceiptRejection::EffectLedger(_) => "effect_ledger",
735            ReceiptRejection::CapsulePolicies(_) => "capsule_policies",
736            ReceiptRejection::DenialsLedger(_) => "denials_ledger",
737            ReceiptRejection::SignerKeyId { .. } => "signer_key_id",
738            ReceiptRejection::Signature(_) => "signature",
739        }
740    }
741}
742
743/// The typed summary of a successfully verified receipt: what was proven.
744/// Every field was either recomputed from the snapshot during verification
745/// or covered by the signature over the canonical form — nothing here is
746/// taken on trust.
747#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
748pub struct VerifiedRun {
749    /// The verified run.
750    pub run_id: String,
751
752    /// The verified journal head (recomputed from the snapshot's chain).
753    pub journal_head: JournalRef,
754
755    /// The verified manifest commitment.
756    #[serde(default, skip_serializing_if = "Option::is_none")]
757    pub manifest_digest: Option<String>,
758
759    /// The verified resolved-capsule map.
760    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
761    pub capsules: BTreeMap<String, CapsuleId>,
762
763    /// How many journaled effect receipts the verified ledger covers.
764    pub effect_receipts: usize,
765
766    /// The executor policy version the receipt attests (carried,
767    /// signature-covered evidence).
768    #[serde(default, skip_serializing_if = "Option::is_none")]
769    pub executor_policy: Option<PolicyVersion>,
770
771    /// The verified Cedar policy versions.
772    #[serde(default, skip_serializing_if = "Vec::is_empty")]
773    pub capsule_policies: Vec<String>,
774
775    /// The verified denials ledger.
776    #[serde(default, skip_serializing_if = "Vec::is_empty")]
777    pub denials: Vec<String>,
778
779    /// The verified signer's key id.
780    pub signer: String,
781}
782
783/// Verify a receipt against an exported journal snapshot and a public key:
784/// recompute the head over the snapshot's event chain, recompute the
785/// manifest and ledger digests, check the signature.
786///
787/// The order is evidence-first, signature-last: the snapshot's own chain
788/// is re-verified before any comparison (tampered evidence is named as
789/// such, never compared against), each journal-derived component is
790/// recomputed and compared by name, and only then does the signature
791/// check run — so a failure always says *which* digest mismatched, and a
792/// signature failure means the signed statement itself was altered.
793///
794/// The manifest and executor policy are the two components no journal can
795/// recompute (they live in checkpoint headers); the carried manifest is
796/// re-hashed against its committed digest, and both are covered by the
797/// signature. Everything else is proven from the snapshot alone.
798pub fn verify_receipt(
799    snapshot: &JournalSnapshot,
800    receipt: &RunReceipt,
801    public_key: &PublicKey,
802) -> Result<VerifiedRun, ReceiptRejection> {
803    if receipt.format_version != RECEIPT_FORMAT_VERSION {
804        return Err(ReceiptRejection::FormatVersion {
805            claimed: receipt.format_version,
806            supported: RECEIPT_FORMAT_VERSION,
807        });
808    }
809    if !snapshot.artifact_refs.is_empty() {
810        return Err(ReceiptRejection::ExternalArtifacts);
811    }
812    let recomputed_head = crate::journal::recompute_head_hash(&snapshot.events).map_err(|e| {
813        ReceiptRejection::Signature(format!("the snapshot's events cannot be hashed: {e}"))
814    })?;
815    if recomputed_head != snapshot.head_hash {
816        return Err(ReceiptRejection::SnapshotHead {
817            claimed: snapshot.head_hash.clone(),
818            recomputed: recomputed_head,
819        });
820    }
821    if receipt.run_id != snapshot.run_id {
822        return Err(ReceiptRejection::RunId {
823            claimed: receipt.run_id.clone(),
824            snapshot: snapshot.run_id.clone(),
825        });
826    }
827    if receipt.journal_head.sha256 != recomputed_head {
828        return Err(ReceiptRejection::JournalHead {
829            claimed: receipt.journal_head.sha256.clone(),
830            recomputed: recomputed_head,
831        });
832    }
833    if receipt.journal_head.events != snapshot.events.len() as u64 {
834        return Err(ReceiptRejection::JournalLength {
835            claimed: receipt.journal_head.events,
836            actual: snapshot.events.len() as u64,
837        });
838    }
839    let recomputed_manifest = manifest_digest(receipt.manifest.as_ref())
840        .map_err(|e| ReceiptRejection::Signature(format!("the manifest cannot be hashed: {e}")))?;
841    if recomputed_manifest != receipt.manifest_digest {
842        return Err(ReceiptRejection::ManifestDigest {
843            claimed: receipt.manifest_digest.clone(),
844            recomputed: recomputed_manifest,
845        });
846    }
847    let components = derive_components(snapshot)
848        .map_err(|e| ReceiptRejection::Signature(format!("the ledger cannot be digested: {e}")))?;
849    if components.capsules != receipt.capsules {
850        return Err(ReceiptRejection::CapsuleResolutions(ledger_diff(
851            "capsules",
852            &receipt.capsules,
853            &components.capsules,
854        )));
855    }
856    if components.effects != receipt.effects {
857        return Err(ReceiptRejection::EffectLedger(sequence_diff(
858            "effects",
859            &receipt.effects,
860            &components.effects,
861        )));
862    }
863    if components.capsule_policies != receipt.capsule_policies {
864        return Err(ReceiptRejection::CapsulePolicies(sequence_diff(
865            "capsule policies",
866            &receipt.capsule_policies,
867            &components.capsule_policies,
868        )));
869    }
870    if components.denials != receipt.denials {
871        return Err(ReceiptRejection::DenialsLedger(sequence_diff(
872            "denials",
873            &receipt.denials,
874            &components.denials,
875        )));
876    }
877    let derived_key_id = public_key.key_id();
878    if derived_key_id != receipt.signer {
879        return Err(ReceiptRejection::SignerKeyId {
880            claimed: receipt.signer.clone(),
881            derived: derived_key_id,
882        });
883    }
884    let canonical = receipt
885        .canonical_bytes()
886        .map_err(|e| ReceiptRejection::Signature(format!("the statement cannot be hashed: {e}")))?;
887    let signature_bytes = hex_decode(&receipt.signature)
888        .and_then(|bytes| <[u8; 64]>::try_from(bytes.as_slice()).ok())
889        .ok_or_else(|| {
890            ReceiptRejection::Signature("the signature is not 64 bytes of hex".to_string())
891        })?;
892    let signature = ed25519_dalek::Signature::from_bytes(&signature_bytes);
893    // `verify_strict`: canonical-S and torsion-safe — one valid encoding
894    // per signature, the posture a witnessed statement wants.
895    public_key
896        .0
897        .verify_strict(&canonical, &signature)
898        .map_err(|_| {
899            ReceiptRejection::Signature(
900                "the signature does not verify over the canonical statement".to_string(),
901            )
902        })?;
903    Ok(VerifiedRun {
904        run_id: receipt.run_id.clone(),
905        journal_head: receipt.journal_head.clone(),
906        manifest_digest: receipt.manifest_digest.clone(),
907        capsules: components.capsules,
908        effect_receipts: components.effects.len(),
909        executor_policy: receipt.executor_policy.clone(),
910        capsule_policies: components.capsule_policies,
911        denials: components.denials,
912        signer: receipt.signer.clone(),
913    })
914}
915
916/// Verify a receipt's authenticity and its head *as a prefix of a
917/// journal that may have grown since the mint* (R0.12 wave 2 — the
918/// retention sweeper's coverage check).
919///
920/// [`verify_receipt`] answers "does this receipt attest this exact
921/// journal?"; this answers the retention question "does this receipt
922/// still pin the addresses its covered events name?". A receipt is a
923/// statement about the events under its head, and the journal's
924/// append-only hash chain makes that statement durable: recomputing the
925/// head over the current journal's first `journal_head.events` events
926/// and matching it against the signed head proves the covered prefix is
927/// byte-identical to what was signed, however much the journal grew
928/// since. Ledger components (effects, capsules, denials) are whole-
929/// journal derivations and are deliberately *not* recomputed here — the
930/// coverage question is about the prefix, not the tail.
931///
932/// The fail-closed rule matches [`verify_receipt`]'s: authenticity
933/// (signer key id plus the strict signature over the canonical
934/// statement), run identity, and the prefix head are all checked, and
935/// any mismatch is a typed rejection — a sweeper that cannot verify a
936/// receipt's coverage of an address must assume the coverage stands.
937pub fn verify_receipt_prefix(
938    snapshot: &JournalSnapshot,
939    receipt: &RunReceipt,
940    public_key: &PublicKey,
941) -> Result<(), ReceiptRejection> {
942    if receipt.format_version != RECEIPT_FORMAT_VERSION {
943        return Err(ReceiptRejection::FormatVersion {
944            claimed: receipt.format_version,
945            supported: RECEIPT_FORMAT_VERSION,
946        });
947    }
948    if receipt.run_id != snapshot.run_id {
949        return Err(ReceiptRejection::RunId {
950            claimed: receipt.run_id.clone(),
951            snapshot: snapshot.run_id.clone(),
952        });
953    }
954    let covered = receipt.journal_head.events as usize;
955    if covered > snapshot.events.len() {
956        return Err(ReceiptRejection::JournalLength {
957            claimed: receipt.journal_head.events,
958            actual: snapshot.events.len() as u64,
959        });
960    }
961    let recomputed =
962        crate::journal::recompute_head_hash(&snapshot.events[..covered]).map_err(|e| {
963            ReceiptRejection::Signature(format!("the covered events cannot be hashed: {e}"))
964        })?;
965    if recomputed != receipt.journal_head.sha256 {
966        return Err(ReceiptRejection::JournalHead {
967            claimed: receipt.journal_head.sha256.clone(),
968            recomputed,
969        });
970    }
971    let derived_key_id = public_key.key_id();
972    if derived_key_id != receipt.signer {
973        return Err(ReceiptRejection::SignerKeyId {
974            claimed: receipt.signer.clone(),
975            derived: derived_key_id,
976        });
977    }
978    let canonical = receipt
979        .canonical_bytes()
980        .map_err(|e| ReceiptRejection::Signature(format!("the statement cannot be hashed: {e}")))?;
981    let signature_bytes = hex_decode(&receipt.signature)
982        .and_then(|bytes| <[u8; 64]>::try_from(bytes.as_slice()).ok())
983        .ok_or_else(|| {
984            ReceiptRejection::Signature("the signature is not 64 bytes of hex".to_string())
985        })?;
986    let signature = ed25519_dalek::Signature::from_bytes(&signature_bytes);
987    // `verify_strict`, as in `verify_receipt`: one valid encoding per
988    // signature, the posture a witnessed statement wants.
989    public_key
990        .0
991        .verify_strict(&canonical, &signature)
992        .map_err(|_| {
993            ReceiptRejection::Signature(
994                "the signature does not verify over the canonical statement".to_string(),
995            )
996        })?;
997    Ok(())
998}
999
1000/// The first divergence between a claimed and recomputed sequence, phrased
1001/// for the rejection message.
1002fn sequence_diff(what: &str, claimed: &[String], recomputed: &[String]) -> String {
1003    if claimed.len() != recomputed.len() {
1004        return format!(
1005            "the receipt's {what} ledger holds {} entries, the journal recomputes {}",
1006            claimed.len(),
1007            recomputed.len()
1008        );
1009    }
1010    for (index, (claimed, recomputed)) in claimed.iter().zip(recomputed).enumerate() {
1011        if claimed != recomputed {
1012            return format!(
1013                "the receipt's {what} entry {index} is `{claimed}`, the journal recomputes `{recomputed}`"
1014            );
1015        }
1016    }
1017    format!("the receipt's {what} ledger disagrees with the journal")
1018}
1019
1020/// The divergence between a claimed and recomputed capsule map, phrased
1021/// for the rejection message.
1022fn ledger_diff(
1023    what: &str,
1024    claimed: &BTreeMap<String, CapsuleId>,
1025    recomputed: &BTreeMap<String, CapsuleId>,
1026) -> String {
1027    for (name, id) in claimed {
1028        match recomputed.get(name) {
1029            None => {
1030                return format!(
1031                    "the receipt resolves pin `{name}` to `{id}`, the journal holds no resolution"
1032                )
1033            }
1034            Some(recomputed) if recomputed != id => {
1035                return format!(
1036                    "the receipt resolves pin `{name}` to `{id}`, the journal recomputes `{recomputed}`"
1037                )
1038            }
1039            _ => {}
1040        }
1041    }
1042    for name in recomputed.keys() {
1043        if !claimed.contains_key(name) {
1044            return format!(
1045                "the journal resolves pin `{name}`, the receipt's {what} ledger omits it"
1046            );
1047        }
1048    }
1049    format!("the receipt's {what} ledger disagrees with the journal")
1050}
1051
1052#[cfg(test)]
1053mod tests {
1054    use super::*;
1055
1056    #[test]
1057    fn hex_roundtrip_and_rejects_malformed() {
1058        assert_eq!(hex_encode(&[0x00, 0xff, 0x10]), "00ff10");
1059        assert_eq!(hex_decode("00ff10"), Some(vec![0x00, 0xff, 0x10]));
1060        assert_eq!(hex_decode("00FF10"), Some(vec![0x00, 0xff, 0x10]));
1061        assert_eq!(hex_decode("0ff"), None);
1062        assert_eq!(hex_decode("zz"), None);
1063    }
1064
1065    #[test]
1066    fn key_id_is_a_content_address() {
1067        let key = SigningKey::from_bytes(&[7u8; 32]);
1068        let public = key.public_key();
1069        assert_eq!(key.key_id(), derive_key_id(&public));
1070        assert_eq!(key.key_id().len(), 64);
1071        // Different secret, different id — the id commits to the key.
1072        let other = SigningKey::from_bytes(&[8u8; 32]);
1073        assert_ne!(key.key_id(), other.key_id());
1074        // Hex round-trip preserves the key (and thus the id).
1075        let rehydrated = PublicKey::from_hex(&public.to_hex()).unwrap();
1076        assert_eq!(rehydrated, public);
1077        let secret = SigningKey::from_hex(&key.to_hex()).unwrap();
1078        assert_eq!(secret.key_id(), key.key_id());
1079    }
1080
1081    #[test]
1082    fn generated_keys_sign_and_verify() {
1083        let key = SigningKey::generate();
1084        let signature = key.sign_hex(b"canonical bytes");
1085        let bytes = hex_decode(&signature).unwrap();
1086        let signature =
1087            ed25519_dalek::Signature::from_bytes(&<[u8; 64]>::try_from(bytes.as_slice()).unwrap());
1088        key.public_key()
1089            .0
1090            .verify_strict(b"canonical bytes", &signature)
1091            .unwrap();
1092    }
1093
1094    #[test]
1095    fn prefix_verification_survives_journal_growth() {
1096        use crate::journal::{Clock, EventDraft, Journal};
1097        use crate::record::{Effect, RunEventKind};
1098
1099        let signing = SigningKey::from_bytes(&[9u8; 32]);
1100        let journal = Journal::new("run-prefix", "thread-prefix", Clock::System);
1101        journal.record(
1102            EventDraft::new(RunEventKind::SuperStepStart, Effect::Pure)
1103                .output(serde_json::json!({"step": 0})),
1104        );
1105        journal.record(
1106            EventDraft::new(RunEventKind::NodeOutput, Effect::Pure)
1107                .output(serde_json::json!({"value": 1})),
1108        );
1109        let minted = journal.snapshot();
1110        let receipt = mint_receipt(&minted, None, None, &signing).unwrap();
1111        // Whole-journal verification agrees at mint time.
1112        verify_receipt(&minted, &receipt, &signing.public_key()).unwrap();
1113
1114        // The journal grows after the mint — post-mint commits must not
1115        // stale the coverage the receipt attests.
1116        journal.record(
1117            EventDraft::new(RunEventKind::SuperStepEnd, Effect::Pure)
1118                .output(serde_json::json!({"step": 0})),
1119        );
1120        let grown = journal.snapshot();
1121        verify_receipt_prefix(&grown, &receipt, &signing.public_key()).unwrap();
1122        // The whole-journal check *does* reject the grown journal — the
1123        // prefix check is the sweeper's answer, not a loosening.
1124        assert!(matches!(
1125            verify_receipt(&grown, &receipt, &signing.public_key()),
1126            Err(ReceiptRejection::JournalHead { .. })
1127        ));
1128
1129        // A tampered covered event changes the recomputed prefix head.
1130        let mut tampered = grown.clone();
1131        tampered.events[0].seq = 99;
1132        assert!(matches!(
1133            verify_receipt_prefix(&tampered, &receipt, &signing.public_key()),
1134            Err(ReceiptRejection::JournalHead { .. })
1135        ));
1136        // The wrong key never verifies, however the journal stands.
1137        let other = SigningKey::from_bytes(&[10u8; 32]);
1138        assert!(matches!(
1139            verify_receipt_prefix(&grown, &receipt, &other.public_key()),
1140            Err(ReceiptRejection::SignerKeyId { .. })
1141        ));
1142    }
1143}