Skip to main content

capsule_sdk/
push.rs

1//! Pushing a locally-imported asset to a server — the glue between
2//! `capsule_core`'s [`UploadBundle`] and the hand-written [upload client](crate::upload).
3//!
4//! `capsule-core` builds the bundle (ciphertext, sealed metadata blob, derivatives, and the
5//! manifest-envelope projection); this module turns it into the protocol's `POST /upload`
6//! bodies and drives them in [tier ladder](crate::staged) order. Nothing here re-implements a
7//! network flow — every byte goes through [`UploadClient`], and the ordering/gating goes
8//! through [`StagedScheduler::plan_sessions`].
9//!
10//! **Resume derives from server truth.** There is no push-side state file: pull the sync feed,
11//! fold it with [`held_from_feed`](crate::staged::held_from_feed) into the set of blob content
12//! addresses the server durably holds, and [`remaining_tiers`]
13//! rebuilds exactly the outstanding work. Within a blob, `POST /upload`'s idempotent re-create
14//! returns the authoritative offset; across an asset's blobs, a `duplicate_blob` answer is a
15//! merge, not an error. Re-running a push against an unchanged library is therefore a no-op.
16//!
17//! # The index tier is two blobs, not one
18//!
19//! `T0` is **provenance and metadata**, in that order. The server publishes an asset to other
20//! devices only once it holds both index-tier roles
21//! (`capsule_server::upload::visibility::INDEX_TIER_ROLES`), and the head of the server-side
22//! provenance chain — what a later lifecycle op's `prior_provenance_hash` must equal — is the
23//! SHA-256 of the provenance blob's bytes. A ladder that shipped only the metadata blob
24//! therefore uploaded an asset that no device could ever see and no op could ever chain onto:
25//! the bytes were on the server and the asset was not in anybody's library.
26//!
27//! The provenance blob is the canonical CBOR of the chain's head `ProvenanceRecord`
28//! ([`UploadBundle::provenance_blob`]), which `capsule-core` encodes once so the SDK and the
29//! FFI cannot disagree about it. It goes **first** within `T0`: it is the blob the server reads
30//! `prior_provenance_hash`, `action` and `retention_until` out of, so sending it first is the
31//! order in which the asset's own claims arrive before the bytes they describe.
32//!
33//! **Every blob this module ships is ciphertext.** The original is re-derived from its
34//! manifest's nonce prefix one upload chunk at a time ([`BlobBytes::Original`]), so a push holds
35//! one chunk window of an original and never the whole file; the metadata blob is carried sealed, and **derivative blobs are
36//! encrypted too** — `capsule-core` re-derives each one from the plaintext it holds locally
37//! using the prefix that derivative's signed manifest recorded. Nothing here decrypts, encrypts,
38//! or inspects a blob; it moves opaque bytes.
39//!
40//! **One deviation from "the envelope mirrors the signed manifest", and it is the server's
41//! rule:** invariant 15 requires `manifest_envelope.ciphertext_hash == hash` (the top-level
42//! declared content address of *this* blob). A bundle's metadata and derivative blobs are not
43//! the original, so their envelope carries their own content address; every other field is the
44//! head manifest's, verbatim. See [`envelope_for`].
45//!
46//! # A transfer is not custody
47//!
48//! Every byte reaching the server is not the same as the server holding the asset. A finalize
49//! that lost its claim race answers the chunk `204` and is still running; an index failure after
50//! the commit leaves bytes nobody references. So a push does not end at the last chunk:
51//! [`verify_custody`] asks `POST /storage/verify` whether every blob the asset now relies on is
52//! stored, indexed and retrievable, then fetches the asset's custody-receipt log and requires a
53//! receipt per blob that verifies under the server's attestation-key history and names the
54//! exact bytes, size and role the client sent. That history is the one the caller pinned for the
55//! server (`capsule_library::library::pin_attestation_keys`), never a fetch trusted on its own. Only then is the asset reported as pushed, and
56//! the verified receipts are what the caller persists beside the provenance chain.
57
58use std::borrow::Cow;
59use std::collections::HashSet;
60use std::sync::{Mutex, MutexGuard, PoisonError};
61use std::time::{Duration, Instant};
62
63use capsule_core::crypto::hash::{Hash32, hash_bytes};
64use capsule_core::crypto::keys::HybridVerifyingKey;
65use capsule_core::crypto::provenance::DerivativeRole;
66use capsule_library::import::UploadTier;
67use capsule_library::library::{
68    BlobRole as CoreBlobRole, CustodyReceipt, ReceiptExpectations, ReceiptRejection, verify_receipt,
69};
70use capsule_library::lifecycle::{OriginalChanged, OriginalCiphertext, UploadBundle};
71use serde::Serialize;
72use tracing::instrument;
73
74use crate::albums::{AlbumClient, AlbumError, ProvisionedAlbum};
75use crate::events::{TransferEvent, TransferEvents};
76use crate::staged::{StagedAsset, StagedScheduler, TierBlob, TierSessionOutcome, remaining_tiers};
77use crate::upload::advice::ServerAdvice;
78use crate::upload::queue::{
79    GrantId, LaneWindows, QueuedJob, RangeId, RangeRefused, ServerKey, UploadQueue,
80};
81use crate::upload::{
82    BlobRole, CreateUploadRequest, ManifestEnvelope, SourceChanged, SourceIdentity, TransferGate,
83    UploadClient, UploadError, UploadOutcome, UploadSource,
84};
85use crate::verify::{AssetQuery, StorageVerifyClient, VerifyError};
86
87/// The content type a blob the server may not parse declares. The sealed metadata blob is AMK
88/// ciphertext and the provenance blob is a signed CBOR document with no media type of its own —
89/// the server's closed content-type enum (invariant 5) admits exactly this for both.
90const OPAQUE_CONTENT_TYPE: &str = "application/octet-stream";
91
92// ─── Blob view over a bundle ──────────────────────────────────────────────────
93
94/// One transferable blob of an [`UploadBundle`]: its ladder tier, protocol blob role, declared
95/// content type, and the bytes themselves (borrowed from the bundle). Paired with its content
96/// address by [`bundle_blobs`].
97#[derive(Debug, Clone, Copy)]
98pub struct BundleBlob<'a> {
99    /// Which rung of the upload ladder this blob is.
100    pub tier: UploadTier,
101    /// The blob's role within the asset bundle.
102    pub role: BlobRole,
103    /// The MIME type declared for this blob. For a derivative it is the derivative's signed
104    /// `format`, which the envelope also declares as `derivative_format`.
105    pub content_type: &'a str,
106    /// The derivative's signed role, for a [`BlobRole::Derivative`] blob and for nothing else.
107    pub derivative_role: Option<DerivativeRole>,
108    /// The bytes to transfer.
109    pub bytes: BlobBytes<'a>,
110}
111
112/// Where a [`BundleBlob`]'s bytes come from. Everything but the original is small and already
113/// in the bundle; the original is a [`OriginalCiphertext`] source the upload client reads one
114/// chunk window at a time, so a push never holds an original whole.
115#[derive(Debug, Clone, Copy)]
116pub enum BlobBytes<'a> {
117    /// Bytes the bundle holds: the provenance and metadata blobs, derivative manifests and
118    /// derivatives.
119    Inline(&'a [u8]),
120    /// The original's ciphertext, re-derived per window from the plaintext on disk.
121    Original(&'a OriginalCiphertext),
122}
123
124impl BlobBytes<'_> {
125    /// The blob's size in bytes — what `POST /upload` declares.
126    #[must_use]
127    pub fn size(&self) -> u64 {
128        match self {
129            Self::Inline(bytes) => bytes.len() as u64,
130            Self::Original(original) => original.size(),
131        }
132    }
133
134    /// The bytes, when the bundle holds them.
135    #[must_use]
136    pub fn inline(&self) -> Option<&[u8]> {
137        match self {
138            Self::Inline(bytes) => Some(bytes),
139            Self::Original(_) => None,
140        }
141    }
142
143    /// The whole blob in memory, for a caller that can only take a buffer (the FFI's
144    /// `FfiUploadBlob`). An original read this way costs its full size; the SDK's own push
145    /// never does it.
146    pub fn to_vec(&self) -> std::io::Result<Vec<u8>> {
147        match self {
148            Self::Inline(bytes) => Ok(bytes.to_vec()),
149            Self::Original(original) => original.to_vec(),
150        }
151    }
152}
153
154impl UploadSource for BlobBytes<'_> {
155    fn read_at(&self, offset: u64, len: usize) -> std::io::Result<Cow<'_, [u8]>> {
156        match self {
157            Self::Inline(bytes) => bytes.read_at(offset, len),
158            Self::Original(original) => {
159                // The original checks every chunk it re-derives against the tag its bundle
160                // recorded, and refuses the read carrying `OriginalChanged` on a mismatch: that
161                // is a changed source, typed as one.
162                let window = original.read_at(offset, len).map_err(source_change_of)?;
163                // The check before the read cannot see an edit made while the window was being
164                // sealed; this one refuses that window before it is sent.
165                original
166                    .check_unchanged()
167                    .map_err(|changed| std::io::Error::other(SourceChanged::new(changed.reason)))?;
168                Ok(Cow::Owned(window))
169            }
170        }
171    }
172
173    /// Inline bytes cannot change and affirm it. An original affirms while its plaintext file
174    /// still has the length, modification time and (on Unix) inode and status-change time it
175    /// had when the bundle verified its ciphertext, and is changed otherwise.
176    fn check_unchanged(&self) -> Result<SourceIdentity, SourceChanged> {
177        match self {
178            Self::Inline(bytes) => bytes.check_unchanged(),
179            Self::Original(original) => original
180                .check_unchanged()
181                .map(|()| SourceIdentity::Affirmed)
182                .map_err(|changed| SourceChanged::new(changed.reason)),
183        }
184    }
185
186    /// Both verify what they return: inline bytes cannot change, and an original checks every
187    /// re-derived STREAM chunk against the tag its bundle recorded.
188    fn verifies_rederived(&self) -> bool {
189        true
190    }
191}
192
193/// A failed read of an original, with an [`OriginalChanged`] it carries re-carried as the
194/// SDK's [`SourceChanged`], which the upload client types as
195/// [`UploadError::SourceChanged`].
196fn source_change_of(error: std::io::Error) -> std::io::Error {
197    if !matches!(error.get_ref(), Some(inner) if inner.is::<OriginalChanged>()) {
198        return error;
199    }
200    let kind = error.kind();
201    match error.into_inner() {
202        Some(inner) => match inner.downcast::<OriginalChanged>() {
203            Ok(changed) => std::io::Error::other(SourceChanged::new(changed.reason)),
204            Err(inner) => std::io::Error::new(kind, inner),
205        },
206        None => kind.into(),
207    }
208}
209
210/// Every transferable blob of `bundle`, in ladder order: the **index tier** (T0) — the
211/// provenance blob then the sealed metadata blob — the **preview tier** (T1) — each derivative
212/// tier's signed manifest, then each derivative — then the original (T2).
213///
214/// The provenance blob is unconditional: a managed asset always has a chain head, and the
215/// server needs that blob both to publish the asset and to hold a chain head for the next
216/// lifecycle op. The metadata blob is conditional — a head action that binds none (`delete`,
217/// `trash-restore`, …) simply contributes no metadata rung, because the ladder is whatever the
218/// manifest actually commits to and never a fabrication.
219#[must_use]
220pub fn bundle_blobs(bundle: &UploadBundle) -> Vec<(BundleBlob<'_>, String)> {
221    let mut blobs =
222        Vec::with_capacity(3 + bundle.derivative_manifests.len() + bundle.derivatives.len());
223    blobs.push((
224        BundleBlob {
225            tier: UploadTier::Index,
226            role: BlobRole::Provenance,
227            content_type: OPAQUE_CONTENT_TYPE,
228            derivative_role: None,
229            bytes: BlobBytes::Inline(&bundle.provenance_blob),
230        },
231        // The content address of the provenance blob is `record_hash()` by definition — the
232        // digest of the canonical record — so it is derived from the bytes rather than read off
233        // a field. Nothing signs it: it *is* the chain head, and the chain is what signs.
234        hash_bytes(&bundle.provenance_blob).to_hex(),
235    ));
236    if let Some(hash) = &bundle.metadata_blob_hash {
237        blobs.push((
238            BundleBlob {
239                tier: UploadTier::Index,
240                role: BlobRole::Metadata,
241                content_type: OPAQUE_CONTENT_TYPE,
242                derivative_role: None,
243                bytes: BlobBytes::Inline(&bundle.metadata_blob),
244            },
245            hash.to_hex(),
246        ));
247    }
248    // Each derivative tier's signed manifest, ahead of the derivatives: it is what a receiver
249    // opens them with, so a device that sees a derivative has already been handed its manifest.
250    for manifest in &bundle.derivative_manifests {
251        blobs.push((
252            BundleBlob {
253                tier: UploadTier::Preview,
254                role: BlobRole::DerivativeManifest,
255                content_type: OPAQUE_CONTENT_TYPE,
256                derivative_role: None,
257                bytes: BlobBytes::Inline(manifest),
258            },
259            // Signed CBOR, not ciphertext, so — as for the provenance blob — its address is
260            // derived from the bytes rather than read off a field.
261            hash_bytes(manifest).to_hex(),
262        ));
263    }
264    for derivative in &bundle.derivatives {
265        blobs.push((
266            BundleBlob {
267                tier: UploadTier::Preview,
268                role: BlobRole::Derivative,
269                content_type: &derivative.format,
270                derivative_role: Some(derivative.role),
271                bytes: BlobBytes::Inline(&derivative.bytes),
272            },
273            derivative.ciphertext_hash.to_hex(),
274        ));
275    }
276    blobs.push((
277        BundleBlob {
278            tier: UploadTier::Original,
279            role: BlobRole::Original,
280            content_type: &bundle.content_type,
281            derivative_role: None,
282            bytes: BlobBytes::Original(&bundle.original),
283        },
284        bundle.ciphertext_hash.to_hex(),
285    ));
286    blobs
287}
288
289/// The bundle as a [`StagedAsset`] the scheduler can order and gate.
290#[must_use]
291pub fn staged_asset(bundle: &UploadBundle) -> StagedAsset {
292    StagedAsset::new(
293        bundle.asset_id.to_string(),
294        bundle_blobs(bundle)
295            .into_iter()
296            .map(|(blob, hash)| TierBlob::new(blob.tier, hash, blob.bytes.size()))
297            .collect(),
298    )
299}
300
301// ─── Envelope + request mapping ───────────────────────────────────────────────
302
303/// Serialize a wire enum (`Action`, `KeyMode`, …) to its bare protocol string.
304fn wire_enum<T: Serialize>(value: &T) -> String {
305    serde_json::to_value(value)
306        .ok()
307        .and_then(|v| v.as_str().map(str::to_string))
308        .unwrap_or_default()
309}
310
311/// The [`ManifestEnvelope`] for one blob of `bundle`: every field of the head manifest,
312/// verbatim, with `ciphertext_hash` naming **this** blob (the server's invariant-15
313/// consistency rule — `manifest_envelope.ciphertext_hash` must equal the top-level `hash`).
314#[must_use]
315pub fn envelope_for(bundle: &UploadBundle, blob_hash: &str) -> ManifestEnvelope {
316    ManifestEnvelope {
317        crypto_suite_id: bundle.crypto_suite_id,
318        protocol_version: bundle.protocol_version.clone(),
319        album_id: Some(bundle.album_id.to_string()),
320        file_id: bundle.asset_id.to_string(),
321        amk_version: bundle.amk_version,
322        ciphertext_hash: blob_hash.to_string(),
323        plaintext_size: bundle.plaintext_size,
324        chunk_size: bundle.chunk_size,
325        key_mode: wire_enum(&bundle.key_mode),
326        metadata_blob_hash: bundle.metadata_blob_hash.map(|h| h.to_hex()),
327        // Per-blob, not per-head: [`create_request`] fills the pair for a derivative.
328        derivative_role: None,
329        derivative_format: None,
330        created_by_user: bundle.created_by_user.to_string(),
331        created_by_device: bundle.created_by_device.to_string(),
332        client_version: bundle.client_version.clone(),
333        timestamp: bundle.timestamp.clone(),
334        action: wire_enum(&bundle.action),
335        prior_provenance_hash: bundle.prior_provenance_hash.map(|h| h.to_hex()),
336        retention_until: bundle.retention_until.clone(),
337    }
338}
339
340/// The `POST /upload` body for one blob of `bundle`.
341///
342/// A derivative's envelope declares its signed `(role, format)` pair, which the server checks
343/// against the closed still-derivative format set on receipt; every other blob declares none,
344/// because the server refuses the pair on anything but a derivative.
345#[must_use]
346pub fn create_request(
347    bundle: &UploadBundle,
348    blob: &BundleBlob<'_>,
349    hash: &str,
350) -> CreateUploadRequest {
351    let mut manifest_envelope = envelope_for(bundle, hash);
352    if let Some(role) = blob.derivative_role {
353        manifest_envelope.derivative_role = Some(wire_enum(&role));
354        manifest_envelope.derivative_format = Some(blob.content_type.to_string());
355    }
356    CreateUploadRequest {
357        size: blob.bytes.size(),
358        hash: hash.to_string(),
359        content_type: blob.content_type.to_string(),
360        crypto_suite_id: bundle.crypto_suite_id,
361        protocol_version: bundle.protocol_version.clone(),
362        blob_role: blob.role,
363        manifest_envelope,
364        album_id: Some(bundle.album_id.to_string()),
365        owner_id: None,
366        intent_id: None,
367    }
368}
369
370// ─── Provisioning the album ───────────────────────────────────────────────────
371
372/// Register `album_id` with the server before any blob session opens for it.
373///
374/// The album's id is derived from the account master key, so the client knows it and the
375/// server does not. [Invariant 6] refuses an upload whose album does not exist or is not
376/// writable by the caller, so without this step a real push cannot land a single byte — the
377/// ladder below would open its first session straight into `error.upload.album_access_denied`.
378///
379/// **Idempotent, and relied upon to be.** Provisioning an album the caller already owns is a
380/// success that writes nothing, so this runs unconditionally on every push: there is no
381/// client-side "already registered" flag to keep in sync across devices, which is exactly what
382/// deriving the id from the master key buys. Pushing twice therefore cannot fail here.
383///
384/// No album name crosses the wire — album titles live in the encrypted sidecar.
385///
386/// [Invariant 6]: https://docs/design/threat-model/validation/#server-side-validation-invariants
387#[instrument(skip(client), fields(album_id = %album_id))]
388pub async fn ensure_album(
389    client: &AlbumClient,
390    album_id: uuid::Uuid,
391) -> Result<ProvisionedAlbum, AlbumError> {
392    let provisioned = client.provision(album_id).await?;
393    tracing::info!(
394        created = provisioned.created,
395        "push: album provisioned on the server"
396    );
397    Ok(provisioned)
398}
399
400// ─── Driving a push ───────────────────────────────────────────────────────────
401
402/// What a push **would** do for one bundle: the blobs it plans to open sessions for, in ladder
403/// order, plus what it skipped and why. Computed without touching the network — the dry-run
404/// primitive, and the first half of [`push_bundle`].
405#[derive(Debug, Clone, PartialEq, Eq)]
406pub struct PushPlan {
407    /// The blobs whose sessions would open now, in ladder order.
408    pub blobs: Vec<TierBlob>,
409    /// Blobs the server already holds (skipped from server truth, before any request).
410    pub already_held: usize,
411    /// Blobs a staged policy defers to a later window.
412    pub deferred: usize,
413    /// The content addresses of those deferred blobs.
414    pub deferred_hashes: Vec<String>,
415    /// Bytes the planned blobs carry.
416    pub bytes: u64,
417}
418
419/// Plan a push for one bundle: prune to what server truth says is outstanding, then let the
420/// scheduler decide which of those tiers open now.
421///
422/// `force` ignores `held` and plans the whole ladder — the server still answers
423/// `duplicate_blob` for anything it holds, which resolves as a merge.
424#[must_use]
425pub fn plan<H: std::hash::BuildHasher>(
426    scheduler: &StagedScheduler,
427    bundle: &UploadBundle,
428    held: &HashSet<String, H>,
429    force: bool,
430) -> PushPlan {
431    let asset = staged_asset(bundle);
432    let total = asset.blobs.len();
433    let outstanding = if force {
434        asset
435    } else {
436        remaining_tiers(&asset, held)
437    };
438    let blobs = scheduler.plan_sessions(&outstanding);
439    let deferred_hashes = outstanding
440        .blobs
441        .iter()
442        .filter(|candidate| !blobs.iter().any(|b| b.hash == candidate.hash))
443        .map(|candidate| candidate.hash.clone())
444        .collect();
445    PushPlan {
446        already_held: total - outstanding.blobs.len(),
447        deferred: outstanding.blobs.len() - blobs.len(),
448        deferred_hashes,
449        bytes: blobs.iter().map(|b| b.size).sum(),
450        blobs,
451    }
452}
453
454/// Every blob of the bundle except the deferred ones, in ladder order — what the server must
455/// hold once a run that deferred `deferred` is done.
456fn custody_hashes(blobs: &[(BundleBlob<'_>, String)], deferred: &[String]) -> Vec<String> {
457    blobs
458        .iter()
459        .map(|(_, hash)| hash)
460        .filter(|hash| !deferred.contains(hash))
461        .cloned()
462        .collect()
463}
464
465/// Errors a push can fail with.
466#[derive(Debug, thiserror::Error)]
467pub enum PushError {
468    /// The bundle's album could not be provisioned on the server, so nothing may be uploaded
469    /// into it (invariant 6 would refuse every session).
470    #[error(transparent)]
471    Album(#[from] AlbumError),
472    /// A blob's transfer failed non-recoverably.
473    #[error(transparent)]
474    Upload(#[from] UploadError),
475    /// The server refused a **create**'s provenance blob at finalization
476    /// (`error.upload.envelope_rejected`), so the asset was not published (issue #822).
477    ///
478    /// The provenance blob is the first rung of the ladder and the one that publishes the
479    /// manifest, so a refusal of it means nothing of the asset reached the row. The one cause a
480    /// client can act on is invariant 18: the album's epoch moved past the one the create is
481    /// sealed under. The wire answer is generic, so the caller decides — by checking whether it
482    /// holds a newer epoch — whether a re-seal at the album's current epoch
483    /// (`Workspace::reseal_create`) is the fix.
484    #[error(
485        "asset {asset_id}: the server refused its create, sealed at album epoch {amk_version}: \
486         {source}"
487    )]
488    CreateRefused {
489        /// The asset whose create was refused.
490        asset_id: String,
491        /// The album epoch the refused manifest names.
492        amk_version: u32,
493        /// The server's refusal, boxed to keep `PushError` small.
494        #[source]
495        source: Box<UploadError>,
496    },
497    /// The scheduler planned a blob the bundle does not contain — an internal inconsistency
498    /// between [`staged_asset`] and [`bundle_blobs`], surfaced rather than panicked on.
499    #[error("asset {asset_id}: planned blob {hash} is not part of its upload bundle")]
500    UnknownBlob {
501        /// The asset whose plan named the blob.
502        asset_id: String,
503        /// The content address that could not be resolved.
504        hash: String,
505    },
506    /// The storage-verification or custody-receipt surface could not answer, so custody is
507    /// unconfirmed — never assumed.
508    #[error(transparent)]
509    Verify(#[from] VerifyError),
510    /// The server's verdict says it does not durably hold every blob the asset relies on.
511    #[error("asset {asset_id}: the server does not durably hold {} of its blobs", not_durable.len())]
512    NotDurable {
513        /// The asset the verdict is for.
514        asset_id: String,
515        /// The content addresses not stored ∧ indexed ∧ retrievable (or absent from the verdict).
516        not_durable: Vec<String>,
517    },
518    /// The asset's receipt log holds no receipt for a blob the asset relies on.
519    #[error("asset {asset_id}: no custody receipt for blob {hash}")]
520    ReceiptMissing {
521        /// The asset whose log was read.
522        asset_id: String,
523        /// The blob with no receipt.
524        hash: String,
525    },
526    /// Every receipt the log holds for a blob was refused: a signature no published attestation
527    /// key verifies, or a field that disagrees with what the client sent.
528    #[error("asset {asset_id}: the custody receipt for blob {hash} did not verify ({rejection:?})")]
529    ReceiptRejected {
530        /// The asset whose log was read.
531        asset_id: String,
532        /// The blob whose receipt was refused.
533        hash: String,
534        /// Why the last candidate receipt was refused.
535        rejection: ReceiptRejection,
536    },
537}
538
539impl PushError {
540    /// A stable, machine-readable name for the failure — the `kind` a `--json` report carries.
541    #[must_use]
542    pub fn kind(&self) -> &'static str {
543        match self {
544            Self::Album(_) => "album",
545            Self::Upload(UploadError::SourceChanged(_)) => "source_changed",
546            Self::Upload(_) => "upload",
547            Self::CreateRefused { .. } => "create_refused",
548            Self::UnknownBlob { .. } => "unknown_blob",
549            Self::Verify(_) => "verify_unavailable",
550            Self::NotDurable { .. } => "not_durable",
551            Self::ReceiptMissing { .. } => "receipt_missing",
552            Self::ReceiptRejected { .. } => "receipt_rejected",
553        }
554    }
555
556    /// The stable `error.*` code the server supplied, when there was one.
557    #[must_use]
558    pub fn error_code(&self) -> Option<&str> {
559        match self {
560            Self::CreateRefused { source, .. } => source.error_code(),
561            Self::Upload(UploadError::UpgradeRequired { .. }) => {
562                Some(capsule_i18n::error_codes::PROTOCOL_VERSION_UNSUPPORTED)
563            }
564            Self::Upload(error) => error.error_code(),
565            Self::Verify(error) => error.error_code(),
566            Self::Album(error) => error.error_code(),
567            _ => None,
568        }
569    }
570}
571
572/// How one blob of a bundle resolved.
573#[derive(Debug, Clone, PartialEq, Eq)]
574pub struct PushedBlob {
575    /// The ladder tier the blob belongs to.
576    pub tier: UploadTier,
577    /// The blob's content address.
578    pub hash: String,
579    /// Whether it transferred or merged onto an already-stored blob.
580    pub outcome: TierSessionOutcome,
581}
582
583/// What pushing one asset did.
584#[derive(Debug, Clone, Default, PartialEq, Eq)]
585pub struct AssetPushReport {
586    /// The asset id, as a string.
587    pub asset_id: String,
588    /// The blobs whose sessions were opened this run, in ladder order.
589    pub pushed: Vec<PushedBlob>,
590    /// Blobs the server already held (skipped from server truth, before any request).
591    pub already_held: usize,
592    /// Blobs a staged policy deferred to a later window.
593    pub deferred: usize,
594    /// Total bytes handed to the upload client this run.
595    pub bytes: u64,
596    /// The content addresses the server must hold once this run is done, in ladder order:
597    /// every blob of the bundle except those a staged policy deferred. This is the set
598    /// [`verify_custody`] declares to `/storage/verify` and requires a receipt for — a deferred
599    /// tier was never sent, so it is not yet the server's to hold.
600    pub custody_hashes: Vec<String>,
601}
602
603impl AssetPushReport {
604    /// The ladder sequence actually driven — the ordering proof.
605    #[must_use]
606    pub fn tier_sequence(&self) -> Vec<UploadTier> {
607        self.pushed.iter().map(|b| b.tier).collect()
608    }
609
610    /// Whether this run moved nothing: every blob was already held or deferred.
611    #[must_use]
612    pub fn is_no_op(&self) -> bool {
613        self.pushed.is_empty()
614    }
615}
616
617/// Push one [`UploadBundle`] through `client`, in the order `scheduler` permits.
618///
619/// `held` is the set of blob content addresses the server already holds (from
620/// [`held_from_feed`](crate::staged::held_from_feed) over a fresh feed pull); those blobs are
621/// skipped without a request. `force` ignores `held` and re-drives every planned blob — the
622/// server still answers `duplicate_blob` for anything it holds, which resolves as a merge.
623///
624/// Every blob's transfer steps are published to `client`'s
625/// [`events`](UploadClient::with_events) handle, tagged with the blob's content address.
626#[instrument(skip_all, fields(asset_id = %bundle.asset_id, album_id = %bundle.album_id, force))]
627pub async fn push_bundle<H: std::hash::BuildHasher + Sync>(
628    client: &UploadClient,
629    scheduler: &StagedScheduler,
630    bundle: &UploadBundle,
631    held: &HashSet<String, H>,
632    force: bool,
633) -> Result<AssetPushReport, PushError> {
634    push_bundle_with(client, scheduler, bundle, held, force, None).await
635}
636
637/// [`push_bundle`], with every range reserved through `gate` when there is one.
638async fn push_bundle_with<H: std::hash::BuildHasher + Sync>(
639    client: &UploadClient,
640    scheduler: &StagedScheduler,
641    bundle: &UploadBundle,
642    held: &HashSet<String, H>,
643    force: bool,
644    gate: Option<&dyn TransferGate>,
645) -> Result<AssetPushReport, PushError> {
646    let asset_id = bundle.asset_id.to_string();
647    let planned = plan(scheduler, bundle, held, force);
648    let blobs = bundle_blobs(bundle);
649
650    let mut report = AssetPushReport {
651        asset_id: asset_id.clone(),
652        already_held: planned.already_held,
653        deferred: planned.deferred,
654        custody_hashes: custody_hashes(&blobs, &planned.deferred_hashes),
655        ..Default::default()
656    };
657    tracing::info!(
658        planned = planned.blobs.len(),
659        already_held = planned.already_held,
660        deferred = planned.deferred,
661        bytes = planned.bytes,
662        "push: bundle planned"
663    );
664
665    for tier_blob in planned.blobs {
666        let Some((blob, hash)) = blobs.iter().find(|(_, hash)| *hash == tier_blob.hash) else {
667            return Err(PushError::UnknownBlob {
668                asset_id,
669                hash: tier_blob.hash,
670            });
671        };
672        let request = create_request(bundle, blob, hash);
673        tracing::info!(
674            tier = ?tier_blob.tier,
675            role = ?blob.role,
676            hash = %hash,
677            bytes = blob.bytes.size(),
678            content_type = %blob.content_type,
679            "push: opening upload session"
680        );
681        let uploaded = match gate {
682            Some(gate) => client.upload_gated(&request, &blob.bytes, gate).await,
683            None => client.upload(&request, &blob.bytes).await,
684        }
685        .map_err(|error| classify_refusal(bundle, blob, error))?;
686        let outcome = match uploaded {
687            UploadOutcome::Completed { session_id } => {
688                tracing::info!(tier = ?tier_blob.tier, hash = %hash, %session_id, "push: blob transferred");
689                TierSessionOutcome::Uploaded { session_id }
690            }
691            UploadOutcome::AlreadyStored { asset_ref } => {
692                tracing::info!(tier = ?tier_blob.tier, hash = %hash, %asset_ref, "push: blob already stored — merged");
693                TierSessionOutcome::AlreadyStored { asset_ref }
694            }
695        };
696        report.bytes += blob.bytes.size();
697        report.pushed.push(PushedBlob {
698            tier: tier_blob.tier,
699            hash: hash.clone(),
700            outcome,
701        });
702    }
703
704    tracing::info!(
705        pushed = report.pushed.len(),
706        bytes = report.bytes,
707        "push: bundle complete"
708    );
709    Ok(report)
710}
711
712// ─── Pushing many bundles across lanes ───────────────────────────────────────
713
714/// One bundle queued on a lane, with the server truth its plan prunes against (see
715/// [`push_bundle`]'s `held`).
716pub struct LaneBundle<'a, H> {
717    /// The bundle to push.
718    pub bundle: &'a UploadBundle,
719    /// The blob content addresses the lane's server already holds.
720    pub held: &'a HashSet<String, H>,
721}
722
723// By hand: a derive would demand `H: Clone`, but only references are copied.
724impl<H> Clone for LaneBundle<'_, H> {
725    fn clone(&self) -> Self {
726        *self
727    }
728}
729
730impl<H> Copy for LaneBundle<'_, H> {}
731
732/// One server's share of a [`push_lanes`] run: the client that reaches it, and the bundles
733/// queued for it.
734pub struct LanePush<'a, H> {
735    /// The lane's key: the server's canonical origin.
736    pub server: ServerKey,
737    /// The client every session on the lane is driven through.
738    pub client: &'a UploadClient,
739    /// The bundles queued on the lane, in the order they were planned.
740    pub bundles: Vec<LaneBundle<'a, H>>,
741    /// The account's live-session cap on the server, where the caller knows it: the lane's W
742    /// never exceeds it ([`UploadQueue::set_session_cap`]). `None` leaves W at the run's window
743    /// and the server's advice.
744    pub session_cap: Option<u32>,
745}
746
747/// The device-wide byte budget a push run's ranges reserve against when the caller has no
748/// narrower one: four of the protocol's largest chunks in flight at once, however many sessions
749/// and servers the run drives.
750pub const PUSH_BYTE_BUDGET: u64 = 4 * crate::upload::PROTOCOL_MAX_CHUNK;
751
752/// The most bundles a caller pushing a long list of assets should hold at once: it pushes them
753/// in batches of this many, each batch through one [`push_lanes`] run. Four times the widest
754/// sessions window keeps that window full for most of a batch, while a list of any length holds
755/// at most this many bundles' derivatives in memory.
756pub const PUSH_BATCH_BUNDLES: usize = 4 * crate::upload::queue::MAX_SESSIONS_WINDOW as usize;
757
758/// What every lane of a run shares: the device's one upload queue, and the signal a released
759/// reservation or a finished session sends to the ranges waiting on the budget.
760struct LaneShared {
761    queue: Mutex<UploadQueue<(usize, usize)>>,
762    freed: tokio::sync::Notify,
763}
764
765impl LaneShared {
766    fn queue(&self) -> MutexGuard<'_, UploadQueue<(usize, usize)>> {
767        // A panic while holding the lock left a scheduler of plain values; it stays usable.
768        self.queue.lock().unwrap_or_else(PoisonError::into_inner)
769    }
770}
771
772/// The gate one admitted bundle's transfers run under: every range reserves its length in the
773/// shared queue under the bundle's grant, and the server's advice lowers its lane's windows.
774struct QueueGate<'s> {
775    shared: &'s LaneShared,
776    server: &'s ServerKey,
777    grant: GrantId,
778}
779
780impl TransferGate for QueueGate<'_> {
781    fn reserve(
782        &self,
783        len: u64,
784    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Option<RangeId>> + Send + '_>> {
785        Box::pin(async move {
786            loop {
787                // Register for the next release before asking, so one that lands between the
788                // refusal and the wait is not missed.
789                let mut freed = std::pin::pin!(self.shared.freed.notified());
790                freed.as_mut().enable();
791                let (asked, still_waiting) = {
792                    let mut queue = self.shared.queue();
793                    let asked = queue.reserve_range(self.grant, len, Instant::now());
794                    (asked, queue.waiting_for_budget())
795                };
796                match asked {
797                    Ok(range) => {
798                        // The budget serves its line first-come: a waiter woken by the release
799                        // this range was served from, and refused for being behind it, asks
800                        // again now that it is next.
801                        if still_waiting > 0 {
802                            self.shared.freed.notify_waiters();
803                        }
804                        return Some(range);
805                    }
806                    Err(RangeRefused::NotInFlight) => {
807                        tracing::warn!(server = %self.server, "push: a range asked for a grant no longer in flight");
808                        return None;
809                    }
810                    Err(refused @ (RangeRefused::WindowFull | RangeRefused::BudgetFull)) => {
811                        tracing::trace!(server = %self.server, len, ?refused, "push: waiting for a range reservation");
812                    }
813                }
814                freed.await;
815            }
816        })
817    }
818
819    fn release(&self, range: RangeId) {
820        self.shared.queue().release_range(range, Instant::now());
821        self.shared.freed.notify_waiters();
822    }
823
824    fn advised(&self, advice: &ServerAdvice) {
825        let mut queue = self.shared.queue();
826        queue.set_advice(self.server, *advice, Instant::now());
827        queue.set_session_ranges(self.grant, advice);
828    }
829}
830
831/// Push every lane's bundles through one device-wide [`UploadQueue`], up to W at once per lane.
832///
833/// Each bundle is one job on its server's lane, queued at its lowest planned tier. The queue
834/// admits up to `windows.sessions` bundles per lane at once, lowered by the advice each server
835/// sends and by the lane's [`session_cap`](LanePush::session_cap), serving lanes round-robin; a bundle drives its own blobs one session at a time in
836/// ladder order, exactly as [`push_bundle`] does, so W bundles in flight are W sessions, each on
837/// its own HTTP/1.1 connection. Every range any of them sends reserves its length against the
838/// one `budget` before its bytes are read, and waits while the budget is full. A session holds
839/// up to the lane's P ranges in flight (`windows.ranges`, never more than the lane client's own
840/// window), lowered by the server's advice. Each lane's
841/// client spends from its lane's shared retry budget, so a failing server costs a bounded number
842/// of retries across all of its bundles.
843///
844/// Returns each lane's results in the order of its bundles. One bundle's failure is its own:
845/// the others still run.
846#[instrument(skip_all, fields(lanes = lanes.len(), budget, sessions = windows.sessions, ranges = windows.ranges, force))]
847pub async fn push_lanes<H: std::hash::BuildHasher + Sync>(
848    scheduler: &StagedScheduler,
849    lanes: &[LanePush<'_, H>],
850    force: bool,
851    budget: u64,
852    windows: LaneWindows,
853) -> Vec<Vec<Result<AssetPushReport, PushError>>> {
854    // No stall reclaim here: each request's own stall bound already cuts a link that stops
855    // moving (`RequestBounds`), and the transfer resumes or fails inside its bundle.
856    let mut queue = UploadQueue::new(budget, Duration::from_secs(3600)).with_windows(windows);
857    let mut clients = Vec::with_capacity(lanes.len());
858    for (lane_at, lane) in lanes.iter().enumerate() {
859        // Each session plans no more ranges than the lane's P lets it reserve; a source that
860        // does not verify what it re-derives is still sent one at a time.
861        let ranges = lane.client.ranges_window().min(windows.ranges);
862        clients.push(
863            lane.client
864                .clone()
865                .with_ranges_window(ranges)
866                .with_lane_retries(queue.lane_retries(&lane.server)),
867        );
868        if let Some(cap) = lane.session_cap {
869            queue.set_session_cap(&lane.server, cap);
870        }
871        for (bundle_at, queued) in lane.bundles.iter().enumerate() {
872            let tier = plan(scheduler, queued.bundle, queued.held, force)
873                .blobs
874                .first()
875                .map_or(UploadTier::Index, |blob| blob.tier);
876            queue.enqueue(&lane.server, QueuedJob::new(tier, (lane_at, bundle_at)));
877        }
878    }
879    let shared = LaneShared {
880        queue: Mutex::new(queue),
881        freed: tokio::sync::Notify::new(),
882    };
883    let mut results: Vec<Vec<Option<Result<AssetPushReport, PushError>>>> = lanes
884        .iter()
885        .map(|lane| lane.bundles.iter().map(|_| None).collect())
886        .collect();
887
888    type Running<'f> = std::pin::Pin<
889        Box<
890            dyn std::future::Future<
891                    Output = (usize, usize, GrantId, Result<AssetPushReport, PushError>),
892                > + Send
893                + 'f,
894        >,
895    >;
896    let mut running: Vec<Running<'_>> = Vec::new();
897    loop {
898        let admitted: Vec<_> = {
899            let mut queue = shared.queue();
900            let now = Instant::now();
901            std::iter::from_fn(|| queue.next(now)).collect()
902        };
903        for grant in admitted {
904            let (lane_at, bundle_at) = grant.job;
905            let lane = &lanes[lane_at];
906            let queued = lane.bundles[bundle_at];
907            let client = &clients[lane_at];
908            let shared = &shared;
909            tracing::info!(
910                server = %lane.server,
911                asset_id = %queued.bundle.asset_id,
912                ranges = grant.ranges,
913                "push: bundle admitted to its lane"
914            );
915            running.push(Box::pin(async move {
916                let gate = QueueGate {
917                    shared,
918                    server: &lane.server,
919                    grant: grant.id,
920                };
921                let pushed = push_bundle_with(
922                    client,
923                    scheduler,
924                    queued.bundle,
925                    queued.held,
926                    force,
927                    Some(&gate),
928                )
929                .await;
930                (lane_at, bundle_at, grant.id, pushed)
931            }));
932        }
933        if running.is_empty() {
934            break;
935        }
936        let (at, (lane_at, bundle_at, grant, pushed)) = std::future::poll_fn(|cx| {
937            for (at, bundle) in running.iter_mut().enumerate() {
938                if let std::task::Poll::Ready(done) = bundle.as_mut().poll(cx) {
939                    return std::task::Poll::Ready((at, done));
940                }
941            }
942            std::task::Poll::Pending
943        })
944        .await;
945        drop(running.swap_remove(at));
946        shared.queue().complete(grant, Instant::now());
947        shared.freed.notify_waiters();
948        if let Err(error) = &pushed {
949            tracing::warn!(server = %lanes[lane_at].server, kind = error.kind(), %error, "push: a bundle on the lane failed");
950        }
951        results[lane_at][bundle_at] = Some(pushed);
952    }
953    debug_assert!(shared.queue().is_empty(), "no lane is ever paused here");
954    results
955        .into_iter()
956        .map(|lane| {
957            lane.into_iter()
958                .map(|pushed| pushed.expect("every queued bundle runs before the queue drains"))
959                .collect()
960        })
961        .collect()
962}
963
964/// Name a transfer failure [`PushError::CreateRefused`] when it is the one a stale-epoch create
965/// meets: the server's finalization refused the **provenance** blob of a **create** bundle
966/// (`error.upload.envelope_rejected`). Every other failure stays [`PushError::Upload`].
967///
968/// Decided here, where the blob's role is known, because the wire answer is generic: the same
969/// code covers every re-validation a finalization runs, and it is the role that rules out the one
970/// unsafe reading. A refusal on any later rung could follow a provenance blob that did land, and
971/// re-sealing an asset the server already published would fork its chain.
972fn classify_refusal(bundle: &UploadBundle, blob: &BundleBlob<'_>, error: UploadError) -> PushError {
973    let refused_at_finalize = matches!(
974        &error,
975        UploadError::Rejected { code: Some(code), .. }
976            if code == capsule_i18n::error_codes::UPLOAD_ENVELOPE_REJECTED
977    );
978    let is_genesis = bundle.action == capsule_core::crypto::provenance::Action::Create
979        && bundle.prior_provenance_hash.is_none();
980    if refused_at_finalize && is_genesis && blob.role == BlobRole::Provenance {
981        tracing::warn!(
982            amk_version = bundle.amk_version,
983            "push: the server refused this create's manifest at finalization; \
984             nothing of it is published"
985        );
986        return PushError::CreateRefused {
987            asset_id: bundle.asset_id.to_string(),
988            amk_version: bundle.amk_version,
989            source: Box::new(error),
990        };
991    }
992    PushError::Upload(error)
993}
994
995// ─── Redacting a deleted asset ────────────────────────────────────────────────
996
997/// What [`redact_asset`] did to one asset's open upload sessions.
998#[derive(Debug, Clone, Default, PartialEq, Eq)]
999pub struct Redaction {
1000    /// The sessions cancelled (`DELETE /upload/{id}` answered `204` or `404`): no further byte
1001    /// of them is sent, and the server dropped what they had staged.
1002    pub cancelled: Vec<String>,
1003    /// The sessions the server would not cancel because their finalization was already running
1004    /// or done (`409 error.upload.session_not_active`). Their blob lands; the asset's `delete`
1005    /// record, sent after, supersedes the create it completes.
1006    pub finalizing: Vec<String>,
1007}
1008
1009/// Abort every open upload session this account holds for `asset_id`: the network half of
1010/// redacting an asset deleted before its upload finished
1011/// ([Organization — Deletion State Machine]).
1012///
1013/// The sessions come from `GET /upload/sessions`, filtered by the asset each names, so a
1014/// session a previous run left behind (a staged tier that never finished, a push killed
1015/// mid-ladder) is found without any client-side state. A session the listing names as terminal
1016/// (`completed`, `failed_processing`) is skipped: its outcome is decided and it is neither
1017/// cancelled nor finalizing. Each other session is cancelled with `DELETE /upload/{id}`:
1018///
1019/// - `204` or `404` is a cancelled session: its staged bytes and quota reservation are released.
1020/// - `409 error.upload.session_not_active` is the race with a finalization that started before
1021///   the abort reached it. Finalization is not interruptible, so that blob lands; the session is
1022///   reported in [`Redaction::finalizing`] and the caller's `delete` supersedes the create.
1023///
1024/// Any other answer fails the redaction. Re-running it is safe: a session already cancelled is a
1025/// `404`, and the listing no longer names it.
1026///
1027/// Pending tiers need no call: a deferred tier has no session, and a push of a trashed asset
1028/// plans nothing, so the abort is the whole of what the server has to forget.
1029///
1030/// [Organization — Deletion State Machine]: https://docs/design/organization/#deletion-state-machine
1031#[instrument(skip(client), fields(%asset_id))]
1032pub async fn redact_asset(client: &UploadClient, asset_id: &str) -> Result<Redaction, UploadError> {
1033    let sessions = client.list_sessions().await?;
1034    let mut redaction = Redaction::default();
1035    let mut settled = 0_usize;
1036    for session in sessions.iter().filter(|s| s.asset_id == asset_id) {
1037        if is_settled(&session.status) {
1038            tracing::debug!(session_id = %session.id, status = %session.status, "redact: the session already settled; nothing to cancel");
1039            settled += 1;
1040            continue;
1041        }
1042        match client.delete(&session.id).await {
1043            Ok(()) => {
1044                tracing::info!(session_id = %session.id, status = %session.status, received = session.received_bytes, "redact: upload session cancelled");
1045                redaction.cancelled.push(session.id.clone());
1046            }
1047            Err(UploadError::Rejected {
1048                status: 409,
1049                code: Some(code),
1050                ..
1051            }) if code == capsule_i18n::error_codes::UPLOAD_SESSION_NOT_ACTIVE => {
1052                tracing::info!(session_id = %session.id, status = %session.status, "redact: the session is already finalizing; its delete will supersede it");
1053                redaction.finalizing.push(session.id.clone());
1054            }
1055            Err(error) => {
1056                tracing::warn!(session_id = %session.id, %error, "redact: an upload session could not be cancelled");
1057                return Err(error);
1058            }
1059        }
1060    }
1061    tracing::info!(
1062        listed = sessions.len(),
1063        settled,
1064        cancelled = redaction.cancelled.len(),
1065        finalizing = redaction.finalizing.len(),
1066        "redact: the asset's open upload sessions are aborted"
1067    );
1068    Ok(redaction)
1069}
1070
1071/// Whether a listed session status is terminal (`completed`, `failed_processing`): the server
1072/// keeps such a record until its lifetime cap, but there is nothing left to cancel and its
1073/// outcome is already decided. Any other status, including one this client does not know, is
1074/// treated as open, so a newer server's state is still cancelled rather than silently kept.
1075fn is_settled(status: &str) -> bool {
1076    matches!(status, "completed" | "failed_processing")
1077}
1078
1079// ─── Confirming custody ───────────────────────────────────────────────────────
1080
1081/// What [`verify_custody`] established for one asset.
1082#[derive(Debug, Clone, PartialEq, Eq)]
1083pub struct VerifiedCustody {
1084    /// The server's trusted clock when it judged the asset durable (RFC 3339).
1085    pub checked_at: String,
1086    /// One verified receipt per blob the asset relies on, in ladder order — the evidence the
1087    /// caller persists beside the provenance chain
1088    /// ([`append_receipt`](capsule_library::library::append_receipt)).
1089    pub receipts: Vec<CustodyReceipt>,
1090}
1091
1092/// The core receipt role for a protocol blob role, where the core's closed enum names it.
1093fn core_role(role: BlobRole) -> Option<CoreBlobRole> {
1094    match role {
1095        BlobRole::Original => Some(CoreBlobRole::Original),
1096        BlobRole::Derivative => Some(CoreBlobRole::Derivative),
1097        BlobRole::Metadata => Some(CoreBlobRole::Metadata),
1098        BlobRole::Provenance => Some(CoreBlobRole::Provenance),
1099        BlobRole::Backup | BlobRole::DerivativeManifest => None,
1100    }
1101}
1102
1103/// Check one receipt against the blob the client sent.
1104///
1105/// The four roles `capsule_core`'s receipt verifier names go through
1106/// [`verify_receipt`] unchanged. A `derivative_manifest` blob has no arm there, so it gets the
1107/// same signature and field checks spelled against its wire role; the `received_at` drift bound
1108/// is the one check it does not get, and that bound is evidentiary only.
1109fn check_receipt(
1110    receipt: &CustodyReceipt,
1111    keys: &[HybridVerifyingKey],
1112    blob: &BundleBlob<'_>,
1113    hash: Hash32,
1114    now_unix: i64,
1115) -> Result<(), ReceiptRejection> {
1116    let size = blob.bytes.size();
1117    // The chain position, and only on the blob that *is* the manifest. SHA-256 by definition,
1118    // which is what `hash_bytes` computes, whatever digest the suite addresses blobs with.
1119    let envelope_hash = (blob.role == BlobRole::Provenance)
1120        .then(|| blob.bytes.inline().map(hash_bytes))
1121        .flatten();
1122    if let Some(role) = core_role(blob.role) {
1123        let expected = ReceiptExpectations {
1124            ciphertext_hash: hash,
1125            size,
1126            role,
1127            envelope_hash,
1128        };
1129        return verify_receipt(receipt, keys, &expected, now_unix);
1130    }
1131    if !keys.iter().any(|key| receipt.verify_under(key)) {
1132        return Err(ReceiptRejection::Signature);
1133    }
1134    let core = &receipt.core;
1135    if core.ciphertext_hash != hash {
1136        return Err(ReceiptRejection::FieldMismatch("ciphertext_hash"));
1137    }
1138    if core.size != size {
1139        return Err(ReceiptRejection::FieldMismatch("size"));
1140    }
1141    if core.blob_role != wire_enum(&blob.role) {
1142        return Err(ReceiptRejection::FieldMismatch("blob_role"));
1143    }
1144    if core.envelope_hash.is_some() {
1145        return Err(ReceiptRejection::FieldMismatch("envelope_hash"));
1146    }
1147    Ok(())
1148}
1149
1150/// Confirm the server holds what [`push_bundle`] sent, and collect the evidence that it does.
1151///
1152/// Two facts, both required, in this order:
1153///
1154/// 1. **Durability.** `POST /storage/verify` over exactly `report.custody_hashes`. The verdict's
1155///    aggregate is not trusted on its own: every declared hash must appear in the per-blob
1156///    detail as stored ∧ indexed ∧ retrievable, the re-check
1157///    [`release_is_safe`](capsule_library::library::release_is_safe) makes before a release.
1158/// 2. **Accountability.** The asset's receipt log (`GET /assets/{id}/receipts`), and for every
1159///    declared blob a receipt that verifies under one of `attestation_keys` (the pinned
1160///    history, not a fetch the caller has not checked against its pin) and names the
1161///    bytes, size, role and — for the provenance blob — the chain position the client sent.
1162///
1163/// The durable log rather than the per-session fetch, because a blob this run did not
1164/// transfer — one the feed said was held, or one a retry of this same asset found finalized as
1165/// `duplicate_blob` — has no session to ask about, and its custody needs the same evidence as a
1166/// fresh one. A `duplicate_blob` naming a *different* asset is covered the same way: the server
1167/// adopts that blob onto this asset before refusing (#672), indexing it under this asset and
1168/// receipting it in this asset's log.
1169///
1170/// `now_unix` is the client's clock, injected for the receipt's drift bound.
1171pub async fn verify_custody(
1172    client: &StorageVerifyClient,
1173    attestation_keys: &[HybridVerifyingKey],
1174    bundle: &UploadBundle,
1175    report: &AssetPushReport,
1176    now_unix: i64,
1177) -> Result<VerifiedCustody, PushError> {
1178    verify_custody_with_events(
1179        client,
1180        attestation_keys,
1181        bundle,
1182        report,
1183        now_unix,
1184        &TransferEvents::disabled(),
1185    )
1186    .await
1187}
1188
1189/// [`verify_custody`], publishing the verdict ([`TransferEvent::Verify`]) and each verified
1190/// receipt ([`TransferEvent::Receipt`]) to `events`.
1191#[instrument(skip_all, fields(asset_id = %bundle.asset_id, blobs = report.custody_hashes.len()))]
1192pub async fn verify_custody_with_events(
1193    client: &StorageVerifyClient,
1194    attestation_keys: &[HybridVerifyingKey],
1195    bundle: &UploadBundle,
1196    report: &AssetPushReport,
1197    now_unix: i64,
1198    events: &TransferEvents,
1199) -> Result<VerifiedCustody, PushError> {
1200    let asset_id = bundle.asset_id.to_string();
1201    let blobs = bundle_blobs(bundle);
1202    let mut declared = Vec::with_capacity(report.custody_hashes.len());
1203    for hash in &report.custody_hashes {
1204        let Some((blob, _)) = blobs.iter().find(|(_, candidate)| candidate == hash) else {
1205            return Err(PushError::UnknownBlob {
1206                asset_id,
1207                hash: hash.clone(),
1208            });
1209        };
1210        let parsed = Hash32::from_hex(hash).map_err(|_| PushError::UnknownBlob {
1211            asset_id: asset_id.clone(),
1212            hash: hash.clone(),
1213        })?;
1214        declared.push((blob, hash, parsed));
1215    }
1216
1217    // 1. Durability.
1218    let query = AssetQuery {
1219        asset_id: bundle.asset_id,
1220        blob_hashes: declared.iter().map(|(_, _, parsed)| *parsed).collect(),
1221    };
1222    let verdict = client
1223        .verify(&[query], false)
1224        .await?
1225        .into_iter()
1226        .find(|verdict| verdict.asset_id == bundle.asset_id)
1227        .ok_or_else(|| VerifyError::Malformed("the verdict omits the asset asked about".into()))?;
1228    let not_durable: Vec<String> = declared
1229        .iter()
1230        .filter(|(_, _, parsed)| {
1231            !verdict
1232                .blobs
1233                .iter()
1234                .any(|blob| blob.hash == *parsed && blob.safely_stored())
1235        })
1236        .map(|(_, hash, _)| (*hash).clone())
1237        .collect();
1238    events.emit(|| TransferEvent::Verify {
1239        asset_id: asset_id.clone(),
1240        durable: verdict.durable,
1241        blobs: declared.len() as u64,
1242        not_durable: not_durable.len() as u64,
1243    });
1244    if !verdict.durable || !not_durable.is_empty() {
1245        tracing::warn!(
1246            durable = verdict.durable,
1247            not_durable = ?not_durable,
1248            "push: the server does not durably hold the asset"
1249        );
1250        return Err(PushError::NotDurable {
1251            asset_id,
1252            not_durable,
1253        });
1254    }
1255    tracing::debug!(checked_at = %verdict.checked_at, "push: the server reports the asset durable");
1256
1257    // 2. Accountability.
1258    let log = client.fetch_asset_receipts(bundle.asset_id).await?;
1259    tracing::debug!(
1260        receipts = log.len(),
1261        "push: the asset's receipt log fetched"
1262    );
1263    let mut receipts = Vec::with_capacity(declared.len());
1264    for (blob, hash, parsed) in declared {
1265        let mut last_rejection = None;
1266        let mut verified = None;
1267        for candidate in log.iter().filter(|r| r.core.ciphertext_hash == parsed) {
1268            match check_receipt(candidate, attestation_keys, blob, parsed, now_unix) {
1269                Ok(()) => {
1270                    verified = Some(candidate.clone());
1271                    break;
1272                }
1273                Err(rejection) => last_rejection = Some(rejection),
1274            }
1275        }
1276        match (verified, last_rejection) {
1277            (Some(receipt), _) => {
1278                tracing::debug!(
1279                    hash = %hash,
1280                    role = ?blob.role,
1281                    receipt_seq = receipt.core.receipt_seq,
1282                    "push: custody receipt verified"
1283                );
1284                events.emit(|| TransferEvent::Receipt {
1285                    asset_id: asset_id.clone(),
1286                    blob: hash.clone(),
1287                    receipt_seq: receipt.core.receipt_seq,
1288                });
1289                receipts.push(receipt);
1290            }
1291            (None, Some(rejection)) => {
1292                tracing::warn!(hash = %hash, ?rejection, "push: custody receipt refused");
1293                return Err(PushError::ReceiptRejected {
1294                    asset_id,
1295                    hash: hash.clone(),
1296                    rejection,
1297                });
1298            }
1299            (None, None) => {
1300                tracing::warn!(hash = %hash, "push: no custody receipt for a blob");
1301                return Err(PushError::ReceiptMissing {
1302                    asset_id,
1303                    hash: hash.clone(),
1304                });
1305            }
1306        }
1307    }
1308
1309    tracing::info!(receipts = receipts.len(), "push: custody verified");
1310    Ok(VerifiedCustody {
1311        checked_at: verdict.checked_at,
1312        receipts,
1313    })
1314}
1315
1316#[cfg(test)]
1317mod tests;