Skip to main content

capsule_core/crypto/
storage_attestation.rs

1//! Signed storage attestations — the durability verdict in a form a client can keep (SSoT:
2//! [Transfer — Durability: Signed Storage Attestation](https://docs/design/transfer/durability/#signed-storage-attestation)).
3//!
4//! `POST /v1/storage/verify` answers whether the server holds what a client is about to stop
5//! holding. Unsigned, that answer is a claim the server can later deny. Signed under the server
6//! attestation key — the key that signs [custody receipts](crate::crypto::receipts) — and bound to
7//! a nonce the client chose, it is evidence: an honest server's self-reported loss and a periodic
8//! audit both become statements the server cannot take back.
9//!
10//! # Why this lives in `crypto`
11//!
12//! For the reason [`crate::crypto::receipts`] does: the server that signs an attestation links
13//! `capsule-core` without `native`, and a signed structure defined at both ends stops verifying
14//! the day either copy gains a field. One definition, ungated and shared. It must stay
15//! `std::fs`-free; persisting an attestation is the client library's business.
16//!
17//! # What the nonce is for
18//!
19//! A signed verdict with no client contribution can be replayed: a server that once held the
20//! bytes could answer a later audit with the old signature. The nonce is 32 bytes the client
21//! draws fresh per request and checks on the way back, so an attestation proves the server looked
22//! *after* the client asked. `checked_at` is the server's clock and evidentiary only; freshness
23//! rides the nonce.
24//!
25//! # What a client checks
26//!
27//! [`verify_storage_attestation`] accepts an attestation only when the signature verifies under
28//! a pinned attestation key, the version is this one, the nonce is the one the client sent, and
29//! the verdicts answer exactly the question the client asked — the same assets in the same order,
30//! each with the same declared hashes in the same order. An attestation that answers a different
31//! question is not evidence about this one, however validly it is signed.
32
33use serde::{Deserialize, Serialize};
34
35use crate::cbor::{self, CanonicalError};
36use crate::crypto::hash::Hash32;
37use crate::crypto::keys::{HybridSignature, HybridVerifyingKey};
38
39/// The schema version every storage attestation carries.
40///
41/// Also the domain separator from a custody receipt, which the same key signs: a receipt core
42/// carries `custody-receipt/v1` and a different field set, so neither decodes as the other.
43pub const STORAGE_ATTESTATION_VERSION: &str = "storage-attestation/v1";
44
45/// The length of the client's nonce, in bytes.
46pub const ATTESTATION_NONCE_LEN: usize = 32;
47
48/// The client's per-request nonce.
49pub type AttestationNonce = [u8; ATTESTATION_NONCE_LEN];
50
51/// One declared blob's verdict, as signed.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53pub struct AttestedBlob {
54    /// The content address the client declared.
55    pub hash: Hash32,
56    /// The role the asset holds it under, or `unknown` when the asset does not hold it.
57    pub role: String,
58    /// The bytes are present at that address.
59    pub stored: bool,
60    /// A live asset of the caller's references the address.
61    pub indexed: bool,
62    /// Nothing is withholding it.
63    pub retrievable: bool,
64    /// What a deep scan found — `intact`, `corrupt` or `rate_limited` — and absent when none ran.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub deep: Option<String>,
67}
68
69/// One asset's verdict, as signed.
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
71pub struct AttestedAsset {
72    /// The asset the client asked about.
73    pub asset_id: String,
74    /// Every declared blob is stored ∧ indexed ∧ retrievable.
75    pub durable: bool,
76    /// One entry per declared hash, in declaration order.
77    pub blobs: Vec<AttestedBlob>,
78}
79
80/// The signed core of a [`StorageAttestation`] — every field the attestation key covers.
81///
82/// Canonical CBOR with the manifest wire-presence discipline: an absent optional is an absent
83/// key, never a present `null`.
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
85pub struct StorageAttestationCore {
86    /// Schema version ([`STORAGE_ATTESTATION_VERSION`]).
87    pub version: String,
88    /// The server's canonical origin — binds the attestation to one server.
89    pub server_id: String,
90    /// Fingerprint of the attestation key that signed; survives rotation.
91    pub server_key_id: Hash32,
92    /// The account the verdicts were computed for. Verdicts are owner-scoped, so the same
93    /// question asked by another account has a different answer.
94    pub account: String,
95    /// The client's nonce, echoed.
96    #[serde(with = "serde_bytes")]
97    pub nonce: AttestationNonce,
98    /// The server's trusted clock when it looked (RFC 3339). Evidentiary only.
99    pub checked_at: String,
100    /// One verdict per asset the client asked about, in request order.
101    pub verdicts: Vec<AttestedAsset>,
102}
103
104impl StorageAttestationCore {
105    /// The canonical bytes the attestation signature covers.
106    #[must_use]
107    pub fn signing_bytes(&self) -> Vec<u8> {
108        cbor::to_canonical_vec(self).expect("storage-attestation core serializes")
109    }
110}
111
112/// A signed storage attestation: a [`StorageAttestationCore`] plus its hybrid signature.
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
114pub struct StorageAttestation {
115    /// The signed core.
116    pub core: StorageAttestationCore,
117    /// Hybrid Ed25519 + ML-DSA-65 signature under the server attestation key.
118    pub server_sig: HybridSignature,
119}
120
121impl StorageAttestation {
122    /// Decode a canonical-CBOR attestation (the served and persisted form).
123    pub fn from_canonical_cbor(bytes: &[u8]) -> Result<Self, CanonicalError> {
124        cbor::from_slice(bytes)
125    }
126
127    /// Encode the full signed attestation as canonical CBOR.
128    #[must_use]
129    pub fn to_canonical_cbor(&self) -> Vec<u8> {
130        cbor::to_canonical_vec(self).expect("storage attestation serializes")
131    }
132
133    /// Verify the hybrid signature under a specific attestation public key.
134    #[must_use]
135    pub fn verify_under(&self, key: &HybridVerifyingKey) -> bool {
136        key.verify(&self.core.signing_bytes(), &self.server_sig)
137    }
138}
139
140/// One asset the client asked about, with the hashes it declared — what an attestation must
141/// answer.
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct DeclaredAsset {
144    /// The asset id, as the client sent it.
145    pub asset_id: String,
146    /// The declared content addresses, in the order the client sent them.
147    pub blob_hashes: Vec<Hash32>,
148}
149
150/// Why an attestation was rejected. Every variant means it is not evidence for this request.
151#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
152pub enum AttestationRejection {
153    /// The signature did not verify under any pinned attestation key.
154    #[error("the attestation signature does not verify under a pinned key")]
155    Signature,
156    /// The attestation carries a schema version this client does not know.
157    #[error("unknown attestation version")]
158    Version,
159    /// The nonce is not the one this request sent: a replayed or misdirected attestation.
160    #[error("the attestation does not carry this request's nonce")]
161    Nonce,
162    /// The verdicts answer a different question from the one asked.
163    #[error("the attestation does not answer the request: {0}")]
164    Mismatch(&'static str),
165}
166
167/// Verify a storage attestation for one request.
168///
169/// Checks, in order: the signature under one of `pinned_keys` (the published attestation-key
170/// history), the schema version, the nonce, and that the verdicts cover exactly `declared` — the
171/// same assets in order, each with the same hashes in order. Returns `Ok(())` only when the
172/// attestation is admissible evidence for this request.
173pub fn verify_storage_attestation(
174    attestation: &StorageAttestation,
175    pinned_keys: &[HybridVerifyingKey],
176    nonce: &AttestationNonce,
177    declared: &[DeclaredAsset],
178) -> Result<(), AttestationRejection> {
179    if !pinned_keys.iter().any(|key| attestation.verify_under(key)) {
180        return Err(AttestationRejection::Signature);
181    }
182    let core = &attestation.core;
183    if core.version != STORAGE_ATTESTATION_VERSION {
184        return Err(AttestationRejection::Version);
185    }
186    if &core.nonce != nonce {
187        return Err(AttestationRejection::Nonce);
188    }
189    if core.verdicts.len() != declared.len() {
190        return Err(AttestationRejection::Mismatch("asset count"));
191    }
192    for (verdict, asked) in core.verdicts.iter().zip(declared) {
193        if verdict.asset_id != asked.asset_id {
194            return Err(AttestationRejection::Mismatch("asset_id"));
195        }
196        if verdict.blobs.len() != asked.blob_hashes.len()
197            || verdict
198                .blobs
199                .iter()
200                .zip(&asked.blob_hashes)
201                .any(|(blob, hash)| &blob.hash != hash)
202        {
203            return Err(AttestationRejection::Mismatch("blob_hashes"));
204        }
205    }
206    Ok(())
207}
208
209#[cfg(test)]
210mod tests;