Skip to main content

capsule_core/crypto/
receipts.rs

1//! Custody receipts — the server-signed complement of the client-signed provenance chain
2//! (SSoT:
3//! [Transfer — Durability: Custody Receipts](https://docs/design/transfer/durability/#custody-receipts)).
4//!
5//! The envelope proves what a client *claimed and signed*; a receipt proves what the server
6//! *accepted*, over a ciphertext hash the server recomputed itself. Before dropping
7//! irreplaceable local bytes a client requires a **verified** receipt for the write, so a
8//! server that withholds receipts never becomes the sole holder of an only copy.
9//!
10//! # Why this lives in `crypto` and not in `library`
11//!
12//! It used to live in `library::receipts`, which is behind the `native` feature — and the
13//! server that *issues* receipts is compiled without `native` on purpose, because a key-free
14//! server turning it on would relink SQLite and MLS. The consequence was that the two ends of
15//! one signed wire format each defined it, which is the worst shape this codebase has for a
16//! signed structure: canonical CBOR sorts map keys, so byte-identity depends on the two copies
17//! agreeing exactly on field names, types and the wire-presence discipline. One added field, or
18//! one `Option` that serialises as a present `null`, and every receipt the server issues stops
19//! verifying on every client — surfacing as "the server is withholding receipts", which is the
20//! accusation the mechanism exists to make checkable.
21//!
22//! So the definition and its verification are here, ungated and shared, exactly as
23//! [`crate::validation`] is. What stayed in `library::receipts` is the client's own
24//! *persistence* — appending and reading the on-disk log — which is the half that needs
25//! `std::fs` and is nobody else's business. This module must stay `std::fs`-free: `crypto` is
26//! compiled for `wasm32`, and `build-check-wasm` is what notices if it stops being.
27//!
28//! Verification is pure offline crypto: [`HybridSignature`] and [`HybridVerifyingKey`] are
29//! `capsule-core`'s own types.
30
31use std::collections::BTreeMap;
32
33use ciborium::value::Value;
34use serde::{Deserialize, Serialize};
35
36use crate::cbor::{self, CanonicalError};
37use crate::crypto::hash::Hash32;
38use crate::crypto::keys::{HybridSignature, HybridVerifyingKey};
39
40/// A blob's role within an asset (closed enum; the value set is owned by the
41/// transfer durability doc).
42///
43/// Lives beside the receipt because the receipt's `blob_role` is written from it and the two
44/// have to agree on the spelling of every arm — see [`role_str`]. `library::storage_verify`
45/// re-exports it, so the path clients already use keeps working.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum BlobRole {
48    /// The original ciphertext blob.
49    Original,
50    /// The encrypted metadata blob.
51    Metadata,
52    /// A derivative (thumbnail / preview / embedding) blob.
53    Derivative,
54    /// The provenance chain.
55    Provenance,
56}
57
58/// The signed core of a [`CustodyReceipt`] — every field the server attestation key covers.
59///
60/// The one definition of the receipt's signed core. `capsule-server`'s attestation module signs
61/// exactly this type rather than a mirror of it, because canonical CBOR sorts map keys
62/// and two definitions of a signed structure disagree the moment either gains a field. Canonical
63/// CBOR with the manifest wire-presence discipline (absent optionals encode as absent keys).
64///
65/// **Unknown keys survive under the signature** ([Versioning — invariant 2]): a receipt from a
66/// newer server that only adds a field decodes here, re-emits that field canonically, and so
67/// still verifies — an older client does not mistake it for a withheld receipt. Stripping the
68/// field fails verification.
69///
70/// [Versioning — invariant 2]: https://docs/design/versioning/#system-invariants
71#[derive(Debug, Clone, PartialEq, Serialize)]
72pub struct CustodyReceiptCore {
73    /// Schema version (`custody-receipt/v1`).
74    pub version: String,
75    /// Primitive bundle id.
76    pub crypto_suite_id: u16,
77    /// Album protocol pin (`YYYY-MM-DD`).
78    pub protocol_version: String,
79    /// The server's canonical origin — binds the receipt to one server.
80    pub server_id: String,
81    /// Fingerprint of the attestation key that signed; survives rotation.
82    pub server_key_id: Hash32,
83    /// Strictly monotonic per server.
84    pub receipt_seq: u64,
85    /// SHA-256 over the previous receipt in the server's log; absent only for the first receipt.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub prior_receipt_hash: Option<Hash32>,
88    /// The upload session that produced custody.
89    pub upload_id: String,
90    /// The asset id.
91    pub asset_id: String,
92    /// `original | derivative | metadata | provenance`.
93    pub blob_role: String,
94    /// The server-recomputed ciphertext content address.
95    pub ciphertext_hash: Hash32,
96    /// Ciphertext size in bytes.
97    pub size: u64,
98    /// SHA-256 over the asset's signed manifest — its provenance-chain position — on the
99    /// receipt for the `provenance` blob, and absent on every other receipt.
100    ///
101    /// **A SHA-256 by definition, not the blob's content address.** The two are equal under
102    /// every suite that content-addresses with SHA-256 and they are not the same identifier: an
103    /// address is whatever digest the suite selects, while a chain position is fixed at SHA-256
104    /// because `prior_provenance_hash` is. Deriving one from the other is correct by
105    /// coincidence, which is a trap.
106    ///
107    /// **Present on one receipt per manifest, and that is the whole design.** The provenance
108    /// blob *is* the signed manifest, so its receipt names the manifest twice — once as the
109    /// bytes taken custody of, once as the chain position — and the manifest itself commits to
110    /// the other blobs' hashes. So "this blob was accepted under this manifest" is provable from
111    /// content addressing, and no other receipt needs to restate it. The server earlier hashed
112    /// its own re-serialization of the JSON *projection* of the manifest, which no client
113    /// outside this exact Rust type could reproduce and which reordering a struct field would
114    /// have silently invalidated.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub envelope_hash: Option<Hash32>,
117    /// The user that uploaded.
118    pub uploaded_by_user: String,
119    /// The device that uploaded, when known.
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub uploaded_by_device: Option<String>,
122    /// The server's trusted clock at the finalization commit (RFC 3339).
123    pub received_at: String,
124    /// Keys a newer server added that this build does not know, preserved verbatim and signed
125    /// over. Empty (and so wire-absent) on everything this build issues.
126    ///
127    /// A key here must never collide with a known field name: the decoder only ever places the
128    /// keys it did not recognise here, and an issuer building a core by hand must do the same.
129    #[serde(flatten)]
130    pub unknown: BTreeMap<String, Value>,
131}
132
133// `Value` holds floats, so it is only `PartialEq`. Equality is never how a receipt is trusted
134// (the signature over the canonical bytes is), so `Eq` stays, as on `ManifestCore`.
135impl Eq for CustodyReceiptCore {}
136
137impl<'de> Deserialize<'de> for CustodyReceiptCore {
138    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
139        let mut m = cbor::OpenMap::deserialize("custody receipt core", d)?;
140        Ok(Self {
141            version: m.take("version")?,
142            crypto_suite_id: m.take("crypto_suite_id")?,
143            protocol_version: m.take("protocol_version")?,
144            server_id: m.take("server_id")?,
145            server_key_id: m.take("server_key_id")?,
146            receipt_seq: m.take("receipt_seq")?,
147            prior_receipt_hash: m.take_opt("prior_receipt_hash")?,
148            upload_id: m.take("upload_id")?,
149            asset_id: m.take("asset_id")?,
150            blob_role: m.take("blob_role")?,
151            ciphertext_hash: m.take("ciphertext_hash")?,
152            size: m.take("size")?,
153            envelope_hash: m.take_opt("envelope_hash")?,
154            uploaded_by_user: m.take("uploaded_by_user")?,
155            uploaded_by_device: m.take_opt("uploaded_by_device")?,
156            received_at: m.take("received_at")?,
157            unknown: m.into_unknown(),
158        })
159    }
160}
161
162impl CustodyReceiptCore {
163    /// The canonical bytes the attestation signature covers.
164    #[must_use]
165    pub fn signing_bytes(&self) -> Vec<u8> {
166        cbor::to_canonical_vec(self).expect("custody-receipt core serializes")
167    }
168}
169
170/// A custody receipt: a [`CustodyReceiptCore`] plus its hybrid attestation signature.
171#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
172pub struct CustodyReceipt {
173    /// The signed core.
174    pub core: CustodyReceiptCore,
175    /// Hybrid Ed25519 + ML-DSA-65 signature under the server attestation key.
176    pub server_sig: HybridSignature,
177}
178
179impl CustodyReceipt {
180    /// Decode a canonical-CBOR receipt (the served / persisted form).
181    pub fn from_canonical_cbor(bytes: &[u8]) -> Result<Self, CanonicalError> {
182        cbor::from_slice(bytes)
183    }
184
185    /// Encode the full signed receipt as canonical CBOR.
186    #[must_use]
187    pub fn to_canonical_cbor(&self) -> Vec<u8> {
188        cbor::to_canonical_vec(self).expect("custody receipt serializes")
189    }
190
191    /// Verify the hybrid signature under a specific attestation public key.
192    #[must_use]
193    pub fn verify_under(&self, key: &HybridVerifyingKey) -> bool {
194        key.verify(&self.core.signing_bytes(), &self.server_sig)
195    }
196}
197
198/// What the client sent to the server, checked against the receipt's server-recomputed facts:
199/// a server that took custody of *different* bytes cannot answer with a matching receipt.
200#[derive(Debug, Clone, PartialEq, Eq)]
201pub struct ReceiptExpectations {
202    /// The ciphertext content address the client uploaded.
203    pub ciphertext_hash: Hash32,
204    /// The ciphertext size the client uploaded.
205    pub size: u64,
206    /// The blob's role on the asset.
207    pub role: BlobRole,
208    /// The asset's provenance-chain position — SHA-256 over the signed manifest — for the
209    /// upload of the `provenance` blob, and `None` for every other role.
210    ///
211    /// Deterministic on both sides, which is what lets this be an equality check: a client
212    /// uploading its manifest knows the digest before it opens the session, and a client
213    /// uploading anything else knows the server has nothing to say here. See
214    /// [`CustodyReceiptCore::envelope_hash`].
215    pub envelope_hash: Option<Hash32>,
216}
217
218/// Why a fetched receipt was rejected — every variant refuses release.
219#[derive(Debug, Clone, PartialEq, Eq)]
220pub enum ReceiptRejection {
221    /// The signature did not verify under any pinned attestation key.
222    Signature,
223    /// A field the client can check (`ciphertext_hash`/`size`/`blob_role`/`envelope_hash`) did
224    /// not match what the client sent.
225    FieldMismatch(&'static str),
226    /// `received_at` failed the gross-drift sanity bound (evidentiary only; ordering rides the
227    /// chain, not this timestamp).
228    ClockDrift,
229}
230
231/// The `blob_role` string the wire uses for a [`BlobRole`].
232///
233/// Public because the *server* writes the field this reads: one function, so the issuer and the
234/// verifier cannot disagree about how a role is spelled.
235#[must_use]
236pub fn role_str(role: BlobRole) -> &'static str {
237    match role {
238        BlobRole::Original => "original",
239        BlobRole::Metadata => "metadata",
240        BlobRole::Derivative => "derivative",
241        BlobRole::Provenance => "provenance",
242    }
243}
244
245/// A gross-drift sanity bound on `received_at`: a year each side of the client's clock. This is
246/// evidentiary only — a receipt whose `received_at` is wildly implausible is suspect — never an
247/// ordering signal (that rides the hash chain, mirroring the manifest `timestamp` rule).
248const RECEIVED_AT_DRIFT_SECS: i64 = 366 * 24 * 3600;
249
250/// Verify a fetched receipt for a finalized upload: the hybrid signature under one of the
251/// `pinned_keys` (the published attestation-key history), then that the server's recomputed
252/// facts match what the client sent, then the gross-drift bound on `received_at`.
253///
254/// `now_unix` is the client's current UNIX time (injected for determinism). Returns `Ok(())`
255/// only when the receipt is admissible evidence for the write.
256pub fn verify_receipt(
257    receipt: &CustodyReceipt,
258    pinned_keys: &[HybridVerifyingKey],
259    expected: &ReceiptExpectations,
260    now_unix: i64,
261) -> Result<(), ReceiptRejection> {
262    if !pinned_keys.iter().any(|k| receipt.verify_under(k)) {
263        return Err(ReceiptRejection::Signature);
264    }
265    let core = &receipt.core;
266    if core.ciphertext_hash != expected.ciphertext_hash {
267        return Err(ReceiptRejection::FieldMismatch("ciphertext_hash"));
268    }
269    if core.size != expected.size {
270        return Err(ReceiptRejection::FieldMismatch("size"));
271    }
272    if core.blob_role != role_str(expected.role) {
273        return Err(ReceiptRejection::FieldMismatch("blob_role"));
274    }
275    if core.envelope_hash != expected.envelope_hash {
276        return Err(ReceiptRejection::FieldMismatch("envelope_hash"));
277    }
278    let Ok(ts) = core.received_at.parse::<jiff::Timestamp>() else {
279        return Err(ReceiptRejection::ClockDrift);
280    };
281    if (ts.as_second() - now_unix).abs() > RECEIVED_AT_DRIFT_SECS {
282        return Err(ReceiptRejection::ClockDrift);
283    }
284    Ok(())
285}