capsule_library/library/attestations.rs
1//! Client-side signed storage attestations — the evidence form of the durability verdict, kept
2//! beside the asset's custody receipts (SSoT:
3//! [Transfer — Durability: Signed Storage Attestation](https://docs/design/transfer/durability/#signed-storage-attestation)).
4//!
5//! A [`StorageAttestation`] is the server's signed answer to "do you hold these blobs?", bound
6//! to a nonce the client drew. A receipt proves the server *accepted* a blob; an attestation
7//! proves what the server *said it held* at `checked_at`, including an honest server's
8//! self-reported loss. Proof of loss names "a signed attestation reporting `H` not stored" as
9//! the evidence of later non-holding, so an attestation the client threw away is evidence lost.
10//!
11//! This module is the client's **persistence** path, and only that. The type and its
12//! verification live in [`capsule_core::crypto::storage_attestation`], shared with the server that
13//! signs it. Nothing here verifies a signature — the library holds no attestation keys — so a
14//! caller appends only an attestation it has already verified for the request it made
15//! (`capsule_sdk::verify::StorageVerifyClient::verify_signed`).
16//!
17//! # The log
18//!
19//! `media/{YYYY}/{YYYY-MM}/{uuid}.attestations.cbor` is canonical CBOR of an array of byte
20//! strings, each one attestation exactly as the server signed it, in the order the client
21//! received them. One attestation answers for every asset a request asked about, so the same
22//! bytes are appended to the log of each asset it names. The log is append-only and
23//! idempotent on the attestation's nonce: re-persisting an attestation already present is a
24//! no-op, so a retried run never duplicates it. Persistence is first-class, not a cache: the log
25//! is included verbatim in the backup artifact.
26
27use std::fs;
28use std::path::Path;
29
30use capsule_core::cbor::{self, CanonicalError};
31pub use capsule_core::crypto::storage_attestation::StorageAttestation;
32use serde_bytes::ByteBuf;
33use uuid::Uuid;
34
35use crate::library::paths::{attestations_path, tmp_path};
36
37/// Errors reading or persisting an asset's attestation log.
38#[derive(Debug, thiserror::Error)]
39pub enum AttestationStoreError {
40 /// The log, or an attestation in it or offered to it, could not be decoded or encoded.
41 #[error("attestation log codec: {0}")]
42 Codec(#[from] CanonicalError),
43 /// The attestation carries no verdict for the asset whose log it was offered to, so it is
44 /// not evidence about that asset.
45 #[error("the attestation does not answer for asset {0}")]
46 NotAboutAsset(Uuid),
47 /// A filesystem error reading or writing the log.
48 #[error("attestation log I/O: {0}")]
49 Io(String),
50}
51
52/// Read the raw attestation log of an asset: each entry is one attestation's canonical-CBOR
53/// bytes, as received. An absent file is an empty log.
54pub fn load_attestation_log(
55 root: &Path,
56 uuid: &Uuid,
57 capture_utc: Option<i64>,
58) -> Result<Vec<Vec<u8>>, AttestationStoreError> {
59 let path = attestations_path(root, uuid, capture_utc);
60 match fs::read(&path) {
61 Ok(bytes) if bytes.is_empty() => Ok(Vec::new()),
62 Ok(bytes) => {
63 let entries: Vec<ByteBuf> = cbor::from_slice(&bytes)?;
64 Ok(entries.into_iter().map(ByteBuf::into_vec).collect())
65 }
66 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
67 Err(e) => Err(AttestationStoreError::Io(e.to_string())),
68 }
69}
70
71/// Read and decode the attestation log of an asset, in the order the attestations were
72/// received. An absent file is an empty log.
73pub fn load_attestations(
74 root: &Path,
75 uuid: &Uuid,
76 capture_utc: Option<i64>,
77) -> Result<Vec<StorageAttestation>, AttestationStoreError> {
78 load_attestation_log(root, uuid, capture_utc)?
79 .iter()
80 .map(|bytes| StorageAttestation::from_canonical_cbor(bytes).map_err(Into::into))
81 .collect()
82}
83
84/// Append a verified attestation (`cbor`, its bytes as received) to the log of `asset`.
85///
86/// Refused with [`AttestationStoreError::NotAboutAsset`] when the attestation carries no
87/// verdict for `asset`. Idempotent on the nonce: returns `Ok(false)` without writing when an
88/// attestation with the same nonce is already in the log, and `Ok(true)` when it appended.
89/// The log is rewritten through a temporary sibling and a rename, so a crash mid-write leaves
90/// the previous log whole.
91#[tracing::instrument(skip(root, cbor), fields(%asset, bytes = cbor.len()))]
92pub fn append_attestation(
93 root: &Path,
94 asset: &Uuid,
95 capture_utc: Option<i64>,
96 cbor: &[u8],
97) -> Result<bool, AttestationStoreError> {
98 let attestation = StorageAttestation::from_canonical_cbor(cbor)?;
99 let asset_text = asset.to_string();
100 if !attestation
101 .core
102 .verdicts
103 .iter()
104 .any(|verdict| verdict.asset_id == asset_text)
105 {
106 tracing::warn!("attestation log: refused an attestation that does not name the asset");
107 return Err(AttestationStoreError::NotAboutAsset(*asset));
108 }
109
110 let mut log = load_attestation_log(root, asset, capture_utc)?;
111 for existing in &log {
112 let existing = StorageAttestation::from_canonical_cbor(existing)?;
113 if existing.core.nonce == attestation.core.nonce {
114 tracing::debug!("attestation log: already holds this nonce; nothing to append");
115 return Ok(false);
116 }
117 }
118 log.push(cbor.to_vec());
119
120 let path = attestations_path(root, asset, capture_utc);
121 if let Some(parent) = path.parent() {
122 fs::create_dir_all(parent).map_err(|e| AttestationStoreError::Io(e.to_string()))?;
123 }
124 let entries: Vec<ByteBuf> = log.into_iter().map(ByteBuf::from).collect();
125 let bytes = cbor::to_canonical_vec(&entries)?;
126 let tmp = tmp_path(&path);
127 fs::write(&tmp, &bytes).map_err(|e| AttestationStoreError::Io(e.to_string()))?;
128 fs::rename(&tmp, &path).map_err(|e| AttestationStoreError::Io(e.to_string()))?;
129 tracing::debug!(
130 entries = entries.len(),
131 checked_at = %attestation.core.checked_at,
132 "attestation log: appended"
133 );
134 Ok(true)
135}
136
137#[cfg(test)]
138mod tests;