capsule_library/library/receipts.rs
1//! Client-side custody receipts — the accountability half of the verify-before-destroy gate
2//! (SSoT:
3//! [Transfer — Durability: Custody Receipts](https://docs/design/transfer/durability/#custody-receipts)).
4//!
5//! A [`CustodyReceipt`] is the server-signed complement of the client-signed provenance chain:
6//! the envelope proves what a client *claimed and signed*; the receipt proves what the server
7//! *accepted*, over a ciphertext hash the server recomputed itself. Before dropping
8//! irreplaceable local bytes a client requires a **verified** receipt for the write, so a
9//! server that withholds receipts never becomes the sole holder of an only-copy.
10//!
11//! This module is the client's **persistence** path, and only that. The receipt type, its
12//! verification and the blob-role enum moved to [`capsule_core::crypto::receipts`] so the
13//! server that *issues* receipts shares one definition instead of mirroring it — a signed
14//! structure defined twice is a signature that eventually stops verifying, and the failure would
15//! look like the server withholding receipts. The receipt type and its verification are
16//! re-exported here and through [`crate::library`], so every path a client already uses keeps
17//! working. The role enum is not: it is reached as
18//! [`crypto::receipts::BlobRole`](capsule_core::crypto::receipts::BlobRole), and as
19//! [`library::BlobRole`](crate::library::BlobRole) through the storage-verify barrel.
20//!
21//! Persistence is first-class, not a cache: the log is appended to
22//! `media/{YYYY}/{YYYY-MM}/{uuid}.receipts.cbor` and included verbatim in the backup artifact —
23//! a server destroying the record of its own liability is exactly the adversary.
24
25use std::fs;
26use std::path::Path;
27
28use capsule_core::cbor::{self, CanonicalError};
29pub use capsule_core::crypto::receipts::{
30 CustodyReceipt, CustodyReceiptCore, ReceiptExpectations, ReceiptRejection, verify_receipt,
31};
32use uuid::Uuid;
33
34use crate::library::paths::receipts_path;
35
36/// Read the persisted custody-receipt log for an asset. An absent file is an empty log (`Ok`).
37pub fn load_receipts(
38 root: &Path,
39 uuid: &Uuid,
40 capture_utc: Option<i64>,
41) -> Result<Vec<CustodyReceipt>, CanonicalError> {
42 let path = receipts_path(root, uuid, capture_utc);
43 match fs::read(&path) {
44 Ok(bytes) if bytes.is_empty() => Ok(Vec::new()),
45 Ok(bytes) => cbor::from_slice(&bytes),
46 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
47 Err(e) => Err(CanonicalError::Deserialize(e.to_string())),
48 }
49}
50
51/// Errors persisting a receipt beside the provenance chain.
52#[derive(Debug, thiserror::Error)]
53pub enum ReceiptStoreError {
54 /// The receipt log could not be read/decoded or (re-)encoded.
55 #[error("receipt log codec: {0}")]
56 Codec(#[from] CanonicalError),
57 /// A filesystem error writing the log.
58 #[error("receipt log I/O: {0}")]
59 Io(String),
60}
61
62/// Append a verified receipt to the asset's on-disk log (`{uuid}.receipts.cbor`), idempotent on
63/// `receipt_seq`: re-persisting a receipt already present is a no-op, so a retried fetch never
64/// duplicates the log. The log is stored as canonical CBOR of the receipt `Vec` in chain order.
65pub fn append_receipt(
66 root: &Path,
67 capture_utc: Option<i64>,
68 receipt: &CustodyReceipt,
69) -> Result<(), ReceiptStoreError> {
70 let uuid = Uuid::parse_str(&receipt.core.asset_id)
71 .map_err(|e| ReceiptStoreError::Io(format!("receipt asset_id not a UUID: {e}")))?;
72 let mut log = load_receipts(root, &uuid, capture_utc)?;
73 if log
74 .iter()
75 .any(|r| r.core.receipt_seq == receipt.core.receipt_seq)
76 {
77 return Ok(());
78 }
79 log.push(receipt.clone());
80 log.sort_by_key(|r| r.core.receipt_seq);
81 let path = receipts_path(root, &uuid, capture_utc);
82 if let Some(parent) = path.parent() {
83 fs::create_dir_all(parent).map_err(|e| ReceiptStoreError::Io(e.to_string()))?;
84 }
85 let bytes = cbor::to_canonical_vec(&log)?;
86 fs::write(&path, bytes).map_err(|e| ReceiptStoreError::Io(e.to_string()))?;
87 Ok(())
88}
89
90#[cfg(test)]
91mod tests;