Skip to main content

capsule_sdk/
verify.rs

1//! Verify-before-destroy: the client half of storage verification (SSoT:
2//! [Storage Verification — Verify Before Destroy]).
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//! **three** complementary facts, all fetched here and combined through the offline data
7//! plane's pure predicates:
8//!
9//! 1. **Durability.** [`StorageVerifyClient::verify`] calls `POST /storage/verify` and maps the
10//!    response into [`capsule_library::library::StorageVerdict`]; the gate applies
11//!    [`capsule_library::library::release_is_safe`], which re-checks every declared blob rather
12//!    than trusting the server's aggregate.
13//! 2. **Accountability.** [`StorageVerifyClient::fetch_receipt`] fetches the write's
14//!    [`CustodyReceipt`] and
15//!    [`capsule_library::library::verify_receipt`] checks the hybrid signature under the pinned
16//!    attestation key plus a field match against what the client sent. A server that withholds
17//!    receipts never becomes the sole holder of an only-copy.
18//! 3. **Crypto validity.** `verify_asset` (the caller's offline check) must have accepted the
19//!    asset — passed in as `verify_asset_accepted`.
20//!
21//! Beside the gate, [`StorageVerifyClient::verify_signed`] asks for the verdict in its **signed**
22//! form, bound to a client nonce and verified under the same pinned attestation keys, so a
23//! client can keep the server's own statement of what it holds — or has lost — as evidence.
24//!
25//! [`ReleaseCoordinator`] composes the three and enforces the **60-second re-verify window**:
26//! the verdict is a point-in-time fact, so a verdict older than the window is re-fetched before
27//! release. The result is a [`capsule_library::library::ReleaseDecision`]; a non-`Release` outcome
28//! never destroys — the caller retains the local copy, retries with backoff, and surfaces
29//! "not yet confirmed on server". Streaming import drives this per asset in its
30//! import→upload→verify→release window.
31//!
32//! [Storage Verification — Verify Before Destroy]: https://docs/design/transfer/durability/#verify-before-destroy
33
34use std::collections::HashMap;
35use std::sync::Mutex;
36
37use base64::Engine as _;
38use capsule_core::crypto::hash::Hash32;
39use capsule_core::crypto::keys::HybridVerifyingKey;
40use capsule_core::crypto::storage_attestation::{
41    ATTESTATION_NONCE_LEN, AttestationNonce, AttestationRejection, DeclaredAsset,
42    StorageAttestation, verify_storage_attestation,
43};
44use capsule_library::library::{
45    BlobRole, BlobVerdict, CustodyReceipt, ReceiptExpectations, ReleaseDecision, RetainReason,
46    StorageVerdict, StorageVerifier, VerifierError, release_is_safe, verify_receipt,
47};
48use capsule_library::lifecycle::{AssetState, UploadBundle};
49use serde::{Deserialize, Serialize};
50use tracing::{debug, instrument, warn};
51use uuid::Uuid;
52
53// ─── Errors ───────────────────────────────────────────────────────────────────
54
55/// A failure fetching or decoding a verdict, receipt, or attestation-key document. The gate
56/// folds these into a `Retain` decision — a client never destroys on an unresolved fetch.
57#[derive(Debug, thiserror::Error)]
58pub enum VerifyError {
59    /// The HTTP request failed on the wire, or the session could not authorize it.
60    #[error("storage-verify transport: {0}")]
61    Transport(String),
62    /// The server answered with a non-success status.
63    #[error("storage-verify server status {status}")]
64    Status {
65        /// The HTTP status code.
66        status: u16,
67        /// The stable `error.*` code, when the server supplied one.
68        code: Option<String>,
69    },
70    /// The response body was missing a field or otherwise unparsable.
71    #[error("malformed storage-verify response: {0}")]
72    Malformed(String),
73    /// A signed verdict came back and is not evidence for this request: a signature that does
74    /// not verify under a pinned attestation key, another request's nonce, or verdicts that
75    /// answer a different question.
76    #[error("storage attestation rejected: {0}")]
77    Attestation(AttestationRejection),
78    /// The server will not take this client's writes: its `426`, or a window it advertised
79    /// that already refuses this build (issue #674). Update the app.
80    #[error(transparent)]
81    UpgradeRequired(Box<crate::net::negotiation::UpgradeRequired>),
82}
83
84impl VerifyError {
85    /// The stable `error.*` code, when one applies.
86    #[must_use]
87    pub fn error_code(&self) -> Option<&str> {
88        match self {
89            Self::Status { code, .. } => code.as_deref(),
90            Self::UpgradeRequired(refusal) => Some(refusal.error_code()),
91            _ => None,
92        }
93    }
94}
95
96impl From<crate::auth::AuthError> for VerifyError {
97    fn from(err: crate::auth::AuthError) -> Self {
98        match err {
99            crate::auth::AuthError::UpgradeRequired(refusal) => {
100                VerifyError::UpgradeRequired(refusal)
101            }
102            other => VerifyError::Transport(other.to_string()),
103        }
104    }
105}
106
107impl From<crate::net::negotiation::SendError> for VerifyError {
108    fn from(err: crate::net::negotiation::SendError) -> Self {
109        match err {
110            crate::net::negotiation::SendError::Upgrade(refusal) => {
111                VerifyError::UpgradeRequired(Box::new(refusal))
112            }
113            crate::net::negotiation::SendError::Transport(error) => {
114                VerifyError::Transport(error.to_string())
115            }
116        }
117    }
118}
119
120// ─── Authorized transport ──────────────────────────────────────────────────────
121
122/// A fixed bearer token, for tests and callers that already hold a live token.
123#[derive(Debug, Clone)]
124pub struct StaticToken(pub String);
125
126#[derive(Clone)]
127enum VerifyAuth {
128    /// Drive requests through the SDK session (pre-flight refresh, single-flight, one `401`
129    /// refresh-and-replay).
130    Session(crate::auth::Session),
131    /// A fixed bearer over a plain client (tests).
132    Static {
133        http: reqwest::Client,
134        token: String,
135    },
136}
137
138/// The authorized HTTP transport for the storage-verification + receipt surfaces: the API root
139/// (no trailing slash) plus the authorization seam.
140#[derive(Clone)]
141pub struct VerifyTransport {
142    base_url: String,
143    auth: VerifyAuth,
144}
145
146impl VerifyTransport {
147    /// Build a transport that authorizes through an authenticated SDK session — the
148    /// sanctioned production path. `base_url` is the API root (`POST {base}/storage/verify`,
149    /// `GET {base}/upload/{id}/receipt`, `GET {base}/assets/{id}/receipts`); the attestation-key
150    /// record is resolved against its origin instead (see
151    /// [`StorageVerifyClient::fetch_attestation_keys`]).
152    pub fn with_session(session: crate::auth::Session, base_url: impl Into<String>) -> Self {
153        Self {
154            base_url: base_url.into().trim_end_matches('/').to_string(),
155            auth: VerifyAuth::Session(session),
156        }
157    }
158
159    /// Build a transport over a fixed bearer token (tests; callers holding a live token).
160    ///
161    /// `http` **must** come from [`crate::net::http_builder`] or [`crate::net::http_client`]: a
162    /// client built any other way sends no protocol handshake, and every gated route refuses it.
163    pub fn with_static_token(
164        http: reqwest::Client,
165        base_url: impl Into<String>,
166        token: StaticToken,
167    ) -> Self {
168        Self {
169            base_url: base_url.into().trim_end_matches('/').to_string(),
170            auth: VerifyAuth::Static {
171                http,
172                token: token.0,
173            },
174        }
175    }
176
177    async fn send<F>(&self, build: F) -> Result<reqwest::Response, VerifyError>
178    where
179        F: Fn(&reqwest::Client) -> reqwest::RequestBuilder,
180    {
181        match &self.auth {
182            VerifyAuth::Session(session) => Ok(session.execute(build).await?),
183            VerifyAuth::Static { http, token } => Ok(crate::net::negotiation::send_negotiated(
184                build(http).bearer_auth(token),
185            )
186            .await?),
187        }
188    }
189}
190
191// ─── Wire DTOs (mirror the server's transport JSON) ─────────────────────────────
192
193/// One asset to verify: the exact blob hashes the client is relying on.
194#[derive(Debug, Clone)]
195pub struct AssetQuery {
196    /// The asset id.
197    pub asset_id: Uuid,
198    /// Every blob content address (as `Hash32`) the client relies on.
199    pub blob_hashes: Vec<Hash32>,
200}
201
202#[derive(Serialize)]
203struct AssetVerifyRequestWire {
204    asset_id: String,
205    blob_hashes: Vec<String>,
206}
207
208#[derive(Serialize)]
209struct StorageVerifyRequestWire {
210    assets: Vec<AssetVerifyRequestWire>,
211    deep: bool,
212    /// Present only on a signed request, so an unsigned one is byte-identical to before.
213    #[serde(skip_serializing_if = "Option::is_none")]
214    attestation_nonce: Option<String>,
215}
216
217#[derive(Deserialize)]
218struct BlobVerdictWire {
219    hash: String,
220    role: String,
221    stored: bool,
222    indexed: bool,
223    retrievable: bool,
224}
225
226#[derive(Deserialize)]
227struct StorageVerdictWire {
228    asset_id: String,
229    durable: bool,
230    blobs: Vec<BlobVerdictWire>,
231    checked_at: String,
232}
233
234#[derive(Deserialize)]
235struct StorageVerifyResponseWire {
236    verdicts: Vec<StorageVerdictWire>,
237    /// Base64 of the canonical-CBOR [`StorageAttestation`], on a signed request only.
238    #[serde(default)]
239    attestation: Option<String>,
240}
241
242#[derive(Deserialize)]
243struct ApiErrorWire {
244    #[serde(default)]
245    code: Option<String>,
246}
247
248/// The role string the server uses, mapped to the closed core enum (`unknown` and anything
249/// unrecognized fall to `Derivative` — the safest bucket, since it does not satisfy the
250/// required-blob set the gate re-checks).
251fn role_from_str(role: &str) -> BlobRole {
252    match role {
253        "original" => BlobRole::Original,
254        "metadata" => BlobRole::Metadata,
255        "provenance" => BlobRole::Provenance,
256        _ => BlobRole::Derivative,
257    }
258}
259
260impl StorageVerdictWire {
261    fn into_core(self) -> Result<StorageVerdict, VerifyError> {
262        let asset_id = Uuid::parse_str(&self.asset_id)
263            .map_err(|e| VerifyError::Malformed(format!("verdict asset_id: {e}")))?;
264        let blobs = self
265            .blobs
266            .into_iter()
267            .map(|b| {
268                let hash = Hash32::from_hex(&b.hash)
269                    .map_err(|_| VerifyError::Malformed(format!("blob hash: {}", b.hash)))?;
270                Ok(BlobVerdict {
271                    hash,
272                    role: role_from_str(&b.role),
273                    stored: b.stored,
274                    indexed: b.indexed,
275                    retrievable: b.retrievable,
276                })
277            })
278            .collect::<Result<Vec<_>, VerifyError>>()?;
279        Ok(StorageVerdict {
280            asset_id,
281            durable: self.durable,
282            blobs,
283            checked_at: self.checked_at,
284        })
285    }
286}
287
288/// A signed verdict that verified for the request it answers.
289///
290/// `cbor` is the attestation exactly as the server signed it — the bytes a client keeps as
291/// evidence, beside its custody receipts. `verdicts` is read from the **signed** core, never from
292/// the unsigned JSON projection beside it, so nothing a caller acts on was outside the signature.
293#[derive(Debug, Clone, PartialEq, Eq)]
294pub struct VerifiedAttestation {
295    /// The decoded, verified attestation.
296    pub attestation: StorageAttestation,
297    /// Its canonical-CBOR bytes, as received.
298    pub cbor: Vec<u8>,
299    /// The signed verdicts, one per asset asked about, in request order.
300    pub verdicts: Vec<StorageVerdict>,
301}
302
303/// Read the verdicts out of a verified attestation's signed core.
304fn signed_verdicts(attestation: &StorageAttestation) -> Result<Vec<StorageVerdict>, VerifyError> {
305    attestation
306        .core
307        .verdicts
308        .iter()
309        .map(|asset| {
310            let asset_id = Uuid::parse_str(&asset.asset_id)
311                .map_err(|e| VerifyError::Malformed(format!("attested asset_id: {e}")))?;
312            Ok(StorageVerdict {
313                asset_id,
314                durable: asset.durable,
315                blobs: asset
316                    .blobs
317                    .iter()
318                    .map(|blob| BlobVerdict {
319                        hash: blob.hash,
320                        role: role_from_str(&blob.role),
321                        stored: blob.stored,
322                        indexed: blob.indexed,
323                        retrievable: blob.retrievable,
324                    })
325                    .collect(),
326                checked_at: attestation.core.checked_at.clone(),
327            })
328        })
329        .collect()
330}
331
332/// One entry of the `GET /assets/{id}/receipts` chain: `receipt_cbor` is base64 of the full
333/// signed canonical-CBOR receipt (the route's other fields are a reading of those bytes and are
334/// not trusted). `GET /upload/{id}/receipt` does **not** use this shape — it serves the raw
335/// `application/cbor` bytes; see [`StorageVerifyClient::fetch_receipt`].
336#[derive(Deserialize)]
337struct ReceiptWire {
338    receipt_cbor: String,
339}
340
341#[derive(Deserialize)]
342struct AssetReceiptsResponseWire {
343    receipts: Vec<ReceiptWire>,
344}
345
346/// The `.well-known` attestation-key publication (append-only history).
347#[derive(Deserialize)]
348struct PublishedKeyWire {
349    public: String,
350}
351
352#[derive(Deserialize)]
353struct WellKnownAttestationWire {
354    keys: Vec<PublishedKeyWire>,
355}
356
357// ─── The client ─────────────────────────────────────────────────────────────────
358
359/// The storage-verification + custody-receipt client over an authorized [`VerifyTransport`].
360#[derive(Clone)]
361pub struct StorageVerifyClient {
362    transport: VerifyTransport,
363}
364
365impl StorageVerifyClient {
366    /// Build a client over an authorized transport.
367    pub fn new(transport: VerifyTransport) -> Self {
368        Self { transport }
369    }
370
371    /// `POST /storage/verify`: confirm each asset's declared blobs are stored, indexed, and
372    /// retrievable. `deep` opt-in re-hashes bytes (server-priced) — leave `false` on the hot
373    /// verify-before-destroy path.
374    #[instrument(skip_all, fields(assets = assets.len(), deep))]
375    pub async fn verify(
376        &self,
377        assets: &[AssetQuery],
378        deep: bool,
379    ) -> Result<Vec<StorageVerdict>, VerifyError> {
380        let wire = self.post_verify(assets, deep, None).await?;
381        wire.verdicts
382            .into_iter()
383            .map(StorageVerdictWire::into_core)
384            .collect()
385    }
386
387    /// `POST /storage/verify` for the **signed** verdict, bound to `nonce`, verified under
388    /// `pinned_keys` (the published attestation-key history).
389    ///
390    /// Returns the attestation only when its signature verifies, it carries `nonce`, and its
391    /// verdicts answer exactly `assets` — the same assets and declared hashes, in order. Anything
392    /// else is [`VerifyError::Attestation`]; a response with no attestation at all is
393    /// [`VerifyError::Malformed`]. The server prices a signed request like `deep`, so a spent
394    /// budget is [`VerifyError::Status`] with `429` and `error.storage.deep_rate_limited`.
395    ///
396    /// `nonce` must be fresh per request — [`ReleaseCoordinator::fetch_verified_attestation`]
397    /// draws one — or a replayed answer to an earlier request would verify.
398    #[instrument(skip_all, fields(assets = assets.len(), deep))]
399    pub async fn verify_signed(
400        &self,
401        assets: &[AssetQuery],
402        deep: bool,
403        nonce: &AttestationNonce,
404        pinned_keys: &[HybridVerifyingKey],
405    ) -> Result<VerifiedAttestation, VerifyError> {
406        let wire = self.post_verify(assets, deep, Some(nonce)).await?;
407        let encoded = wire.attestation.ok_or_else(|| {
408            VerifyError::Malformed("a signed verdict was asked for and none came back".into())
409        })?;
410        let cbor = base64::engine::general_purpose::STANDARD
411            .decode(encoded.as_bytes())
412            .map_err(|e| VerifyError::Malformed(format!("attestation base64: {e}")))?;
413        let attestation = StorageAttestation::from_canonical_cbor(&cbor)
414            .map_err(|e| VerifyError::Malformed(format!("attestation cbor: {e}")))?;
415
416        let declared: Vec<DeclaredAsset> = assets
417            .iter()
418            .map(|asset| DeclaredAsset {
419                asset_id: asset.asset_id.to_string(),
420                blob_hashes: asset.blob_hashes.clone(),
421            })
422            .collect();
423        verify_storage_attestation(&attestation, pinned_keys, nonce, &declared).map_err(
424            |rejection| {
425                warn!(%rejection, "a storage attestation did not verify");
426                VerifyError::Attestation(rejection)
427            },
428        )?;
429        let verdicts = signed_verdicts(&attestation)?;
430        debug!(
431            key_id = %attestation.core.server_key_id,
432            checked_at = %attestation.core.checked_at,
433            "storage attestation verified"
434        );
435        Ok(VerifiedAttestation {
436            attestation,
437            cbor,
438            verdicts,
439        })
440    }
441
442    /// The one `POST /storage/verify` both forms send.
443    async fn post_verify(
444        &self,
445        assets: &[AssetQuery],
446        deep: bool,
447        nonce: Option<&AttestationNonce>,
448    ) -> Result<StorageVerifyResponseWire, VerifyError> {
449        let body = StorageVerifyRequestWire {
450            assets: assets
451                .iter()
452                .map(|a| AssetVerifyRequestWire {
453                    asset_id: a.asset_id.to_string(),
454                    blob_hashes: a.blob_hashes.iter().map(Hash32::to_hex).collect(),
455                })
456                .collect(),
457            deep,
458            attestation_nonce: nonce.map(|nonce| Hash32::from_bytes(*nonce).to_hex()),
459        };
460        let url = format!("{}/storage/verify", self.transport.base_url);
461        let response = self
462            .transport
463            .send(|http| http.post(&url).json(&body))
464            .await?;
465        let response = check_status(response).await?;
466        response
467            .json()
468            .await
469            .map_err(|e| VerifyError::Malformed(e.to_string()))
470    }
471
472    /// `GET /upload/{id}/receipt`: the session-window custody-receipt fetch (pairs with lost-ACK
473    /// recovery). Returns the decoded, signed receipt — verify it with
474    /// [`capsule_library::library::verify_receipt`] before trusting it.
475    ///
476    /// The server serves the receipt as `application/cbor`: the body **is** the signed canonical
477    /// encoding, so it is decoded from the bytes as they arrived and never round-trips through
478    /// a JSON or base64 projection that could hand the verifier bytes the signature does not
479    /// cover.
480    #[instrument(skip_all, fields(%upload_id))]
481    pub async fn fetch_receipt(&self, upload_id: Uuid) -> Result<CustodyReceipt, VerifyError> {
482        let url = format!("{}/upload/{upload_id}/receipt", self.transport.base_url);
483        let response = self.transport.send(|http| http.get(&url)).await?;
484        let response = check_status(response).await?;
485        let bytes = response
486            .bytes()
487            .await
488            .map_err(|e| VerifyError::Transport(e.to_string()))?;
489        debug!(len = bytes.len(), "custody receipt bytes received");
490        decode_receipt_cbor(&bytes)
491    }
492
493    /// `GET /assets/{asset_id}/receipts`: the durable, permanent receipt log for an asset, in
494    /// chain order. Each is signed — verify before trusting.
495    #[instrument(skip_all, fields(%asset_id))]
496    pub async fn fetch_asset_receipts(
497        &self,
498        asset_id: Uuid,
499    ) -> Result<Vec<CustodyReceipt>, VerifyError> {
500        let url = format!("{}/assets/{asset_id}/receipts", self.transport.base_url);
501        let response = self.transport.send(|http| http.get(&url)).await?;
502        let response = check_status(response).await?;
503        let wire: AssetReceiptsResponseWire = response
504            .json()
505            .await
506            .map_err(|e| VerifyError::Malformed(e.to_string()))?;
507        wire.receipts
508            .iter()
509            .map(|r| decode_receipt_b64(&r.receipt_cbor))
510            .collect()
511    }
512
513    /// Fetch the server's published attestation-key history from
514    /// `GET {origin}/.well-known/capsule/attestation-keys`. This only fetches: the caller checks
515    /// the result against the history it pinned for the server before trusting it
516    /// (`capsule_library::library::pin_attestation_keys` — TOFU on first contact, append-only
517    /// after). Every published key is returned so a receipt's `server_key_id` resolves against the whole
518    /// history — a pre-rotation receipt still verifies.
519    ///
520    /// The record lives at the **origin** (RFC 8615), not under the API root the other methods
521    /// use: the transport's `base_url` path (`/v1`) is replaced, not extended. A base that does
522    /// not parse as a URL is a [`VerifyError::Transport`] raised before any request is sent.
523    #[instrument(skip_all)]
524    pub async fn fetch_attestation_keys(&self) -> Result<Vec<HybridVerifyingKey>, VerifyError> {
525        let url = well_known_url(&self.transport.base_url, ATTESTATION_KEYS_PATH)?;
526        debug!(%url, "fetching attestation keys");
527        let response = self.transport.send(|http| http.get(url.clone())).await?;
528        let response = check_status(response).await?;
529        let wire: WellKnownAttestationWire = response
530            .json()
531            .await
532            .map_err(|e| VerifyError::Malformed(e.to_string()))?;
533        wire.keys
534            .iter()
535            .map(|k| {
536                let bytes = base64::engine::general_purpose::STANDARD
537                    .decode(k.public.as_bytes())
538                    .map_err(|e| VerifyError::Malformed(format!("attestation key base64: {e}")))?;
539                HybridVerifyingKey::from_bytes(&bytes)
540                    .map_err(|e| VerifyError::Malformed(format!("attestation key: {e}")))
541            })
542            .collect()
543    }
544}
545
546/// The attestation-key record's path, served at the server's origin
547/// (`capsule-server/src/routes/well_known.rs`).
548const ATTESTATION_KEYS_PATH: &str = "/.well-known/capsule/attestation-keys";
549
550/// Resolve a `.well-known` `path` against the origin of the API root `base_url`: scheme, host
551/// and port are kept, the API path (`/v1`) and any query are dropped.
552fn well_known_url(base_url: &str, path: &str) -> Result<reqwest::Url, VerifyError> {
553    reqwest::Url::parse(base_url)
554        .and_then(|base| base.join(path))
555        .map_err(|e| VerifyError::Transport(format!("base url {base_url:?}: {e}")))
556}
557
558/// Decode a receipt carried as base64 inside a JSON document (the asset-receipts chain).
559fn decode_receipt_b64(b64: &str) -> Result<CustodyReceipt, VerifyError> {
560    let bytes = base64::engine::general_purpose::STANDARD
561        .decode(b64.as_bytes())
562        .map_err(|e| VerifyError::Malformed(format!("receipt base64: {e}")))?;
563    decode_receipt_cbor(&bytes)
564}
565
566/// Decode the signed canonical-CBOR receipt bytes.
567fn decode_receipt_cbor(bytes: &[u8]) -> Result<CustodyReceipt, VerifyError> {
568    CustodyReceipt::from_canonical_cbor(bytes)
569        .map_err(|e| VerifyError::Malformed(format!("receipt cbor: {e}")))
570}
571
572async fn check_status(response: reqwest::Response) -> Result<reqwest::Response, VerifyError> {
573    let status = response.status().as_u16();
574    if (200..300).contains(&status) {
575        return Ok(response);
576    }
577    // The stable `error.*` code rides the JSON body (like the upload/verify surfaces).
578    let code = response
579        .json::<ApiErrorWire>()
580        .await
581        .ok()
582        .and_then(|e| e.code);
583    Err(VerifyError::Status { status, code })
584}
585
586// ─── The 60-second re-verify window + release coordination ─────────────────────
587
588/// The client's clock, injected so the re-verify window is deterministic under test.
589pub trait ReleaseClock: Send + Sync {
590    /// The current UNIX time in seconds.
591    fn now_unix(&self) -> i64;
592}
593
594/// The wall clock (`jiff::Timestamp::now`).
595#[derive(Debug, Default, Clone, Copy)]
596pub struct SystemClock;
597
598impl ReleaseClock for SystemClock {
599    fn now_unix(&self) -> i64 {
600        jiff::Timestamp::now().as_second()
601    }
602}
603
604/// The default re-verify window: a verdict older than this is re-fetched before any release
605/// (SSoT: Storage Verification — "the client re-verifies if more than a bounded interval,
606/// default 60 s, elapses between verdict and release").
607pub const DEFAULT_REVERIFY_WINDOW_SECS: i64 = 60;
608
609/// Everything the gate checks for one write: the asset, its required blob hashes, the upload
610/// session that produced custody, and what the client sent (so the receipt's server-recomputed
611/// facts can be matched).
612#[derive(Debug, Clone)]
613pub struct ReleaseRequest {
614    /// The asset being released.
615    pub asset_id: Uuid,
616    /// The upload session whose receipt proves custody.
617    pub upload_id: Uuid,
618    /// Every required blob the client relies on (declared to `/storage/verify`).
619    pub blob_hashes: Vec<Hash32>,
620    /// What the client sent, matched against the receipt.
621    pub expectations: ReceiptExpectations,
622    /// Whether the offline `verify_asset` accepted the asset (the crypto-validity half).
623    pub verify_asset_accepted: bool,
624}
625
626/// Composes durability, accountability, and crypto validity into a single release decision, and
627/// enforces the 60-second re-verify window. One coordinator serves one asset's release attempts;
628/// it caches the last verdict so a re-attempt inside the window skips a redundant round-trip.
629pub struct ReleaseCoordinator<C: ReleaseClock = SystemClock> {
630    client: StorageVerifyClient,
631    attestation_keys: Vec<HybridVerifyingKey>,
632    window_secs: i64,
633    clock: C,
634    /// The last verdict fetched and the UNIX time it was fetched at.
635    cached: Mutex<Option<(StorageVerdict, i64)>>,
636}
637
638impl ReleaseCoordinator<SystemClock> {
639    /// Build a coordinator over the wall clock with the default 60 s window.
640    pub fn new(client: StorageVerifyClient, attestation_keys: Vec<HybridVerifyingKey>) -> Self {
641        Self::with_clock(
642            client,
643            attestation_keys,
644            DEFAULT_REVERIFY_WINDOW_SECS,
645            SystemClock,
646        )
647    }
648}
649
650impl<C: ReleaseClock> ReleaseCoordinator<C> {
651    /// Build a coordinator with an explicit window and clock (tests advance the clock to drive
652    /// the re-verify window deterministically).
653    pub fn with_clock(
654        client: StorageVerifyClient,
655        attestation_keys: Vec<HybridVerifyingKey>,
656        window_secs: i64,
657        clock: C,
658    ) -> Self {
659        Self {
660            client,
661            attestation_keys,
662            window_secs,
663            clock,
664            cached: Mutex::new(None),
665        }
666    }
667
668    /// Return a verdict fresh within the window: reuse a cached **durable** verdict younger than
669    /// the window (the intended optimization for repeated release attempts), else re-fetch. Only
670    /// durable verdicts are cached — a non-durable verdict must always be re-queried so a caller
671    /// retrying after a `Retain` sees new server state, never a stale "not yet durable". The
672    /// verdict is a point-in-time fact, so a stale one is never trusted for a release.
673    async fn fresh_verdict(
674        &self,
675        asset_id: Uuid,
676        blob_hashes: &[Hash32],
677    ) -> Result<StorageVerdict, VerifyError> {
678        let now = self.clock.now_unix();
679        {
680            let cached = self.cached.lock().expect("release cache mutex");
681            if let Some((verdict, fetched_at)) = cached.as_ref()
682                && verdict.asset_id == asset_id
683                && now.saturating_sub(*fetched_at) < self.window_secs
684            {
685                debug!("reusing durable verdict within the re-verify window");
686                return Ok(verdict.clone());
687            }
688        }
689        let query = AssetQuery {
690            asset_id,
691            blob_hashes: blob_hashes.to_vec(),
692        };
693        let mut verdicts = self.client.verify(&[query], false).await?;
694        let verdict = verdicts
695            .drain(..)
696            .find(|v| v.asset_id == asset_id)
697            .ok_or_else(|| VerifyError::Malformed("verdict missing the requested asset".into()))?;
698        let mut cached = self.cached.lock().expect("release cache mutex");
699        *cached = if verdict.durable {
700            Some((verdict.clone(), now))
701        } else {
702            None
703        };
704        Ok(verdict)
705    }
706
707    /// Evaluate the full verify-before-destroy gate for one write. Returns
708    /// [`ReleaseDecision::Release`] only when the verdict is durable within the window, the
709    /// custody receipt verifies under a pinned attestation key with matching fields, and
710    /// `verify_asset` accepted the asset. Every other outcome is a `Retain` that names why — the
711    /// caller keeps the local copy and retries.
712    #[instrument(skip_all, fields(asset = %request.asset_id))]
713    pub async fn evaluate(&self, request: &ReleaseRequest) -> ReleaseDecision {
714        // 1. Durability, fresh within the window.
715        let verdict = match self
716            .fresh_verdict(request.asset_id, &request.blob_hashes)
717            .await
718        {
719            Ok(v) => v,
720            Err(e) => {
721                warn!(error = %e, "verdict fetch failed; retaining local copy");
722                return ReleaseDecision::Retain(RetainReason::VerifyUnavailable);
723            }
724        };
725        if !release_is_safe(&verdict, request.verify_asset_accepted) {
726            return ReleaseDecision::Retain(RetainReason::NotDurable);
727        }
728
729        // 2. Accountability: fetch + verify the custody receipt under the pinned key.
730        let receipt = match self.client.fetch_receipt(request.upload_id).await {
731            Ok(r) => r,
732            Err(e) => {
733                warn!(error = %e, "receipt fetch failed; refusing release");
734                return ReleaseDecision::Retain(RetainReason::ReceiptUnavailable);
735            }
736        };
737        match verify_receipt(
738            &receipt,
739            &self.attestation_keys,
740            &request.expectations,
741            self.clock.now_unix(),
742        ) {
743            Ok(()) => ReleaseDecision::Release,
744            Err(rejection) => {
745                // Every receipt rejection (bad signature, field mismatch, clock drift) refuses
746                // release — the reason surfaced to the caller is the unverified receipt.
747                warn!(
748                    ?rejection,
749                    "custody receipt did not verify; refusing release"
750                );
751                ReleaseDecision::Retain(RetainReason::ReceiptMissing)
752            }
753        }
754    }
755
756    /// The verified custody receipt for a write, for the caller to persist beside the provenance
757    /// chain (`capsule_library::library::append_receipt`) — evidence, not a cache. Returns the
758    /// receipt only when it verifies under a pinned attestation key with matching fields.
759    #[instrument(skip_all, fields(%upload_id))]
760    pub async fn fetch_verified_receipt(
761        &self,
762        upload_id: Uuid,
763        expectations: &ReceiptExpectations,
764    ) -> Result<CustodyReceipt, VerifyError> {
765        let receipt = self.client.fetch_receipt(upload_id).await?;
766        verify_receipt(
767            &receipt,
768            &self.attestation_keys,
769            expectations,
770            self.clock.now_unix(),
771        )
772        .map_err(|r| VerifyError::Malformed(format!("receipt rejected: {r:?}")))?;
773        Ok(receipt)
774    }
775
776    /// A signed durability verdict for `assets`, under a nonce drawn fresh from the OS CSPRNG
777    /// and verified under the pinned attestation keys — the evidence form of the verdict
778    /// (transfer/durability.md, Signed Storage Attestation). The caller keeps
779    /// [`VerifiedAttestation::cbor`] beside the asset's custody receipts.
780    ///
781    /// Not part of [`evaluate`](Self::evaluate): the release gate needs a fresh `durable`, not
782    /// evidence, and a signed request spends the account's deep budget.
783    #[instrument(skip_all, fields(assets = assets.len(), deep))]
784    pub async fn fetch_verified_attestation(
785        &self,
786        assets: &[AssetQuery],
787        deep: bool,
788    ) -> Result<VerifiedAttestation, VerifyError> {
789        let nonce = capsule_core::crypto::rng::random_array::<ATTESTATION_NONCE_LEN>();
790        self.client
791            .verify_signed(assets, deep, &nonce, &self.attestation_keys)
792            .await
793    }
794
795    /// Fetch the server-side facts the release gate needs for each of `releases`, and hand
796    /// them back as a [`CustodyVerifier`] — the production
797    /// [`StorageVerifier`] the offline data plane's gate
798    /// ([`Workspace::release_move_source`](capsule_library::lifecycle::Workspace::release_move_source))
799    /// consults synchronously.
800    ///
801    /// Per asset: a verdict fresh within the re-verify window over its declared blobs, then —
802    /// only when that verdict is `durable` — the asset's durable receipt log
803    /// (`GET /assets/{id}/receipts`), with every declared blob required to have a receipt that
804    /// verifies under the pinned attestation keys with fields matching what the client sent.
805    /// The log rather than the per-session fetch [`evaluate`](Self::evaluate) uses, because a
806    /// blob a push found already held has no upload session to ask about.
807    ///
808    /// Never fails: a fetch that fails is recorded as that asset's fact, and the gate turns it
809    /// into a `Retain`. Resolve immediately before releasing; the facts are point-in-time.
810    #[instrument(skip_all, fields(assets = releases.len()))]
811    pub async fn resolve_custody(&self, releases: &[HeldRelease]) -> CustodyVerifier {
812        let mut facts = HashMap::with_capacity(releases.len());
813        for release in releases {
814            let blob_hashes = release.blob_hashes();
815            let verdict = self
816                .fresh_verdict(release.asset_id, &blob_hashes)
817                .await
818                .map_err(|error| {
819                    warn!(asset = %release.asset_id, %error, "custody: verdict fetch failed");
820                    error.to_string()
821                });
822            let receipt = match &verdict {
823                Ok(verdict) if verdict.durable => self.receipt_log_covers(release).await,
824                Ok(_) => Err("not consulted: the verdict is not durable".to_owned()),
825                Err(_) => Err("not consulted: no verdict".to_owned()),
826            };
827            debug!(
828                asset = %release.asset_id,
829                durable = verdict.as_ref().is_ok_and(|v| v.durable),
830                receipts_verified = ?receipt,
831                "custody: facts resolved"
832            );
833            facts.insert(
834                release.asset_id,
835                CustodyFacts {
836                    blob_hashes,
837                    verdict,
838                    receipt,
839                },
840            );
841        }
842        CustodyVerifier { facts }
843    }
844
845    /// Whether the asset's receipt log holds, for every blob `release` declares, a receipt
846    /// that verifies under the pinned keys with matching fields. `Err` when the log fetch fails.
847    async fn receipt_log_covers(&self, release: &HeldRelease) -> Result<bool, String> {
848        let log = self
849            .client
850            .fetch_asset_receipts(release.asset_id)
851            .await
852            .map_err(|error| {
853                warn!(asset = %release.asset_id, %error, "custody: receipt log fetch failed");
854                error.to_string()
855            })?;
856        let now = self.clock.now_unix();
857        let missing: Vec<String> = release
858            .blobs
859            .iter()
860            .filter(|expected| {
861                !log.iter().any(|receipt| {
862                    verify_receipt(receipt, &self.attestation_keys, expected, now).is_ok()
863                })
864            })
865            .map(|expected| expected.ciphertext_hash.to_hex())
866            .collect();
867        if !missing.is_empty() {
868            warn!(
869                asset = %release.asset_id,
870                ?missing,
871                log = log.len(),
872                "custody: no verified receipt for every declared blob"
873            );
874        }
875        Ok(missing.is_empty())
876    }
877}
878
879// ─── The production release-gate verifier ─────────────────────────────────────
880
881/// One asset whose local bytes wait on server custody before they may be released, asked
882/// about through [`ReleaseCoordinator::resolve_custody`].
883#[derive(Debug, Clone, PartialEq, Eq)]
884pub struct HeldRelease {
885    /// The asset.
886    pub asset_id: Uuid,
887    /// One entry per required blob: what the client sent, matched against the receipt log.
888    /// Their `ciphertext_hash`es, in order, are the blobs declared to `/storage/verify`.
889    pub blobs: Vec<ReceiptExpectations>,
890}
891
892impl HeldRelease {
893    /// The blobs a release of `bundle`'s original waits on: the original ciphertext and, when
894    /// the head binds one, the sealed metadata blob — in the order
895    /// [`Workspace::release_move_source`](capsule_library::lifecycle::Workspace::release_move_source)
896    /// declares them.
897    #[must_use]
898    pub fn for_original(bundle: &UploadBundle) -> Self {
899        let mut blobs = vec![ReceiptExpectations {
900            ciphertext_hash: bundle.ciphertext_hash,
901            size: bundle.ciphertext_size(),
902            role: BlobRole::Original,
903            envelope_hash: None,
904        }];
905        if let Some(hash) = bundle.metadata_blob_hash {
906            blobs.push(ReceiptExpectations {
907                ciphertext_hash: hash,
908                size: bundle.metadata_blob.len() as u64,
909                role: BlobRole::Metadata,
910                envelope_hash: None,
911            });
912        }
913        Self {
914            asset_id: bundle.asset_id,
915            blobs,
916        }
917    }
918
919    /// The blobs a release of `asset`'s original waits on, read off its provenance chain
920    /// **head**: the original ciphertext and, when the head binds one, the sealed metadata blob
921    /// the library holds — exactly the set, in the order,
922    /// [`Workspace::release_move_source`](capsule_library::lifecycle::Workspace::release_move_source)
923    /// declares. Unlike [`for_original`](Self::for_original) it needs no upload bundle, which
924    /// carries the create and cannot be built once an edit has replaced the create's metadata
925    /// blob.
926    #[must_use]
927    pub fn for_head(asset: &AssetState) -> Self {
928        let head = &asset
929            .chain
930            .records()
931            .last()
932            .expect("provenance chain is never empty")
933            .manifest
934            .core;
935        let mut blobs = vec![ReceiptExpectations {
936            ciphertext_hash: head.ciphertext_hash,
937            size: capsule_core::crypto::encryption::ciphertext_len(head.plaintext_size),
938            role: BlobRole::Original,
939            envelope_hash: None,
940        }];
941        if let Some(hash) = head.metadata_blob_hash {
942            blobs.push(ReceiptExpectations {
943                ciphertext_hash: hash,
944                size: asset.metadata_blob.len() as u64,
945                role: BlobRole::Metadata,
946                envelope_hash: None,
947            });
948        }
949        Self {
950            asset_id: asset.asset_id,
951            blobs,
952        }
953    }
954
955    fn blob_hashes(&self) -> Vec<Hash32> {
956        self.blobs.iter().map(|b| b.ciphertext_hash).collect()
957    }
958}
959
960/// What [`ReleaseCoordinator::resolve_custody`] fetched for one asset. A fetch that failed is
961/// kept as its English detail.
962#[derive(Debug, Clone)]
963struct CustodyFacts {
964    blob_hashes: Vec<Hash32>,
965    verdict: Result<StorageVerdict, String>,
966    receipt: Result<bool, String>,
967}
968
969/// The production [`StorageVerifier`]: server facts resolved over [`StorageVerifyClient`] by
970/// [`ReleaseCoordinator::resolve_custody`], answered synchronously to the offline gate.
971///
972/// It answers only what was resolved. An asset it was not asked about, or the right asset with
973/// a different blob set, is a [`VerifierError`] — which the gate turns into a `Retain` — so
974/// nothing is ever released on a verdict that answered another question.
975#[derive(Debug, Clone, Default)]
976pub struct CustodyVerifier {
977    facts: HashMap<Uuid, CustodyFacts>,
978}
979
980impl CustodyVerifier {
981    fn facts(
982        &self,
983        asset_id: Uuid,
984        blob_hashes: &[Hash32],
985    ) -> Result<&CustodyFacts, VerifierError> {
986        match self.facts.get(&asset_id) {
987            Some(facts) if facts.blob_hashes == blob_hashes => Ok(facts),
988            Some(_) => Err(VerifierError::Transport(format!(
989                "custody for {asset_id} was resolved over a different blob set"
990            ))),
991            None => Err(VerifierError::Transport(format!(
992                "custody for {asset_id} was not resolved"
993            ))),
994        }
995    }
996}
997
998impl StorageVerifier for CustodyVerifier {
999    fn verify(
1000        &self,
1001        asset_id: Uuid,
1002        blob_hashes: &[Hash32],
1003    ) -> Result<StorageVerdict, VerifierError> {
1004        self.facts(asset_id, blob_hashes)?
1005            .verdict
1006            .clone()
1007            .map_err(VerifierError::Transport)
1008    }
1009
1010    fn receipt_verified(
1011        &self,
1012        asset_id: Uuid,
1013        blob_hashes: &[Hash32],
1014    ) -> Result<bool, VerifierError> {
1015        self.facts(asset_id, blob_hashes)?
1016            .receipt
1017            .clone()
1018            .map_err(VerifierError::Transport)
1019    }
1020}
1021
1022#[cfg(test)]
1023mod tests;