Skip to main content

capsule_sdk/peering/
delegation.rs

1//! Upload delegation: a device hands sealed, signed upload bundles to another device of the same
2//! account, which uploads them later as an opaque courier (SSoT: [Peering § Delegation]).
3//!
4//! ```text
5//! origin: seal + sign bundle ──hand-off──▶ delegate: verify, fsync, ack, upload ──▶ server
6//!    ▲                                                                                │
7//!    └──────── origin verifies custody of the hashes it computed itself ◀────────────┘
8//! ```
9//!
10//! # What moves
11//!
12//! A [`HandOff`] is one asset's upload bundle exactly as the origin would upload it: every
13//! blob's `POST /v1/upload` body ([`CreateUploadRequest`], built by [`crate::push`]) and the
14//! blob's bytes, which are ciphertext or signed CBOR. The delegate never holds an album key or
15//! plaintext for it, never re-signs, re-encrypts or re-derives anything, and uploads the requests
16//! byte for byte under its **own** session. The server admits the manifest on the origin's
17//! signature, never on who uploads it (`capsule-server::upload::signer`).
18//!
19//! A hand-off is per asset and all or nothing: the delegate verifies every member against the
20//! signed manifest before it persists any of it, so it never uploads an incomplete bundle.
21//!
22//! # The origin ([`OriginLedger`])
23//!
24//! [`seal`] builds the hand-off and records the hashes the origin computed itself. The
25//! [`OriginLedger`] holds each [`Delegation`] with a **monotonic** deadline: on expiry, when the
26//! delegate is revoked, or when the clock the deadline was set on is gone (a reboot), the asset
27//! is re-queued for the origin to upload itself or delegate again ([`OriginLedger::due`]). It is
28//! released only through the verify-before-destroy gate over custody facts the origin fetched
29//! with its own session for its own hashes, plus a read-back of its own copy
30//! ([`OriginLedger::release`]); an acknowledgement is never custody, and nothing the delegate
31//! relays is consulted. A signed delete of a handed-off asset is held until the create's custody
32//! is confirmed ([`OriginLedger::hold_delete`]), so the server never sees a delete for an asset
33//! it has not indexed.
34//!
35//! # The delegate
36//!
37//! [`accept_hand_off`] verifies a hand-off ([`verify_hand_off`]), persists it durably through a
38//! [`DelegateInbox`] and only then returns the [`HandOffAck`]. [`upload_hand_off`] drives the
39//! requests in ladder order under the delegate's own [`StagedScheduler`] (its own battery and
40//! metering policy), and [`settle`] deletes the delegate's copy once custody of every blob it
41//! sent is confirmed. A delegate copy is never a library asset. A held hand-off that can never
42//! succeed — its origin revoked after acceptance, its bytes no longer verifying, or a server
43//! refusal the delegate cannot act on — is **quarantined** by [`dispose_failure`], never deleted:
44//! a revoked origin is often a lost device, and the delegate's copy may be the only one left. A
45//! quarantined copy keeps its bytes, is no longer retried, and is deleted only when the user
46//! asks ([`DelegateInbox::discard`]). A transient failure keeps the copy for the next run
47//! ([`DelegationError::is_permanent`]).
48//!
49//! # Transport
50//!
51//! The hand-off is a self-verifying byte string with a content address ([`HandOff::address`]),
52//! so it rides any channel: the peering channel ([`offer_hand_offs`] on the origin,
53//! [`take_hand_offs`] on the delegate, a resumable ranged pull and the acknowledgement over the
54//! same verified TLS session), or a file a CLI writes and another reads. Integrity never depends
55//! on the channel: the delegate re-verifies every hash and the manifest's signature, the server
56//! verifies the signature again, and the origin trusts only custody it fetched itself. What the
57//! channel adds is identity: a peer serves only hand-offs it sealed itself, and an
58//! acknowledgement counts only from the device the hand-off was sealed for.
59//!
60//! [Peering § Delegation]: https://docs/design/peering/#delegation
61
62use std::collections::{BTreeMap, BTreeSet};
63use std::sync::Mutex;
64use std::{fmt, io};
65
66use bytes::Bytes;
67use capsule_core::cbor;
68use capsule_core::crypto::hash::{Hash32, hash_bytes};
69use capsule_core::crypto::provenance::{DerivativeManifest, ProvenanceRecord};
70use capsule_core::crypto::verify_asset::verify_device_signature;
71use capsule_library::import::UploadTier;
72use capsule_library::library::{
73    BlobRole as CoreBlobRole, ReceiptExpectations, ReleaseDecision, ReleaseGate, RetainReason,
74    StorageVerifier,
75};
76use capsule_library::lifecycle::UploadBundle;
77use serde::{Deserialize, Serialize};
78use tracing::instrument;
79use uuid::Uuid;
80
81use super::PeeringError;
82use super::channel::{
83    Offering, PeerChannel, PeerClient, PinnedTrust, ServeReport, admit_device, admit_directory,
84    serve,
85};
86use super::session::{DirectoryVersions, TrustSource};
87use super::transfer::pull_over_channel;
88use crate::push::{bundle_blobs, create_request};
89use crate::staged::{StagedAsset, StagedScheduler, TierBlob};
90use crate::upload::{BlobRole, CreateUploadRequest, UploadClient, UploadError, UploadOutcome};
91use crate::verify::{HeldRelease, ReleaseClock, ReleaseCoordinator};
92
93/// The hand-off container format this build writes, and the newest it reads.
94pub const HAND_OFF_FORMAT: u16 = 1;
95
96/// The bytes every hand-off starts with.
97const MAGIC: &[u8; 8] = b"CAPSHOF1";
98
99/// The largest header a hand-off may declare. The header is a few kilobytes of JSON (one upload
100/// request per blob); the ceiling bounds a malicious length prefix.
101pub const MAX_HAND_OFF_HEADER: usize = 1024 * 1024;
102
103/// How long an origin waits, by default, for a delegated asset's custody before it re-queues
104/// the upload itself.
105pub const DEFAULT_HAND_OFF_DEADLINE_MS: u64 = 24 * 60 * 60 * 1000;
106
107/// Why a hand-off could not be sealed, accepted, uploaded or settled.
108#[derive(Debug, thiserror::Error)]
109pub enum DelegationError {
110    /// The device directory or a device in it was refused (unknown, revoked, rolled back,
111    /// foreign).
112    #[error(transparent)]
113    Peering(#[from] PeeringError),
114    /// The origin named itself as the delegate.
115    #[error("a device cannot delegate to itself")]
116    SelfDelegation,
117    /// The bytes are not a hand-off this build reads.
118    #[error("malformed hand-off: {0}")]
119    Malformed(String),
120    /// The hand-off is in a container format newer than this build reads.
121    #[error("hand-off format {found} is newer than this build reads ({HAND_OFF_FORMAT})")]
122    UnsupportedFormat {
123        /// The format the container declares.
124        found: u16,
125    },
126    /// The hand-off was sealed for another delegate.
127    #[error("the hand-off is addressed to device {addressed}, not to this device")]
128    WrongDelegate {
129        /// The delegate the origin named.
130        addressed: Uuid,
131    },
132    /// The bundle's protocol version is newer than this delegate speaks. The delegate refuses
133    /// the hand-off and the origin keeps the upload.
134    #[error("the bundle speaks protocol {bundle}; this device speaks up to {ours}")]
135    ProtocolUnsupported {
136        /// The bundle's `protocol_version`.
137        bundle: String,
138        /// The newest protocol this delegate speaks.
139        ours: String,
140    },
141    /// A member of the bundle does not match what the signed manifest commits to, or its bytes
142    /// do not hash to what its request declares. Carries what failed.
143    #[error("the hand-off does not verify: {0}")]
144    Tampered(String),
145    /// Persisting, reading or removing the delegate's copy failed.
146    #[error("delegate inbox: {0}")]
147    Inbox(String),
148    /// The upload itself failed.
149    #[error(transparent)]
150    Upload(#[from] UploadError),
151    /// The origin ledger knows no delegation for the asset.
152    #[error("no delegation is recorded for asset {0}")]
153    UnknownDelegation(Uuid),
154    /// An acknowledgement names another hand-off or another delegate than the one recorded.
155    #[error("the acknowledgement does not match the recorded hand-off")]
156    AckMismatch,
157    /// A hand-off pulled over the peering channel was sealed by another device than the peer the
158    /// handshake verified: a peer serves only its own hand-offs.
159    #[error("the hand-off was sealed by device {origin}, not by the verified peer {peer}")]
160    WrongOrigin {
161        /// The origin the hand-off names.
162        origin: Uuid,
163        /// The peer the channel verified.
164        peer: Uuid,
165    },
166}
167
168/// The server's `error.*` codes that refuse a hand-off's requests for good. The delegate sends
169/// the origin's signed requests verbatim and can change none of them, so no later run of the
170/// same hand-off can succeed:
171///
172/// - `error.upload.envelope_rejected`: finalization re-validated the manifest and refused it —
173///   a create sealed under an album epoch the album has moved past (invariant 18), a signer
174///   revoked or not the account's, a signature that does not verify, or a role conflict.
175/// - `error.upload.envelope_mismatch`: a request contradicts its own manifest envelope.
176/// - `error.upload.stale_revival`: the asset's chain has moved past the one the manifest
177///   extends — a conflicting provenance only the origin can rebase.
178///
179/// The create-time answers to the conditions finalization answers with `envelope_rejected` are
180/// permanent for the same reason, so a condition is classified the same whichever step meets it:
181///
182/// - `error.upload.timestamp_out_of_range`: the signed manifest's timestamp is outside the
183///   accepted window (past the drift allowance); the timestamp is signed and cannot change.
184/// - `error.upload.album_access_denied`: the album is missing, closed, or not writable by the
185///   uploader.
186/// - `error.upload.device_not_authorized`: the signing device is not authorized in the
187///   uploader's directory.
188pub const PERMANENT_UPLOAD_REFUSALS: [&str; 6] = [
189    capsule_i18n::error_codes::UPLOAD_ENVELOPE_REJECTED,
190    capsule_i18n::error_codes::UPLOAD_ENVELOPE_MISMATCH,
191    capsule_i18n::error_codes::UPLOAD_STALE_REVIVAL,
192    capsule_i18n::error_codes::UPLOAD_TIMESTAMP_OUT_OF_RANGE,
193    capsule_i18n::error_codes::UPLOAD_ALBUM_ACCESS_DENIED,
194    capsule_i18n::error_codes::UPLOAD_DEVICE_NOT_AUTHORIZED,
195];
196
197impl DelegationError {
198    /// The stable name a `--json` report and a channel refusal carry this error under. A refused
199    /// device or directory is named by its [`PeeringError::kind`]; every other variant has its
200    /// own name, never renamed.
201    #[must_use]
202    pub fn kind(&self) -> &'static str {
203        match self {
204            Self::Peering(error) => error.kind(),
205            Self::SelfDelegation => "self_delegation",
206            Self::Malformed(_) => "malformed",
207            Self::UnsupportedFormat { .. } => "unsupported_format",
208            Self::WrongDelegate { .. } => "wrong_delegate",
209            Self::ProtocolUnsupported { .. } => "protocol_unsupported",
210            Self::Tampered(_) => "tampered",
211            Self::Inbox(_) => "inbox",
212            Self::Upload(_) => "upload",
213            Self::UnknownDelegation(_) => "unknown_delegation",
214            Self::AckMismatch => "ack_mismatch",
215            Self::WrongOrigin { .. } => "wrong_origin",
216        }
217    }
218
219    /// The stable `error.*` code the server supplied, when there was one.
220    #[must_use]
221    pub fn error_code(&self) -> Option<&str> {
222        match self {
223            Self::Upload(UploadError::UpgradeRequired { .. }) => {
224                Some(capsule_i18n::error_codes::PROTOCOL_VERSION_UNSUPPORTED)
225            }
226            Self::Upload(error) => error.error_code(),
227            _ => None,
228        }
229    }
230
231    /// Whether a hand-off the delegate holds, failing with this error, can never succeed, so
232    /// [`dispose_failure`] quarantines the delegate's copy rather than retrying it.
233    ///
234    /// Permanent: the origin is no longer an unrevoked device of the pinned directory (revoked
235    /// or removed after the hand-off was accepted); the held bytes no longer verify (malformed,
236    /// addressed to another device, tampered with); or the server refused the requests with one
237    /// of [`PERMANENT_UPLOAD_REFUSALS`]. Everything else is transient and keeps the copy for
238    /// the next run: this device's directory or trust state, a container or protocol newer
239    /// than this build (an update reads it), the inbox, the network, an outage, quota, rate
240    /// limits, and any other refusal.
241    #[must_use]
242    pub fn is_permanent(&self) -> bool {
243        match self {
244            Self::Peering(PeeringError::UnknownDevice(_) | PeeringError::RevokedDevice(_))
245            | Self::Malformed(_)
246            | Self::WrongDelegate { .. }
247            | Self::Tampered(_) => true,
248            Self::Upload(UploadError::Rejected {
249                code: Some(code), ..
250            }) => PERMANENT_UPLOAD_REFUSALS.contains(&code.as_str()),
251            _ => false,
252        }
253    }
254}
255
256/// The ladder tier a blob role belongs to (transfer upload doc, §Upload Tiering).
257#[must_use]
258pub fn tier_of(role: BlobRole) -> UploadTier {
259    match role {
260        BlobRole::Provenance | BlobRole::Metadata | BlobRole::Backup => UploadTier::Index,
261        BlobRole::DerivativeManifest | BlobRole::Derivative => UploadTier::Preview,
262        BlobRole::Original => UploadTier::Original,
263    }
264}
265
266// ─── The hand-off container ───────────────────────────────────────────────────
267
268/// The hand-off's header: who handed what to whom, and each member's upload request.
269#[derive(Debug, Clone, Serialize, Deserialize)]
270pub struct HandOffHeader {
271    /// The container format ([`HAND_OFF_FORMAT`]).
272    pub format: u16,
273    /// The asset the bundle uploads.
274    pub asset_id: Uuid,
275    /// The device that sealed and signed the bundle.
276    pub origin_device: Uuid,
277    /// The device the origin handed it to.
278    pub delegate_device: Uuid,
279    /// The bundle's protocol version — the one every request declares.
280    pub protocol_version: String,
281    /// Each member's `POST /v1/upload` body, in ladder order. The member's bytes follow the
282    /// header in the same order, each exactly `request.size` long.
283    pub members: Vec<CreateUploadRequest>,
284}
285
286/// One asset's sealed upload bundle, as it moves from the origin to the delegate.
287#[derive(Clone)]
288pub struct HandOff {
289    /// The header.
290    pub header: HandOffHeader,
291    /// Each member's bytes, in header order.
292    pub blobs: Vec<Vec<u8>>,
293}
294
295impl fmt::Debug for HandOff {
296    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
297        f.debug_struct("HandOff")
298            .field("header", &self.header)
299            .field("bytes", &self.blobs.iter().map(Vec::len).sum::<usize>())
300            .finish()
301    }
302}
303
304impl HandOff {
305    /// The container's bytes: the magic `CAPSHOF1`, the header's length (`u32`, big-endian), the
306    /// header as JSON, then every member's bytes in header order.
307    ///
308    /// # Errors
309    ///
310    /// [`DelegationError::Malformed`] when the header does not serialize or exceeds
311    /// [`MAX_HAND_OFF_HEADER`].
312    pub fn encode(&self) -> Result<Vec<u8>, DelegationError> {
313        let header = serde_json::to_vec(&self.header)
314            .map_err(|error| DelegationError::Malformed(error.to_string()))?;
315        if header.len() > MAX_HAND_OFF_HEADER {
316            return Err(DelegationError::Malformed(
317                "the header exceeds its ceiling".into(),
318            ));
319        }
320        let length = u32::try_from(header.len())
321            .map_err(|_| DelegationError::Malformed("the header exceeds u32".into()))?;
322        let body: usize = self.blobs.iter().map(Vec::len).sum();
323        let mut out = Vec::with_capacity(MAGIC.len() + 4 + header.len() + body);
324        out.extend_from_slice(MAGIC);
325        out.extend_from_slice(&length.to_be_bytes());
326        out.extend_from_slice(&header);
327        for blob in &self.blobs {
328            out.extend_from_slice(blob);
329        }
330        Ok(out)
331    }
332
333    /// Read a container back. Structure only: [`verify_hand_off`] decides whether to trust it.
334    ///
335    /// # Errors
336    ///
337    /// [`DelegationError::Malformed`] for anything that is not a well-formed container, and
338    /// [`DelegationError::UnsupportedFormat`] for one a newer build wrote.
339    pub fn decode(bytes: &[u8]) -> Result<Self, DelegationError> {
340        let malformed = |what: &str| DelegationError::Malformed(what.to_owned());
341        let rest = bytes
342            .strip_prefix(MAGIC.as_slice())
343            .ok_or_else(|| malformed("not a hand-off"))?;
344        let (length, rest) = rest
345            .split_first_chunk::<4>()
346            .ok_or_else(|| malformed("truncated header length"))?;
347        let length = u32::from_be_bytes(*length) as usize;
348        if length > MAX_HAND_OFF_HEADER || length > rest.len() {
349            return Err(malformed("header length out of bounds"));
350        }
351        let (header, mut body) = rest.split_at(length);
352        let format = serde_json::from_slice::<serde_json::Value>(header)
353            .ok()
354            .and_then(|value| value.get("format").and_then(serde_json::Value::as_u64))
355            .ok_or_else(|| malformed("the header names no format"))?;
356        if format > u64::from(HAND_OFF_FORMAT) {
357            return Err(DelegationError::UnsupportedFormat {
358                found: u16::try_from(format).unwrap_or(u16::MAX),
359            });
360        }
361        let header: HandOffHeader = serde_json::from_slice(header)
362            .map_err(|error| DelegationError::Malformed(error.to_string()))?;
363        let mut blobs = Vec::with_capacity(header.members.len());
364        for member in &header.members {
365            let size = usize::try_from(member.size).map_err(|_| malformed("member too large"))?;
366            if size > body.len() {
367                return Err(malformed("truncated member"));
368            }
369            let (blob, remaining) = body.split_at(size);
370            blobs.push(blob.to_vec());
371            body = remaining;
372        }
373        if !body.is_empty() {
374            return Err(malformed("trailing bytes after the last member"));
375        }
376        Ok(Self { header, blobs })
377    }
378
379    /// The content address of an encoded container (SHA-256, lowercase hex): what an
380    /// acknowledgement names and a ranged pull verifies.
381    #[must_use]
382    pub fn address(encoded: &[u8]) -> String {
383        hash_bytes(encoded).to_hex()
384    }
385}
386
387// ─── The origin ───────────────────────────────────────────────────────────────
388
389/// One blob the origin handed off, as the origin itself computed it.
390#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
391pub struct OwnBlob {
392    /// The blob's role.
393    pub role: BlobRole,
394    /// The content address the origin computed.
395    pub hash: Hash32,
396    /// Its size.
397    pub size: u64,
398}
399
400/// A sealed hand-off: the container to send and what the origin records about it.
401#[derive(Debug, Clone)]
402pub struct SealedHandOff {
403    /// The encoded container. Shared, not copied, by every clone and by the [`Offering`] that
404    /// serves it, so a hand-off of up to [`MAX_ARTIFACT_LEN`] bytes is held in memory once.
405    ///
406    /// [`Offering`]: super::channel::Offering
407    /// [`MAX_ARTIFACT_LEN`]: super::channel::MAX_ARTIFACT_LEN
408    pub bytes: Bytes,
409    /// Its content address.
410    pub address: String,
411    /// The asset.
412    pub asset_id: Uuid,
413    /// The delegate it is addressed to.
414    pub delegate: Uuid,
415    /// Every blob, as the origin computed it.
416    pub own: Vec<OwnBlob>,
417    /// What releasing the asset's original waits on: the origin's own original and metadata
418    /// hashes ([`HeldRelease::for_original`]).
419    pub release: Vec<Hash32>,
420}
421
422/// Seal `bundle` for `delegate`: the full upload bundle exactly as the origin would upload it,
423/// and the hashes the origin computed itself.
424///
425/// The delegate must be a device of `trust`'s directory that is not revoked, and not the device
426/// that signed the bundle.
427///
428/// # Errors
429///
430/// [`DelegationError::SelfDelegation`], a [`PeeringError`] for a delegate the directory does not
431/// admit, [`DelegationError::Inbox`] when the original cannot be read, or
432/// [`DelegationError::Malformed`] when the container cannot be encoded.
433#[instrument(skip_all, fields(asset_id = %bundle.asset_id, %delegate))]
434pub fn seal(
435    bundle: &UploadBundle,
436    delegate: Uuid,
437    trust: &PinnedTrust,
438) -> Result<SealedHandOff, DelegationError> {
439    if delegate == bundle.created_by_device {
440        return Err(DelegationError::SelfDelegation);
441    }
442    admit_device(trust, delegate)?;
443    let mut members = Vec::new();
444    let mut blobs = Vec::new();
445    let mut own = Vec::new();
446    for (blob, hash) in bundle_blobs(bundle) {
447        let bytes = blob
448            .bytes
449            .to_vec()
450            .map_err(|error| DelegationError::Inbox(format!("read the bundle: {error}")))?;
451        let computed = hash_bytes(&bytes);
452        if computed.to_hex() != hash {
453            // The bundle's own address disagrees with its bytes: the library is damaged, and
454            // handing it off would only move the damage.
455            return Err(DelegationError::Tampered(format!(
456                "the origin's {:?} blob does not hash to its address",
457                blob.role
458            )));
459        }
460        own.push(OwnBlob {
461            role: blob.role,
462            hash: computed,
463            size: bytes.len() as u64,
464        });
465        members.push(create_request(bundle, &blob, &hash));
466        blobs.push(bytes);
467    }
468    let hand_off = HandOff {
469        header: HandOffHeader {
470            format: HAND_OFF_FORMAT,
471            asset_id: bundle.asset_id,
472            origin_device: bundle.created_by_device,
473            delegate_device: delegate,
474            protocol_version: bundle.protocol_version.clone(),
475            members,
476        },
477        blobs,
478    };
479    let bytes = hand_off.encode()?;
480    let address = HandOff::address(&bytes);
481    let release = HeldRelease::for_original(bundle)
482        .blobs
483        .iter()
484        .map(|expected| expected.ciphertext_hash)
485        .collect();
486    tracing::info!(
487        %address,
488        members = hand_off.blobs.len(),
489        bytes = bytes.len(),
490        "delegation: hand-off sealed"
491    );
492    Ok(SealedHandOff {
493        bytes: Bytes::from(bytes),
494        address,
495        asset_id: bundle.asset_id,
496        delegate,
497        own,
498        release,
499    })
500}
501
502/// Where a delegation stands on the origin.
503#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
504#[serde(rename_all = "snake_case")]
505pub enum DelegationState {
506    /// Sealed and handed over; the delegate has not acknowledged it yet.
507    HandedOff,
508    /// The delegate verified and persisted it. Not custody.
509    Acknowledged,
510    /// The origin takes the upload back: it uploads the asset itself or delegates again.
511    Requeued,
512    /// The server holds the asset, by the origin's own check: the original may be released.
513    Released,
514}
515
516/// Why a delegation was re-queued.
517#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
518#[serde(rename_all = "snake_case")]
519pub enum RequeueReason {
520    /// The monotonic deadline passed without custody.
521    DeadlineExpired,
522    /// The delegate is no longer an unrevoked device of the directory.
523    DelegateRevoked,
524    /// The deadline was set on a monotonic clock that is gone (the device rebooted), so it can
525    /// no longer be measured; the upload is taken back rather than trusted to a stale clock.
526    ClockReset,
527}
528
529/// One delegated asset, as the origin records it.
530#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
531pub struct Delegation {
532    /// The asset.
533    pub asset_id: Uuid,
534    /// The device it was handed to.
535    pub delegate: Uuid,
536    /// The hand-off's content address.
537    pub hand_off: String,
538    /// Every blob, as the origin computed it.
539    pub own: Vec<OwnBlob>,
540    /// The hashes releasing the original waits on (original and metadata), the origin's own.
541    pub release: Vec<Hash32>,
542    /// The monotonic clock the deadline is on (a boot identity).
543    pub clock_epoch: String,
544    /// The deadline, in that clock's milliseconds.
545    pub deadline_ms: u64,
546    /// Where it stands.
547    pub state: DelegationState,
548    /// Why it was re-queued, once it was.
549    pub requeued_because: Option<RequeueReason>,
550    /// Signed deletes held until the create's custody exists, in the order they were made.
551    pub held_deletes: Vec<Vec<u8>>,
552}
553
554impl Delegation {
555    /// The line an origin shows for the asset while it waits: the delegate it was handed to,
556    /// awaiting the server.
557    #[must_use]
558    pub fn status_line(&self, delegate_name: &str) -> String {
559        match self.state {
560            DelegationState::HandedOff | DelegationState::Acknowledged => {
561                format!("handed to {delegate_name}, awaiting server")
562            }
563            DelegationState::Requeued => "re-queued to upload from this device".to_owned(),
564            DelegationState::Released => "held by the server".to_owned(),
565        }
566    }
567
568    fn is_open(&self) -> bool {
569        matches!(
570            self.state,
571            DelegationState::HandedOff | DelegationState::Acknowledged
572        )
573    }
574}
575
576/// A delegate's acknowledgement: it verified the hand-off and persisted it durably. Not custody.
577#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
578pub struct HandOffAck {
579    /// The asset.
580    pub asset_id: Uuid,
581    /// The hand-off's content address, as the delegate computed it over what it received.
582    pub hand_off: String,
583    /// The acknowledging device.
584    pub delegate_device: Uuid,
585}
586
587/// What [`OriginLedger::hold_delete`] did with a signed delete.
588#[derive(Debug, Clone, PartialEq, Eq)]
589pub enum DeleteDisposition {
590    /// The asset's create has no confirmed custody yet: the delete is held, and
591    /// [`OriginLedger::release`] hands it back once custody is confirmed.
592    Held,
593    /// No open delegation: send it now.
594    SendNow(Vec<u8>),
595}
596
597/// What [`OriginLedger::release`] decided.
598#[derive(Debug, Clone, PartialEq, Eq)]
599pub enum ReleaseOutcome {
600    /// Custody is confirmed: the original may be released, and these held deletes may now be
601    /// sent, in order.
602    Released {
603        /// The deletes held for the asset.
604        deletes: Vec<Vec<u8>>,
605    },
606    /// Not yet: the original stays pinned.
607    Retained(RetainReason),
608}
609
610/// The origin's record of every asset it handed off: pinned until its own custody check
611/// passes, re-queued on a deadline or a revocation.
612///
613/// Serializable whole, so a client persists it beside its own state and reloads it.
614#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
615pub struct OriginLedger {
616    delegations: BTreeMap<Uuid, Delegation>,
617}
618
619impl OriginLedger {
620    /// An empty ledger.
621    #[must_use]
622    pub fn new() -> Self {
623        Self::default()
624    }
625
626    /// Every recorded delegation, by asset.
627    pub fn delegations(&self) -> impl Iterator<Item = &Delegation> {
628        self.delegations.values()
629    }
630
631    /// The delegation recorded for `asset_id`.
632    #[must_use]
633    pub fn get(&self, asset_id: &Uuid) -> Option<&Delegation> {
634        self.delegations.get(asset_id)
635    }
636
637    /// Record `sealed` as handed over now: pinned, with a deadline `deadline_ms` from `now_ms`
638    /// on the monotonic clock `clock_epoch` names.
639    ///
640    /// Recording an asset that already has an open delegation replaces it: the origin delegated
641    /// again, and only the newest hand-off is waited on (the older one, if its delegate still
642    /// uploads it, is resolved by deduplication).
643    pub fn hand_off(
644        &mut self,
645        sealed: &SealedHandOff,
646        clock_epoch: &str,
647        now_ms: u64,
648        deadline_ms: u64,
649    ) {
650        let held_deletes = self
651            .delegations
652            .remove(&sealed.asset_id)
653            .map(|previous| previous.held_deletes)
654            .unwrap_or_default();
655        tracing::info!(
656            asset_id = %sealed.asset_id,
657            delegate = %sealed.delegate,
658            hand_off = %sealed.address,
659            deadline_ms,
660            "delegation: recorded hand-off; the original stays pinned"
661        );
662        self.delegations.insert(
663            sealed.asset_id,
664            Delegation {
665                asset_id: sealed.asset_id,
666                delegate: sealed.delegate,
667                hand_off: sealed.address.clone(),
668                own: sealed.own.clone(),
669                release: sealed.release.clone(),
670                clock_epoch: clock_epoch.to_owned(),
671                deadline_ms: now_ms.saturating_add(deadline_ms),
672                state: DelegationState::HandedOff,
673                requeued_because: None,
674                held_deletes,
675            },
676        );
677    }
678
679    /// Take the delegate's acknowledgement. It must name the recorded hand-off and delegate.
680    /// Changes nothing about custody.
681    ///
682    /// # Errors
683    ///
684    /// [`DelegationError::UnknownDelegation`] or [`DelegationError::AckMismatch`].
685    pub fn acknowledge(&mut self, ack: &HandOffAck) -> Result<(), DelegationError> {
686        let delegation = self
687            .delegations
688            .get_mut(&ack.asset_id)
689            .ok_or(DelegationError::UnknownDelegation(ack.asset_id))?;
690        if delegation.hand_off != ack.hand_off || delegation.delegate != ack.delegate_device {
691            tracing::warn!(asset_id = %ack.asset_id, "delegation: an acknowledgement did not match");
692            return Err(DelegationError::AckMismatch);
693        }
694        if delegation.state == DelegationState::HandedOff {
695            delegation.state = DelegationState::Acknowledged;
696        }
697        tracing::info!(asset_id = %ack.asset_id, "delegation: delegate acknowledged; not custody");
698        Ok(())
699    }
700
701    /// Re-queue every open delegation whose deadline passed on `clock_epoch` at `now_ms`, whose
702    /// deadline was set on another clock, or whose delegate `trust` no longer admits. Returns
703    /// the assets re-queued, for the caller to upload itself or delegate again.
704    pub fn due(
705        &mut self,
706        trust: &PinnedTrust,
707        clock_epoch: &str,
708        now_ms: u64,
709    ) -> Vec<(Uuid, RequeueReason)> {
710        let mut requeued = Vec::new();
711        for delegation in self.delegations.values_mut().filter(|d| d.is_open()) {
712            let reason = if admit_device(trust, delegation.delegate).is_err() {
713                Some(RequeueReason::DelegateRevoked)
714            } else if delegation.clock_epoch != clock_epoch {
715                Some(RequeueReason::ClockReset)
716            } else if now_ms >= delegation.deadline_ms {
717                Some(RequeueReason::DeadlineExpired)
718            } else {
719                None
720            };
721            if let Some(reason) = reason {
722                tracing::warn!(
723                    asset_id = %delegation.asset_id,
724                    delegate = %delegation.delegate,
725                    ?reason,
726                    "delegation: re-queued; the origin takes the upload back"
727                );
728                delegation.state = DelegationState::Requeued;
729                delegation.requeued_because = Some(reason);
730                requeued.push((delegation.asset_id, reason));
731            }
732        }
733        requeued
734    }
735
736    /// Release `asset_id`'s original only through the verify-before-destroy gate: `verifier`
737    /// answers for the **origin's own** hashes and must be backed by facts the origin fetched
738    /// with its own session ([`ReleaseCoordinator::resolve_custody`]), never anything the
739    /// delegate relayed. `verify_asset_accepted` is the origin's own `verify_asset` of the asset,
740    /// and `read_back` whether the origin's copy still hashes to the signed original.
741    ///
742    /// A released asset hands back its held deletes. Either upload's custody releases it — the
743    /// gate names content hashes, not who uploaded them — so a re-queued asset the origin
744    /// uploaded itself releases through here too.
745    ///
746    /// # Errors
747    ///
748    /// [`DelegationError::UnknownDelegation`].
749    pub fn release<V: StorageVerifier + ?Sized>(
750        &mut self,
751        asset_id: Uuid,
752        verifier: &V,
753        verify_asset_accepted: bool,
754        read_back: bool,
755    ) -> Result<ReleaseOutcome, DelegationError> {
756        let delegation = self
757            .delegations
758            .get_mut(&asset_id)
759            .ok_or(DelegationError::UnknownDelegation(asset_id))?;
760        if delegation.state == DelegationState::Released {
761            return Ok(ReleaseOutcome::Released {
762                deletes: Vec::new(),
763            });
764        }
765        if !read_back {
766            tracing::warn!(%asset_id, "delegation: the origin's copy does not read back; kept");
767            return Ok(ReleaseOutcome::Retained(RetainReason::ReadBackMismatch));
768        }
769        match ReleaseGate::new(verifier).may_release(
770            asset_id,
771            &delegation.release,
772            verify_asset_accepted,
773        ) {
774            ReleaseDecision::Release => {
775                delegation.state = DelegationState::Released;
776                let deletes = std::mem::take(&mut delegation.held_deletes);
777                tracing::info!(
778                    %asset_id,
779                    held_deletes = deletes.len(),
780                    "delegation: custody confirmed by the origin's own check; released"
781                );
782                Ok(ReleaseOutcome::Released { deletes })
783            }
784            ReleaseDecision::Retain(reason) => {
785                tracing::debug!(%asset_id, ?reason, "delegation: not yet held; still pinned");
786                Ok(ReleaseOutcome::Retained(reason))
787            }
788        }
789    }
790
791    /// A signed delete of `asset_id`: held while its create has no confirmed custody (an open
792    /// or re-queued delegation), so the server never sees a delete for an asset it has not
793    /// indexed; otherwise returned to send now.
794    pub fn hold_delete(&mut self, asset_id: Uuid, delete: Vec<u8>) -> DeleteDisposition {
795        match self.delegations.get_mut(&asset_id) {
796            Some(delegation) if delegation.state != DelegationState::Released => {
797                tracing::info!(%asset_id, "delegation: delete held until the create's custody");
798                delegation.held_deletes.push(delete);
799                DeleteDisposition::Held
800            }
801            _ => DeleteDisposition::SendNow(delete),
802        }
803    }
804
805    /// Forget a released or re-queued delegation the caller has finished with.
806    pub fn forget(&mut self, asset_id: &Uuid) -> Option<Delegation> {
807        self.delegations.remove(asset_id)
808    }
809}
810
811// ─── The delegate ─────────────────────────────────────────────────────────────
812
813/// A hand-off the delegate verified: every member hashes to what its request declares, the
814/// signed manifest verifies under the origin's published key, and every member is the one the
815/// manifest commits to.
816#[derive(Debug, Clone)]
817pub struct VerifiedHandOff {
818    /// The container's content address.
819    pub address: String,
820    /// The verified container.
821    pub hand_off: HandOff,
822}
823
824impl VerifiedHandOff {
825    /// The asset.
826    #[must_use]
827    pub fn asset_id(&self) -> Uuid {
828        self.hand_off.header.asset_id
829    }
830
831    /// Each member's request and bytes, in ladder order.
832    pub fn members(&self) -> impl Iterator<Item = (&CreateUploadRequest, &[u8])> {
833        self.hand_off
834            .header
835            .members
836            .iter()
837            .zip(self.hand_off.blobs.iter().map(Vec::as_slice))
838    }
839
840    /// What custody of every member the server can receipt looks like, for [`settle`].
841    #[must_use]
842    pub fn held_release(&self) -> HeldRelease {
843        let blobs = self
844            .members()
845            .filter_map(|(request, bytes)| {
846                let role = match request.blob_role {
847                    BlobRole::Original => CoreBlobRole::Original,
848                    BlobRole::Derivative => CoreBlobRole::Derivative,
849                    BlobRole::Metadata => CoreBlobRole::Metadata,
850                    BlobRole::Provenance => CoreBlobRole::Provenance,
851                    BlobRole::Backup | BlobRole::DerivativeManifest => return None,
852                };
853                Some(ReceiptExpectations {
854                    ciphertext_hash: hash_bytes(bytes),
855                    size: bytes.len() as u64,
856                    role,
857                    envelope_hash: (request.blob_role == BlobRole::Provenance)
858                        .then(|| hash_bytes(bytes)),
859                })
860            })
861            .collect();
862        HeldRelease {
863            asset_id: self.asset_id(),
864            blobs,
865        }
866    }
867}
868
869/// Verify a hand-off addressed to `delegate_device`, all or nothing.
870///
871/// `trust` is the account's directory as this device pins it (admitted against `versions`, so a
872/// stale directory cannot readmit a revoked origin); `max_protocol` is the newest upload
873/// protocol this delegate speaks.
874///
875/// # Errors
876///
877/// The [`DelegationError`] naming the first check that failed. Nothing is persisted.
878#[instrument(skip_all, fields(bytes = bytes.len(), delegate = %delegate_device))]
879pub fn verify_hand_off(
880    bytes: &[u8],
881    trust: &PinnedTrust,
882    versions: &dyn DirectoryVersions,
883    delegate_device: Uuid,
884    max_protocol: &str,
885) -> Result<VerifiedHandOff, DelegationError> {
886    admit_directory(trust, versions)?;
887    let hand_off = HandOff::decode(bytes)?;
888    let header = &hand_off.header;
889    if header.delegate_device != delegate_device {
890        return Err(DelegationError::WrongDelegate {
891            addressed: header.delegate_device,
892        });
893    }
894    if header.protocol_version.as_str() > max_protocol {
895        tracing::info!(
896            bundle = %header.protocol_version,
897            ours = max_protocol,
898            "delegation: refusing a bundle newer than this device speaks"
899        );
900        return Err(DelegationError::ProtocolUnsupported {
901            bundle: header.protocol_version.clone(),
902            ours: max_protocol.to_owned(),
903        });
904    }
905    let origin = admit_device(trust, header.origin_device)?;
906
907    let tampered = |what: String| DelegationError::Tampered(what);
908    // Every member: its bytes are what its request declares, and its request is this bundle's.
909    for (request, blob) in header.members.iter().zip(&hand_off.blobs) {
910        let actual = hash_bytes(blob).to_hex();
911        if actual != request.hash || request.manifest_envelope.ciphertext_hash != request.hash {
912            return Err(tampered(format!(
913                "a {:?} member does not hash to its declared address",
914                request.blob_role
915            )));
916        }
917        if request.protocol_version != header.protocol_version
918            || request.manifest_envelope.protocol_version != header.protocol_version
919        {
920            return Err(tampered("a member declares another protocol".into()));
921        }
922        if request.manifest_envelope.file_id != header.asset_id.to_string()
923            || request.manifest_envelope.created_by_device != header.origin_device.to_string()
924        {
925            return Err(tampered("a member names another asset or device".into()));
926        }
927    }
928
929    let only = |role: BlobRole| {
930        let mut found = header
931            .members
932            .iter()
933            .zip(&hand_off.blobs)
934            .filter(|(request, _)| request.blob_role == role);
935        let first = found.next();
936        if found.next().is_some() {
937            return Err(tampered(format!("more than one {role:?} member")));
938        }
939        Ok(first)
940    };
941    let (_, provenance) =
942        only(BlobRole::Provenance)?.ok_or_else(|| tampered("no provenance member".into()))?;
943    let (_, original) =
944        only(BlobRole::Original)?.ok_or_else(|| tampered("no original member".into()))?;
945    let metadata = only(BlobRole::Metadata)?;
946
947    // The signed manifest: the origin's, verifying under the key its directory entry publishes.
948    let record = ProvenanceRecord::decode(provenance)
949        .map_err(|error| tampered(format!("the provenance member: {error}")))?;
950    // The chain head is the hash of these bytes, so a re-spelling of the same values is not the
951    // record the origin produced: the server would refuse it, and the delegate refuses it first.
952    if cbor::to_canonical_vec(&record).ok().as_deref() != Some(provenance) {
953        return Err(tampered(
954            "the provenance record is not canonically encoded".into(),
955        ));
956    }
957    if record.asset_id != header.asset_id || !record.mirrors_manifest() {
958        return Err(tampered(
959            "the provenance record disagrees with its manifest".into(),
960        ));
961    }
962    let manifest = &record.manifest;
963    let core = &manifest.core;
964    if core.file_id != header.asset_id || core.created_by_device != header.origin_device {
965        return Err(tampered(
966            "the manifest names another asset or device".into(),
967        ));
968    }
969    verify_device_signature(manifest, &trust.directory)
970        .map_err(|reason| tampered(format!("the manifest's signature: {reason:?}")))?;
971
972    // Every member the manifest commits to is the member carried.
973    if core.ciphertext_hash != hash_bytes(original) {
974        return Err(tampered(
975            "the original is not the one the manifest signs".into(),
976        ));
977    }
978    match (core.metadata_blob_hash, metadata) {
979        (Some(signed), Some((_, blob))) if signed == hash_bytes(blob) => {}
980        (None, None) => {}
981        _ => {
982            return Err(tampered(
983                "the metadata blob is not the one the manifest signs".into(),
984            ));
985        }
986    }
987    for request in &header.members {
988        let envelope = &request.manifest_envelope;
989        let agrees = envelope.created_by_user == core.created_by_user.to_string()
990            && envelope.album_id.as_deref() == Some(core.album_id.to_string().as_str())
991            && envelope.amk_version == core.amk_version.0
992            && envelope.timestamp == core.timestamp
993            && envelope.metadata_blob_hash == core.metadata_blob_hash.map(|hash| hash.to_hex())
994            && envelope.prior_provenance_hash
995                == core.prior_provenance_hash.map(|hash| hash.to_hex());
996        if !agrees {
997            return Err(tampered(format!(
998                "a {:?} member's envelope is not the signed manifest's",
999                request.blob_role
1000            )));
1001        }
1002    }
1003
1004    // Derivatives: each derivative manifest is the origin's, for this asset, and each
1005    // derivative is one a derivative manifest signs.
1006    let mut signed_derivatives = BTreeSet::new();
1007    for (request, blob) in header.members.iter().zip(&hand_off.blobs) {
1008        if request.blob_role != BlobRole::DerivativeManifest {
1009            continue;
1010        }
1011        let derivative: DerivativeManifest = cbor::from_slice(blob)
1012            .map_err(|error| tampered(format!("a derivative manifest: {error}")))?;
1013        if cbor::to_canonical_vec(&derivative).ok().as_deref() != Some(blob.as_slice()) {
1014            return Err(tampered(
1015                "a derivative manifest is not canonically encoded".into(),
1016            ));
1017        }
1018        let signed_by_origin = derivative.core.generated_by_device == header.origin_device
1019            && derivative.device_sig.classical_algorithm()
1020                == origin.dsk_public.classical_algorithm()
1021            && origin
1022                .dsk_public
1023                .verify(&derivative.signing_bytes(), &derivative.device_sig);
1024        if derivative.core.source_asset_id != header.asset_id || !signed_by_origin {
1025            return Err(tampered(
1026                "a derivative manifest is not the origin's for this asset".into(),
1027            ));
1028        }
1029        signed_derivatives.insert((derivative.core.ciphertext_hash, derivative.core.format));
1030    }
1031    for (request, blob) in header.members.iter().zip(&hand_off.blobs) {
1032        if request.blob_role == BlobRole::Derivative
1033            && !signed_derivatives.contains(&(hash_bytes(blob), request.content_type.clone()))
1034        {
1035            return Err(tampered("a derivative no derivative manifest signs".into()));
1036        }
1037    }
1038
1039    let address = HandOff::address(bytes);
1040    tracing::info!(
1041        %address,
1042        asset_id = %header.asset_id,
1043        origin = %header.origin_device,
1044        members = header.members.len(),
1045        "delegation: hand-off verified"
1046    );
1047    Ok(VerifiedHandOff { address, hand_off })
1048}
1049
1050/// Why a held hand-off was quarantined, recorded beside its copy when it was.
1051#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1052pub struct Quarantine {
1053    /// The asset the hand-off uploads; nil when its header could not be read.
1054    pub asset_id: Uuid,
1055    /// The caller's stable name for the failure (the CLI's `--json` `kind`).
1056    pub kind: String,
1057    /// The server's stable `error.*` code, when it supplied one.
1058    pub code: Option<String>,
1059    /// The English detail.
1060    pub message: String,
1061}
1062
1063impl Quarantine {
1064    /// The note for a held hand-off of `asset_id` that failed for good with `error`, named
1065    /// `kind`.
1066    #[must_use]
1067    pub fn new(asset_id: Uuid, kind: &str, error: &DelegationError) -> Self {
1068        Self {
1069            asset_id,
1070            kind: kind.to_owned(),
1071            code: error.error_code().map(str::to_owned),
1072            message: error.to_string(),
1073        }
1074    }
1075}
1076
1077/// Where a delegate keeps the hand-offs it accepted until custody is confirmed. Never a library:
1078/// a delegate copy is not an asset of the delegate's.
1079///
1080/// A copy is either **held** (listed by [`addresses`](Self::addresses) and uploaded on every
1081/// run) or **quarantined** (kept byte for byte with its [`Quarantine`] note, never retried, and
1082/// deleted only by [`discard`](Self::discard)).
1083pub trait DelegateInbox: Send + Sync {
1084    /// Persist `bytes` under `address` **durably** — written and synced, its directory entry
1085    /// too — before returning. An acknowledgement follows only after this returns.
1086    fn persist(&self, address: &str, bytes: &[u8]) -> io::Result<()>;
1087    /// The bytes held under `address`.
1088    fn load(&self, address: &str) -> io::Result<Option<Vec<u8>>>;
1089    /// Every address held. A quarantined copy is not held.
1090    fn addresses(&self) -> io::Result<Vec<String>>;
1091    /// Delete the copy under `address`. Removing an absent one is not an error.
1092    fn remove(&self, address: &str) -> io::Result<()>;
1093    /// Move the held copy under `address` to quarantine with `note`, **durably**, keeping its
1094    /// bytes. Quarantining an absent copy is not an error.
1095    fn quarantine(&self, address: &str, note: &Quarantine) -> io::Result<()>;
1096    /// Every quarantined copy's address and note, each once.
1097    fn quarantined(&self) -> io::Result<Vec<(String, Quarantine)>>;
1098    /// The bytes of the quarantined copy under `address`.
1099    fn load_quarantined(&self, address: &str) -> io::Result<Option<Vec<u8>>>;
1100    /// Delete the quarantined copy under `address`, returning its note, or `None` when no copy
1101    /// under `address` is quarantined (a held copy is left alone).
1102    fn discard(&self, address: &str) -> io::Result<Option<Quarantine>>;
1103}
1104
1105/// An in-memory [`DelegateInbox`]: durable for the life of the process.
1106#[derive(Debug, Default)]
1107pub struct MemoryInbox(Mutex<MemoryHeld>);
1108
1109#[derive(Debug, Default)]
1110struct MemoryHeld {
1111    held: BTreeMap<String, Vec<u8>>,
1112    quarantined: BTreeMap<String, (Vec<u8>, Quarantine)>,
1113}
1114
1115impl MemoryInbox {
1116    fn held(&self) -> io::Result<std::sync::MutexGuard<'_, MemoryHeld>> {
1117        self.0
1118            .lock()
1119            .map_err(|_| io::Error::other("the inbox lock is poisoned"))
1120    }
1121}
1122
1123impl DelegateInbox for MemoryInbox {
1124    fn persist(&self, address: &str, bytes: &[u8]) -> io::Result<()> {
1125        self.held()?.held.insert(address.to_owned(), bytes.to_vec());
1126        Ok(())
1127    }
1128
1129    fn load(&self, address: &str) -> io::Result<Option<Vec<u8>>> {
1130        Ok(self.held()?.held.get(address).cloned())
1131    }
1132
1133    fn addresses(&self) -> io::Result<Vec<String>> {
1134        Ok(self.held()?.held.keys().cloned().collect())
1135    }
1136
1137    fn remove(&self, address: &str) -> io::Result<()> {
1138        self.held()?.held.remove(address);
1139        Ok(())
1140    }
1141
1142    fn quarantine(&self, address: &str, note: &Quarantine) -> io::Result<()> {
1143        let mut inbox = self.held()?;
1144        if let Some(bytes) = inbox.held.remove(address) {
1145            inbox
1146                .quarantined
1147                .insert(address.to_owned(), (bytes, note.clone()));
1148        }
1149        Ok(())
1150    }
1151
1152    fn quarantined(&self) -> io::Result<Vec<(String, Quarantine)>> {
1153        Ok(self
1154            .held()?
1155            .quarantined
1156            .iter()
1157            .map(|(address, (_, note))| (address.clone(), note.clone()))
1158            .collect())
1159    }
1160
1161    fn load_quarantined(&self, address: &str) -> io::Result<Option<Vec<u8>>> {
1162        Ok(self
1163            .held()?
1164            .quarantined
1165            .get(address)
1166            .map(|(bytes, _)| bytes.clone()))
1167    }
1168
1169    fn discard(&self, address: &str) -> io::Result<Option<Quarantine>> {
1170        Ok(self
1171            .held()?
1172            .quarantined
1173            .remove(address)
1174            .map(|(_, note)| note))
1175    }
1176}
1177
1178/// Take a hand-off: verify it ([`verify_hand_off`]), persist it durably in `inbox`, and only
1179/// then acknowledge it.
1180///
1181/// # Errors
1182///
1183/// Whatever [`verify_hand_off`] refused, or [`DelegationError::Inbox`] when it could not be
1184/// persisted — in which case there is no acknowledgement and the origin keeps the upload.
1185pub fn accept_hand_off(
1186    bytes: &[u8],
1187    trust: &PinnedTrust,
1188    versions: &dyn DirectoryVersions,
1189    delegate_device: Uuid,
1190    max_protocol: &str,
1191    inbox: &dyn DelegateInbox,
1192) -> Result<(VerifiedHandOff, HandOffAck), DelegationError> {
1193    let verified = verify_hand_off(bytes, trust, versions, delegate_device, max_protocol)?;
1194    persist_and_acknowledge(verified, bytes, delegate_device, inbox)
1195}
1196
1197/// [`accept_hand_off`] for a hand-off pulled over a peering channel from `peer`, the device the
1198/// channel's handshake verified: the hand-off must also have been sealed by that peer, so a
1199/// peer can hand over only its own uploads.
1200///
1201/// # Errors
1202///
1203/// Whatever [`accept_hand_off`] refuses, or [`DelegationError::WrongOrigin`] — checked before
1204/// anything is persisted.
1205pub fn accept_hand_off_from(
1206    bytes: &[u8],
1207    peer: Uuid,
1208    trust: &PinnedTrust,
1209    versions: &dyn DirectoryVersions,
1210    delegate_device: Uuid,
1211    max_protocol: &str,
1212    inbox: &dyn DelegateInbox,
1213) -> Result<(VerifiedHandOff, HandOffAck), DelegationError> {
1214    let verified = verify_hand_off(bytes, trust, versions, delegate_device, max_protocol)?;
1215    let origin = verified.hand_off.header.origin_device;
1216    if origin != peer {
1217        tracing::warn!(%origin, %peer, "delegation: a peer served a hand-off it did not seal");
1218        return Err(DelegationError::WrongOrigin { origin, peer });
1219    }
1220    persist_and_acknowledge(verified, bytes, delegate_device, inbox)
1221}
1222
1223fn persist_and_acknowledge(
1224    verified: VerifiedHandOff,
1225    bytes: &[u8],
1226    delegate_device: Uuid,
1227    inbox: &dyn DelegateInbox,
1228) -> Result<(VerifiedHandOff, HandOffAck), DelegationError> {
1229    inbox
1230        .persist(&verified.address, bytes)
1231        .map_err(|error| DelegationError::Inbox(format!("persist the hand-off: {error}")))?;
1232    let ack = HandOffAck {
1233        asset_id: verified.asset_id(),
1234        hand_off: verified.address.clone(),
1235        delegate_device,
1236    };
1237    tracing::info!(asset_id = %ack.asset_id, hand_off = %ack.hand_off, "delegation: persisted and acknowledged");
1238    Ok((verified, ack))
1239}
1240
1241// ─── Over the peering channel ─────────────────────────────────────────────────
1242
1243/// **The origin's side** of a hand-off over a verified peering channel: offer each sealed
1244/// hand-off to the channel's peer, serve its ranged pulls, and take its acknowledgements,
1245/// authorizing every request against `trust` ([`serve`]).
1246///
1247/// Every hand-off must be sealed for the peer the handshake verified. An acknowledgement must
1248/// name that peer and one of these hand-offs, and the asset it was sealed for, before `on_ack`
1249/// (which records it in the origin ledger) sees it.
1250///
1251/// # Errors
1252///
1253/// [`DelegationError::WrongDelegate`] for a hand-off sealed for another device (nothing is sent),
1254/// or the [`PeeringError`] that ended the session.
1255#[instrument(skip_all, fields(peer = %channel.peer().device_id, hand_offs = sealed.len()))]
1256pub async fn offer_hand_offs<T, F>(
1257    channel: &mut PeerChannel,
1258    sealed: &[SealedHandOff],
1259    trust: &T,
1260    versions: &dyn DirectoryVersions,
1261    mut on_ack: F,
1262) -> Result<ServeReport, DelegationError>
1263where
1264    T: TrustSource,
1265    F: FnMut(&HandOffAck) -> Result<(), DelegationError> + Send,
1266{
1267    let peer = channel.peer().device_id;
1268    let mut offering = Offering::new();
1269    let mut assets = BTreeMap::new();
1270    for hand_off in sealed {
1271        if hand_off.delegate != peer {
1272            return Err(DelegationError::WrongDelegate {
1273                addressed: hand_off.delegate,
1274            });
1275        }
1276        // A reference-count bump: the offering shares the sealed bytes.
1277        let address = offering.offer(hand_off.bytes.clone())?;
1278        assets.insert(address, hand_off.asset_id);
1279    }
1280    let report = serve(channel, &offering, trust, versions, |ack| {
1281        if assets.get(&ack.hand_off) != Some(&ack.asset_id) {
1282            return Err(DelegationError::AckMismatch);
1283        }
1284        on_ack(ack)
1285    })
1286    .await?;
1287    Ok(report)
1288}
1289
1290/// What became of one hand-off a peer offered.
1291#[derive(Debug)]
1292pub struct TakenHandOff {
1293    /// The hand-off's content address, as offered.
1294    pub address: String,
1295    /// The acknowledgement, when the hand-off verified and was persisted durably: the delegate
1296    /// holds it and uploads it, whether or not the origin took the acknowledgement.
1297    pub ack: Option<HandOffAck>,
1298    /// Why it was not taken (`ack` is `None`), or why its acknowledgement did not reach the
1299    /// origin (`ack` is `Some`).
1300    pub error: Option<DelegationError>,
1301}
1302
1303/// What one session of [`take_hand_offs`] did.
1304#[derive(Debug, Default)]
1305pub struct TakenHandOffs {
1306    /// Each offered hand-off this session reached, in listing order.
1307    pub taken: Vec<TakenHandOff>,
1308    /// Whether the channel failed before every offered hand-off was reached: the partial pulls
1309    /// are kept, and a later session with the same origin resumes them.
1310    pub severed: bool,
1311}
1312
1313/// **The delegate's side** of a hand-off over a verified peering channel: pull each hand-off the
1314/// peer offers, verify it ([`accept_hand_off_from`], so it must be the verified peer's own),
1315/// persist it durably, and only then acknowledge it over the same channel.
1316///
1317/// `partials` holds the bytes of pulls an earlier session lost with its channel, by address: a
1318/// pull resumes after them and re-fetches none of them, and a pull severed now leaves what it
1319/// received there. A hand-off the inbox already holds (taken in an earlier session whose
1320/// acknowledgement was lost) is re-verified from the inbox and acknowledged again, not pulled.
1321///
1322/// The session ends with [`PeerClient::finish`] unless the channel broke or the peer refused a
1323/// request, which ends it on the peer's side.
1324#[allow(clippy::too_many_arguments)]
1325#[instrument(skip_all, fields(peer = %client.peer().device_id, offered = client.listing().len()))]
1326pub async fn take_hand_offs(
1327    client: &PeerClient,
1328    trust: &PinnedTrust,
1329    versions: &dyn DirectoryVersions,
1330    delegate_device: Uuid,
1331    max_protocol: &str,
1332    inbox: &dyn DelegateInbox,
1333    partials: &mut BTreeMap<String, Vec<u8>>,
1334) -> TakenHandOffs {
1335    let peer = client.peer().device_id;
1336    let mut outcome = TakenHandOffs::default();
1337    let mut ended = false;
1338    for offered in client.listing() {
1339        let address = offered.address.clone();
1340        let held = match inbox.load(&address) {
1341            Ok(held) => held,
1342            Err(error) => {
1343                outcome.taken.push(TakenHandOff {
1344                    address,
1345                    ack: None,
1346                    error: Some(DelegationError::Inbox(format!("read the inbox: {error}"))),
1347                });
1348                continue;
1349            }
1350        };
1351        let bytes = if let Some(bytes) = held {
1352            bytes
1353        } else {
1354            let mut partial = partials.remove(&address).unwrap_or_default();
1355            match pull_over_channel(client, &address, offered.len, &mut partial).await {
1356                Ok(bytes) => bytes,
1357                Err(error) => {
1358                    if !partial.is_empty() {
1359                        partials.insert(address.clone(), partial);
1360                    }
1361                    let refused = matches!(error, PeeringError::PeerRefused { .. });
1362                    outcome.taken.push(TakenHandOff {
1363                        address,
1364                        ack: None,
1365                        error: Some(error.into()),
1366                    });
1367                    if client.is_broken() {
1368                        outcome.severed = true;
1369                        ended = true;
1370                        break;
1371                    }
1372                    if refused {
1373                        ended = true;
1374                        break;
1375                    }
1376                    continue;
1377                }
1378            }
1379        };
1380        let accepted = accept_hand_off_from(
1381            &bytes,
1382            peer,
1383            trust,
1384            versions,
1385            delegate_device,
1386            max_protocol,
1387            inbox,
1388        );
1389        let ack = match accepted {
1390            Ok((_, ack)) => ack,
1391            Err(error) => {
1392                tracing::warn!(%address, %error, "delegation: an offered hand-off was refused");
1393                outcome.taken.push(TakenHandOff {
1394                    address,
1395                    ack: None,
1396                    error: Some(error),
1397                });
1398                continue;
1399            }
1400        };
1401        // A refused acknowledgement is the origin's verdict on that one hand-off, and the
1402        // session goes on; a broken channel ends it.
1403        let delivered = client.acknowledge(&ack).await;
1404        outcome.taken.push(TakenHandOff {
1405            address,
1406            ack: Some(ack),
1407            error: delivered.err().map(DelegationError::from),
1408        });
1409        if client.is_broken() {
1410            outcome.severed = true;
1411            ended = true;
1412            break;
1413        }
1414    }
1415    if !ended && let Err(error) = client.finish().await {
1416        tracing::debug!(%error, "delegation: could not end the session cleanly");
1417    }
1418    tracing::info!(
1419        taken = outcome.taken.iter().filter(|t| t.ack.is_some()).count(),
1420        offered = client.listing().len(),
1421        severed = outcome.severed,
1422        "delegation: hand-off session over"
1423    );
1424    outcome
1425}
1426
1427/// What [`upload_hand_off`] did.
1428#[derive(Debug, Clone, Default, PartialEq, Eq)]
1429pub struct DelegatedUpload {
1430    /// The members whose sessions this run drove, with how each resolved: `true` when the
1431    /// server already held the bytes (a merge), `false` when they were transferred.
1432    pub pushed: Vec<(String, bool)>,
1433    /// The members the delegate's own policy deferred to a later window.
1434    pub deferred: Vec<String>,
1435}
1436
1437/// Upload a verified hand-off under the delegate's own session, in the order the delegate's own
1438/// `scheduler` permits — its battery and metering policy, not the origin's. Each member's
1439/// request is sent exactly as the origin built it.
1440///
1441/// # Errors
1442///
1443/// [`DelegationError::Upload`] for a member the server refused or a transfer that failed.
1444#[instrument(skip_all, fields(asset_id = %hand_off.asset_id(), hand_off = %hand_off.address))]
1445pub async fn upload_hand_off(
1446    client: &UploadClient,
1447    scheduler: &StagedScheduler,
1448    hand_off: &VerifiedHandOff,
1449) -> Result<DelegatedUpload, DelegationError> {
1450    let staged = StagedAsset::new(
1451        hand_off.asset_id().to_string(),
1452        hand_off
1453            .members()
1454            .map(|(request, _)| {
1455                TierBlob::new(tier_of(request.blob_role), &request.hash, request.size)
1456            })
1457            .collect(),
1458    );
1459    let planned = scheduler.plan_sessions(&staged);
1460    let mut report = DelegatedUpload {
1461        deferred: staged
1462            .blobs
1463            .iter()
1464            .filter(|blob| !planned.iter().any(|p| p.hash == blob.hash))
1465            .map(|blob| blob.hash.clone())
1466            .collect(),
1467        ..DelegatedUpload::default()
1468    };
1469    for tier_blob in planned {
1470        let Some((request, bytes)) = hand_off
1471            .members()
1472            .find(|(request, _)| request.hash == tier_blob.hash)
1473        else {
1474            continue;
1475        };
1476        tracing::info!(role = ?request.blob_role, hash = %request.hash, "delegation: uploading a member");
1477        let merged = match client.upload(request, &bytes).await? {
1478            UploadOutcome::Completed { .. } => false,
1479            UploadOutcome::AlreadyStored { .. } => true,
1480        };
1481        report.pushed.push((request.hash.clone(), merged));
1482    }
1483    tracing::info!(
1484        pushed = report.pushed.len(),
1485        deferred = report.deferred.len(),
1486        "delegation: upload run done"
1487    );
1488    Ok(report)
1489}
1490
1491/// What [`settle`] did with the delegate's copy.
1492#[derive(Debug, Clone, PartialEq, Eq)]
1493pub enum Settled {
1494    /// Custody of every member is confirmed: the copy is deleted.
1495    Removed,
1496    /// Not yet: the copy is kept and the upload is retried later.
1497    Kept(RetainReason),
1498}
1499
1500/// Delete the delegate's copy of `hand_off` once the server holds every member it can receipt,
1501/// by custody facts the delegate fetched with its own session through `coordinator`. Deferred
1502/// members (`deferred` non-empty) keep the copy.
1503///
1504/// # Errors
1505///
1506/// [`DelegationError::Inbox`] when the copy could not be deleted.
1507pub async fn settle<C: ReleaseClock>(
1508    coordinator: &ReleaseCoordinator<C>,
1509    hand_off: &VerifiedHandOff,
1510    deferred: &[String],
1511    inbox: &dyn DelegateInbox,
1512) -> Result<Settled, DelegationError> {
1513    if !deferred.is_empty() {
1514        return Ok(Settled::Kept(RetainReason::NotDurable));
1515    }
1516    let held = hand_off.held_release();
1517    let hashes: Vec<Hash32> = held.blobs.iter().map(|b| b.ciphertext_hash).collect();
1518    let verifier = coordinator
1519        .resolve_custody(std::slice::from_ref(&held))
1520        .await;
1521    // The delegate cannot run `verify_asset` (it holds no album key); what it verified is the
1522    // manifest's device signature and every member's hash, which `verify_hand_off` required.
1523    match ReleaseGate::new(&verifier).may_release(hand_off.asset_id(), &hashes, true) {
1524        ReleaseDecision::Release => {
1525            inbox
1526                .remove(&hand_off.address)
1527                .map_err(|error| DelegationError::Inbox(format!("delete the copy: {error}")))?;
1528            tracing::info!(asset_id = %hand_off.asset_id(), "delegation: custody confirmed; delegate copy deleted");
1529            Ok(Settled::Removed)
1530        }
1531        ReleaseDecision::Retain(reason) => {
1532            tracing::info!(asset_id = %hand_off.asset_id(), ?reason, "delegation: copy kept until custody");
1533            Ok(Settled::Kept(reason))
1534        }
1535    }
1536}
1537
1538/// What [`dispose_failure`] did with a held hand-off a run could not deliver.
1539#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1540pub enum HeldFailure {
1541    /// The failure is transient: the copy stays for the next run.
1542    Kept,
1543    /// The failure is permanent ([`DelegationError::is_permanent`]): the copy is quarantined,
1544    /// its bytes kept, and no later run retries it.
1545    Quarantined,
1546}
1547
1548/// Decide the fate of the hand-off of `asset_id` held under `address` after `error`: a
1549/// permanent refusal quarantines the delegate's copy under a [`Quarantine`] note naming `kind`,
1550/// so it neither fails every later run nor is lost; a transient one keeps it held.
1551///
1552/// The copy is never deleted here. A revoked origin is often a lost device whose original is
1553/// gone, and a refused bundle may be the account's only copy of the asset; only the user deletes
1554/// a quarantined copy ([`DelegateInbox::discard`]).
1555///
1556/// # Errors
1557///
1558/// [`DelegationError::Inbox`] when a permanently refused copy could not be quarantined; it then
1559/// stays held and is tried again.
1560#[instrument(skip_all, fields(hand_off = %address, %asset_id, permanent = error.is_permanent()))]
1561pub fn dispose_failure(
1562    inbox: &dyn DelegateInbox,
1563    address: &str,
1564    asset_id: Uuid,
1565    kind: &str,
1566    error: &DelegationError,
1567) -> Result<HeldFailure, DelegationError> {
1568    if !error.is_permanent() {
1569        tracing::info!(%error, "delegation: transient failure; the copy is kept");
1570        return Ok(HeldFailure::Kept);
1571    }
1572    inbox
1573        .quarantine(address, &Quarantine::new(asset_id, kind, error))
1574        .map_err(|io| DelegationError::Inbox(format!("quarantine the copy: {io}")))?;
1575    tracing::warn!(%error, kind, "delegation: permanently refused; the copy is quarantined");
1576    Ok(HeldFailure::Quarantined)
1577}
1578
1579#[cfg(test)]
1580mod tests;