capsule_library/library/storage_verify.rs
1//! The verify-before-destroy gate — client half of storage verification (SSoT:
2//! [Transfer — Durability](https://docs/design/transfer/durability/)).
3//!
4//! Before any post-write local cleanup of irreplaceable bytes (releasing a device-owned
5//! original, deleting a Move-import source, a streaming-mode release), a client requires
6//! **both** halves to pass: `verify_asset` accepts the asset (crypto validity — the
7//! offline core already implements it) and the server's `POST /storage/verify` verdict is
8//! `durable` (stored ∧ indexed ∧ retrievable for every required blob). The predicate here
9//! is the pure conjunction those call sites consume; fetching the verdict goes through the
10//! `StorageVerifier` seam.
11
12use std::fs;
13use std::path::Path;
14
15use capsule_core::crypto::hash::Hash32;
16/// A blob's role within an asset, as the storage-verification endpoint reports it.
17///
18/// Defined in [`capsule_core::crypto::receipts`] and re-exported here, because a custody receipt's
19/// `blob_role` is written from the same enum and the issuer and the verifier must not each
20/// have their own. This path is the one the transfer durability doc names, so it
21/// stays.
22pub use capsule_core::crypto::receipts::BlobRole;
23use uuid::Uuid;
24
25use crate::db::DatabaseDriver;
26
27/// The server's key-free per-blob verdict.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct BlobVerdict {
30 /// The content address the client declared it relies on.
31 pub hash: Hash32,
32 /// The blob's role on the asset.
33 pub role: BlobRole,
34 /// Present in the blob store at its content address (`stat`), not merely in-flight.
35 pub stored: bool,
36 /// Referenced by a committed, `uploaded = true` index row.
37 pub indexed: bool,
38 /// Refcount > 0, not mid-GC (`collectable_since`), not quarantined.
39 pub retrievable: bool,
40}
41
42impl BlobVerdict {
43 /// One blob's contribution to durability: all three independent facts hold.
44 pub fn safely_stored(&self) -> bool {
45 self.stored && self.indexed && self.retrievable
46 }
47}
48
49/// The per-asset verdict from `POST /storage/verify`. `durable` attests **this home
50/// server's** storage only — never replicas or peers.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct StorageVerdict {
53 /// The asset the verdict is for.
54 pub asset_id: Uuid,
55 /// Server-computed: every required blob is stored ∧ indexed ∧ retrievable.
56 pub durable: bool,
57 /// Per-blob detail, one entry per hash the client declared.
58 pub blobs: Vec<BlobVerdict>,
59 /// The server's trusted clock at verification (RFC 3339, like `received_at`).
60 pub checked_at: String,
61}
62
63/// The verify-before-destroy predicate: destructive local cleanup of irreplaceable bytes
64/// may proceed **only** when the server's verdict is `durable`, every declared blob
65/// individually re-checks as safely stored (the client never trusts the server's
66/// aggregate over the details it can recompute), and `verify_asset` accepted the asset.
67///
68/// A `false` result never triggers a destructive action — the caller retains the local
69/// copy, retries with backoff, and surfaces "not yet confirmed on server".
70pub fn release_is_safe(verdict: &StorageVerdict, verify_asset_accepted: bool) -> bool {
71 verify_asset_accepted
72 && verdict.durable
73 && !verdict.blobs.is_empty()
74 && verdict.blobs.iter().all(BlobVerdict::safely_stored)
75}
76
77// ─── The release gate seam ────────────────────────────────────────────────────
78
79/// A transport error fetching a verdict or receipt from the server. A gate that cannot reach a
80/// definitive `durable`/receipt answer **never** destroys — the caller retains and retries.
81#[derive(Debug, thiserror::Error)]
82pub enum VerifierError {
83 /// The `POST /storage/verify` or receipt fetch failed on the wire or server-side.
84 #[error("storage verifier transport: {0}")]
85 Transport(String),
86}
87
88/// The client's source of the server-side facts the gate needs: the key-free `/storage/verify`
89/// verdict and whether a **verified** custody receipt is held for the write. The `capsule-sdk`
90/// fills this over HTTP (`POST /storage/verify` + `GET …/receipt` verified under the pinned
91/// attestation key); tests fill it with deterministic mocks. Sync by construction — the offline
92/// data plane calls it; async callers resolve the futures before invoking the gate.
93pub trait StorageVerifier {
94 /// Fetch a fresh `/storage/verify` verdict for the asset's declared blob hashes.
95 fn verify(
96 &self,
97 asset_id: Uuid,
98 blob_hashes: &[Hash32],
99 ) -> Result<StorageVerdict, VerifierError>;
100
101 /// Whether a custody receipt covering the write is held **and verifies** under the pinned
102 /// attestation key with fields matching what the client sent. `false` (not an error) means
103 /// missing-or-unverified, which the gate treats as refuse-to-release.
104 fn receipt_verified(
105 &self,
106 asset_id: Uuid,
107 blob_hashes: &[Hash32],
108 ) -> Result<bool, VerifierError>;
109}
110
111/// Why the gate refused to release. Every variant retains the local bytes.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub enum RetainReason {
114 /// The server's verdict was not `durable` (or a per-blob re-check disagreed, or
115 /// `verify_asset` rejected the asset).
116 NotDurable,
117 /// No verified custody receipt is held for the write (missing or unverified).
118 ReceiptMissing,
119 /// The verdict fetch failed on the wire — retry with backoff.
120 VerifyUnavailable,
121 /// The receipt fetch failed on the wire — retry with backoff.
122 ReceiptUnavailable,
123 /// The read-back check failed: the library copy, or the Move source itself, no longer
124 /// hashes to the asset's signed original. Deleting the source could lose the only copy of
125 /// those bytes, so it is kept whatever the server says.
126 ReadBackMismatch,
127}
128
129/// The gate's decision. `Release` is returned **only** when all three checks pass (durable
130/// verdict, matching per-blob detail + `verify_asset`, and a verified receipt).
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub enum ReleaseDecision {
133 /// Every check passed; destroying the local bytes is safe.
134 Release,
135 /// A check did not pass; the local bytes are retained.
136 Retain(RetainReason),
137}
138
139impl ReleaseDecision {
140 /// Whether this decision permits destroying the local bytes.
141 #[must_use]
142 pub fn is_release(&self) -> bool {
143 matches!(self, ReleaseDecision::Release)
144 }
145}
146
147/// The verify-before-destroy gate over a [`StorageVerifier`]. It never destroys anything itself:
148/// [`may_release`](Self::may_release) is the pure decision the three destructive paths
149/// (device-owned-original release, Move-import source deletion, streaming-mode release) consult
150/// before any local cleanup, and streaming import drives its per-asset release window
151/// through the same call.
152pub struct ReleaseGate<'a, V: StorageVerifier + ?Sized> {
153 verifier: &'a V,
154}
155
156impl<'a, V: StorageVerifier + ?Sized> ReleaseGate<'a, V> {
157 /// Build a gate over a verifier.
158 pub fn new(verifier: &'a V) -> Self {
159 Self { verifier }
160 }
161
162 /// Decide whether the write's local bytes may be released. Both halves of the gate are
163 /// required: the server's verdict must be `durable` (with every declared blob individually
164 /// re-checking as safely stored and `verify_asset` having accepted the asset — the
165 /// [`release_is_safe`] conjunction), **and** a verified custody receipt must be held. A
166 /// transport failure on either fetch yields a `Retain`, never a destroy.
167 pub fn may_release(
168 &self,
169 asset_id: Uuid,
170 blob_hashes: &[Hash32],
171 verify_asset_accepted: bool,
172 ) -> ReleaseDecision {
173 let Ok(verdict) = self.verifier.verify(asset_id, blob_hashes) else {
174 return ReleaseDecision::Retain(RetainReason::VerifyUnavailable);
175 };
176 if !release_is_safe(&verdict, verify_asset_accepted) {
177 return ReleaseDecision::Retain(RetainReason::NotDurable);
178 }
179 match self.verifier.receipt_verified(asset_id, blob_hashes) {
180 Ok(true) => ReleaseDecision::Release,
181 Ok(false) => ReleaseDecision::Retain(RetainReason::ReceiptMissing),
182 Err(_) => ReleaseDecision::Retain(RetainReason::ReceiptUnavailable),
183 }
184 }
185}
186
187// ─── The three destructive paths, gated ───────────────────────────────────────
188
189/// **Device-owned-original release** (the cache-eviction sweep's counterpart for owned
190/// originals, which [`cache_sweep`](crate::library::cache_sweep) never touches
191/// automatically). An original the device itself uploaded is the source of truth until the
192/// server durably holds it; it is released — its local file deleted and its owned-original
193/// representation row dropped, after which it becomes an ordinary server-only, re-fetchable
194/// asset — **only** on a `Release` decision. On any `Retain` the file and row are untouched.
195pub fn release_owned_original<V: StorageVerifier + ?Sized>(
196 db: &DatabaseDriver,
197 verifier: &V,
198 asset_id: Uuid,
199 local_path: &Path,
200 blob_hashes: &[Hash32],
201 verify_asset_accepted: bool,
202) -> Result<ReleaseDecision, rusqlite::Error> {
203 let decision =
204 ReleaseGate::new(verifier).may_release(asset_id, blob_hashes, verify_asset_accepted);
205 if decision.is_release() {
206 let _ = fs::remove_file(local_path);
207 db.remove_representation(&asset_id.to_string(), "original")?;
208 }
209 Ok(decision)
210}
211
212/// **Move-import source deletion.** Deleting the external source after a Move-mode import waits
213/// on the server's `durable` verdict + a verified receipt — never on the local library copy
214/// alone — so a crash mid-import cannot lose the only copy. Returns the decision; the source is
215/// unlinked only on `Release`. The gate alone: a caller holding the library uses
216/// [`Workspace::release_move_source`](crate::lifecycle::Workspace::release_move_source), which
217/// adds the read-back hash check before it reaches here.
218pub fn release_move_source<V: StorageVerifier + ?Sized>(
219 verifier: &V,
220 asset_id: Uuid,
221 src_path: &Path,
222 blob_hashes: &[Hash32],
223 verify_asset_accepted: bool,
224) -> ReleaseDecision {
225 let decision =
226 ReleaseGate::new(verifier).may_release(asset_id, blob_hashes, verify_asset_accepted);
227 if decision.is_release() {
228 let _ = fs::remove_file(src_path);
229 }
230 decision
231}
232
233#[cfg(test)]
234mod tests;