Skip to main content

capsule_sdk/peering/
transfer.rs

1//! What moves over the wire, and how it is applied.
2//!
3//! The transfer payload is a **delta-scoped [backup artifact]** — backup artifacts are
4//! explicitly *"constructed from a list of assets, albums, and so on,"* so a delta-scoped one
5//! needs no special construction path ([`build_delta_artifact`]). It is fetched with ranged
6//! `GET` ([`pull_artifact`] over the shared [`RangedFetcher`]), which makes the transfer
7//! **resumable** across the flaky-by-nature LAN and **idempotent** — content-addressing turns a
8//! re-fetch of an already-held blob into a no-op.
9//!
10//! A received artifact is ingested through the **backup restore path** ([`ingest`]) — peering
11//! adds no separate deserialization. Restore re-verifies every ciphertext hash, checks STREAM
12//! tags on decrypt, and runs each manifest through `verify_asset`. Peering adds on top:
13//!
14//! - **Chain-aware forward-vs-stale reconciliation.** A peer pull cannot resurrect an asset the
15//!   local device has already superseded — even if the artifact was honestly produced from an
16//!   older state of the sender. Such an asset is **quarantined**, never silently applied.
17//! - **No resurrection.** An asset the device holds a tombstone for (kept past purge) is refused.
18//! - **All-or-nothing per asset.** Each asset restores on its own: one that fails to decrypt, or
19//!   arrives without the metadata its manifest commits to, is not applied, and does not stop the
20//!   rest.
21//!
22//! The artifact is sealed under the session's [`ArtifactSecret`], derived from the channel's TLS
23//! exporter — never a user passphrase.
24//!
25//! Over a verified peering channel the ranged pull runs through [`ChannelBlobSource`]
26//! ([`pull_over_channel`]): the same fetch engine, the same content-address check, and a pull
27//! severed with the channel resumes on the next channel after the bytes it already holds.
28//!
29//! [backup artifact]: https://docs/design/backup-recovery/#backup-artifact
30
31use std::collections::{BTreeMap, BTreeSet};
32use std::sync::{Arc, Mutex, PoisonError};
33
34use capsule_core::backup::{
35    BackupArtifact, BackupAsset, BackupInput, RestoreMode, RestoredAsset, export,
36};
37use capsule_core::crypto::hash::{Hash32, hash_bytes};
38use capsule_core::crypto::keys::{HybridVerifyingKey, Signer};
39use tracing::instrument;
40use uuid::Uuid;
41
42use super::PeeringError;
43use super::channel::{ArtifactSecret, MAX_ARTIFACT_LEN, PeerClient, RangeFailure};
44use crate::fetch::{
45    BlobSource, FetchError, FetchScope, RangeOutcome, RangedFetcher, Representation,
46};
47use crate::net::ConnectionClass;
48
49/// The ciphertext content address of a backup asset — the head manifest's `ciphertext_hash`,
50/// which is what a delta is expressed over.
51fn asset_address(asset: &BackupAsset) -> Option<Hash32> {
52    asset
53        .provenance
54        .last()
55        .map(|record| record.manifest.core.ciphertext_hash)
56}
57
58/// Everything needed to assemble a delta-scoped artifact on the sending device.
59pub struct DeltaExport<'a> {
60    /// The sender's full candidate asset set (only those in `delta` are included).
61    pub assets: &'a [BackupAsset],
62    /// The content addresses the receiver is missing — the delta to include.
63    pub delta: &'a BTreeSet<Hash32>,
64    /// The receiver's synchronization scope. A backup artifact always carries each asset's
65    /// original, so only a receiver that eagerly holds originals can take one.
66    pub scope: FetchScope,
67    /// The AMKs for every `(album, epoch)` an included asset references.
68    pub amks: &'a BTreeMap<(Uuid, u32), [u8; 32]>,
69    /// The exporting device id (provenance: who produced the artifact).
70    pub exporter_device: Uuid,
71    /// The sender's library version string.
72    pub source_library_version: String,
73    /// RFC 3339 export timestamp.
74    pub export_timestamp: String,
75}
76
77/// Build a delta-scoped backup artifact: include exactly the sender's assets whose content
78/// address is in `delta`, then export through the ordinary backup path. Assets the receiver
79/// already holds are never in `delta`, so they never enter the artifact — the "only missing
80/// assets transfer" guarantee is structural, decided before a single byte is sealed.
81///
82/// The receiver's scope is honoured: a receiver whose scope does not eagerly hold originals is
83/// refused with [`PeeringError::OutOfScope`] rather than sent bytes it would not keep; it syncs
84/// from the server, where its scope is served representation by representation.
85#[instrument(skip(export_input, secret, signer), fields(delta = export_input.delta.len()))]
86pub fn build_delta_artifact(
87    export_input: &DeltaExport<'_>,
88    secret: &ArtifactSecret,
89    signer: &dyn Signer,
90) -> Result<Vec<u8>, PeeringError> {
91    if !export_input
92        .scope
93        .eager_representations()
94        .contains(&Representation::Original)
95    {
96        tracing::debug!(scope = ?export_input.scope, "receiver scope excludes originals");
97        return Err(PeeringError::OutOfScope(export_input.scope));
98    }
99    let assets: Vec<BackupAsset> = export_input
100        .assets
101        .iter()
102        .filter(|asset| asset_address(asset).is_some_and(|addr| export_input.delta.contains(&addr)))
103        .cloned()
104        .collect();
105    tracing::debug!(
106        included = assets.len(),
107        candidates = export_input.assets.len(),
108        "assembled delta-scoped backup artifact"
109    );
110    let input = BackupInput {
111        assets,
112        amks: export_input.amks.clone(),
113        // A peer pull moves assets between devices that already hold the album and its
114        // authority; `ingest` folds in no keys, so the delta carries no authority ledger.
115        authorities: BTreeMap::new(),
116        // Label records travel the sealed-document path between members, not the asset delta.
117        docs: Vec::new(),
118        // The pinned attestation-key history is the library's, not an asset's: it rides a
119        // backup of the whole library, never a peer's asset delta.
120        attestation_key_pins: Vec::new(),
121        exporter_device: export_input.exporter_device,
122        source_library_version: export_input.source_library_version.clone(),
123        export_timestamp: export_input.export_timestamp.clone(),
124    };
125    Ok(export(&input, secret.as_bytes(), signer)?)
126}
127
128/// The content address (SHA-256 hex) of an assembled artifact, for the ranged-GET integrity
129/// check. Byte-identical to the media server's `/blob/{hash}` addressing.
130#[must_use]
131pub fn artifact_address(bytes: &[u8]) -> String {
132    hash_bytes(bytes).to_hex()
133}
134
135/// Pull an artifact over ranged `GET`, reusing the adverse-hardened [`RangedFetcher`]. Each
136/// request resumes from the current buffer length, so an interruption re-fetches **zero** bytes
137/// already held, and the reassembled bytes must hash to `artifact_hash` or the transfer fails —
138/// the same resumability and content-address verification the server download path relies on.
139#[instrument(skip(source), fields(len))]
140pub async fn pull_artifact<B: BlobSource>(
141    source: &B,
142    artifact_hash: &str,
143    len: u64,
144) -> Result<Vec<u8>, PeeringError> {
145    RangedFetcher::new(ConnectionClass::Unmetered)
146        .fetch(source, artifact_hash, len)
147        .await
148        .map_err(|e| PeeringError::Transfer(e.to_string()))
149}
150
151/// The receiving device's state an ingest reconciles against.
152#[derive(Debug, Clone, Copy)]
153pub struct LocalLibrary<'a> {
154    /// Each held asset's current provenance head (`asset_id -> head record hash`).
155    pub heads: &'a BTreeMap<Uuid, Hash32>,
156    /// Every asset this device has tombstoned, kept past purge: never resurrected by a peer.
157    pub tombstones: &'a BTreeSet<Uuid>,
158}
159
160/// The outcome of ingesting a peered artifact: every asset the artifact carried lands in exactly
161/// one bucket.
162#[derive(Debug, Default)]
163pub struct PeerRestore {
164    /// Decrypted, verified, complete assets to write — new assets and **forward** updates the
165    /// local head is an ancestor of.
166    pub applied: Vec<RestoredAsset>,
167    /// Assets whose artifact head the local device has already superseded (or diverged from):
168    /// **quarantined**, never applied — "peer sent stale state".
169    pub quarantined: Vec<Uuid>,
170    /// Assets already at the artifact's head locally — a no-op.
171    pub identical: Vec<Uuid>,
172    /// Assets this device holds a tombstone for: refused, never resurrected.
173    pub tombstoned: Vec<Uuid>,
174    /// Assets that failed to restore or arrived without the metadata their manifest commits
175    /// to: not applied, in whole.
176    pub incomplete: Vec<Uuid>,
177}
178
179/// Ingest a peered artifact through the backup restore path with chain-aware reconciliation.
180///
181/// For each asset the artifact carries, relative to `local`:
182/// - **tombstoned locally** → refused, whatever its chain says;
183/// - **absent locally** → applied (a new asset);
184/// - **head identical** → no-op;
185/// - **head differs, artifact chain contains our head as an ancestor** → a *forward* update, so
186///   we adopt it (applied);
187/// - **head differs otherwise** → the artifact is stale or divergent; **quarantined**, never
188///   applied, so a peer can never resurrect a locally-superseded asset.
189///
190/// Each asset to apply restores on its own through [`BackupArtifact::restore`] in `Commit` mode
191/// (which decrypts and re-verifies), so it applies whole or not at all: a restore failure, or a
192/// metadata blob that is missing or does not match the hash its manifest commits to, lands it in
193/// [`PeerRestore::incomplete`] without touching the others.
194#[instrument(skip_all, fields(bytes = artifact_bytes.len()))]
195pub fn ingest(
196    artifact_bytes: &[u8],
197    secret: &ArtifactSecret,
198    exporter_pub: &HybridVerifyingKey,
199    local: LocalLibrary<'_>,
200) -> Result<PeerRestore, PeeringError> {
201    let artifact = BackupArtifact::open(artifact_bytes, secret.as_bytes(), exporter_pub)?;
202    let mut outcome = PeerRestore::default();
203    let mut to_apply = Vec::new();
204
205    for (asset_id, artifact_head) in artifact.provenance_heads() {
206        if local.tombstones.contains(asset_id) {
207            tracing::warn!(asset = %asset_id, "peer offered a tombstoned asset; refusing");
208            outcome.tombstoned.push(*asset_id);
209            continue;
210        }
211        match local.heads.get(asset_id) {
212            None => to_apply.push(*asset_id),
213            Some(head) if head == artifact_head => outcome.identical.push(*asset_id),
214            Some(head) => {
215                let chain = artifact.provenance_chain(asset_id)?.unwrap_or_default();
216                if chain.iter().any(|record| record.record_hash() == *head) {
217                    to_apply.push(*asset_id);
218                } else {
219                    tracing::warn!(asset = %asset_id, "peer sent stale state; quarantining");
220                    outcome.quarantined.push(*asset_id);
221                }
222            }
223        }
224    }
225
226    // A head map under which every carried asset reads as identical, so a restore against it
227    // with one asset's entry removed applies exactly that asset.
228    let mut isolate: BTreeMap<Uuid, Hash32> = artifact.provenance_heads().iter().copied().collect();
229    for asset_id in to_apply {
230        let held = isolate.remove(&asset_id);
231        let restored = artifact
232            .restore(RestoreMode::Commit, &isolate)
233            .map(|report| report.applied);
234        if let Some(head) = held {
235            isolate.insert(asset_id, head);
236        }
237        match restored {
238            Ok(mut applied) if applied.len() == 1 && carries_committed_metadata(&applied[0]) => {
239                outcome.applied.append(&mut applied);
240            }
241            Ok(_) => {
242                tracing::warn!(asset = %asset_id, "peer sent a partial asset; not applying it");
243                outcome.incomplete.push(asset_id);
244            }
245            Err(error) => {
246                tracing::warn!(asset = %asset_id, %error, "peer asset failed to restore");
247                outcome.incomplete.push(asset_id);
248            }
249        }
250    }
251    tracing::debug!(
252        applied = outcome.applied.len(),
253        quarantined = outcome.quarantined.len(),
254        identical = outcome.identical.len(),
255        tombstoned = outcome.tombstoned.len(),
256        incomplete = outcome.incomplete.len(),
257        "peer artifact ingested"
258    );
259    Ok(outcome)
260}
261
262/// Whether a restored asset carries the metadata its chain requires: the exact blob the newest
263/// metadata-bearing manifest commits to, or — for a chain that commits to none — a non-empty one.
264fn carries_committed_metadata(asset: &RestoredAsset) -> bool {
265    let committed = asset
266        .provenance
267        .iter()
268        .rev()
269        .find_map(|record| record.manifest.core.metadata_blob_hash);
270    match committed {
271        Some(hash) => hash_bytes(&asset.metadata_blob) == hash,
272        None => !asset.metadata_blob.is_empty(),
273    }
274}
275
276// ── Over the peering channel ─────────────────────────────────────────────────
277
278/// A [`BlobSource`] over a verified peering channel ([`PeerClient`]), resuming after `held`: the
279/// bytes of the artifact this device already holds from an earlier, severed pull. A range inside
280/// `held` is answered locally; only the bytes after it cross the channel, so a resumed pull
281/// re-fetches nothing it already holds. Every byte that arrives is appended to `held`, so a pull
282/// severed again keeps what it got.
283pub struct ChannelBlobSource<'a> {
284    client: &'a PeerClient,
285    held: Mutex<Vec<u8>>,
286    failure: Mutex<Option<PeeringError>>,
287}
288
289impl<'a> ChannelBlobSource<'a> {
290    /// A source over `client` that already holds `held`, the artifact's first bytes.
291    #[must_use]
292    pub fn resuming(client: &'a PeerClient, held: Vec<u8>) -> Self {
293        Self {
294            client,
295            held: Mutex::new(held),
296            failure: Mutex::new(None),
297        }
298    }
299
300    /// The bytes held so far, and the first channel failure, the one that stopped the pull, if
301    /// one did.
302    #[must_use]
303    pub fn into_parts(self) -> (Vec<u8>, Option<PeeringError>) {
304        (
305            self.held
306                .into_inner()
307                .unwrap_or_else(PoisonError::into_inner),
308            self.failure
309                .into_inner()
310                .unwrap_or_else(PoisonError::into_inner),
311        )
312    }
313
314    fn held(&self) -> std::sync::MutexGuard<'_, Vec<u8>> {
315        self.held.lock().unwrap_or_else(PoisonError::into_inner)
316    }
317}
318
319impl BlobSource for ChannelBlobSource<'_> {
320    async fn get_range(&self, hash: &str, start: u64, max_len: Option<u64>) -> RangeOutcome {
321        {
322            let held = self.held();
323            let held_len = held.len() as u64;
324            if start < held_len {
325                let end = max_len.map_or(held_len, |max| held_len.min(start.saturating_add(max)));
326                return RangeOutcome::Partial {
327                    bytes: held[start as usize..end as usize].to_vec(),
328                };
329            }
330            if start > held_len {
331                // The fetch resumes from what it received, which is what is held; a gap would
332                // be a bug, and is refused rather than papered over.
333                return RangeOutcome::Status {
334                    status: 0,
335                    code: None,
336                };
337            }
338        }
339        match self.client.range(hash, start, max_len).await {
340            Ok(bytes) => {
341                self.held().extend_from_slice(&bytes);
342                RangeOutcome::Complete { bytes }
343            }
344            Err(RangeFailure { received, error }) => {
345                tracing::debug!(%error, received = received.len(), "peering: a ranged pull broke off");
346                self.held().extend_from_slice(&received);
347                // The first failure is the diagnosis: once the channel breaks, every later call
348                // fails with a generic "broke earlier" that must not replace it.
349                self.failure
350                    .lock()
351                    .unwrap_or_else(PoisonError::into_inner)
352                    .get_or_insert(error);
353                if received.is_empty() {
354                    RangeOutcome::Status {
355                        status: 0,
356                        code: None,
357                    }
358                } else {
359                    RangeOutcome::Partial { bytes: received }
360                }
361            }
362        }
363    }
364}
365
366/// Pull the artifact `address` (`len` bytes) from the serving peer over `client`, through the
367/// same resumable, content-address-verified ranged fetch as [`pull_artifact`].
368///
369/// `held` is what an earlier, severed pull of the same artifact received (empty for a fresh
370/// pull): the pull resumes after it and **re-fetches none of it**. On success the whole verified
371/// artifact is returned and `held` is left empty; when the channel fails, `held` keeps every
372/// byte received so far for the next attempt; when the bytes do not hash to `address`, `held`
373/// is cleared, since some of it is wrong.
374///
375/// # Errors
376///
377/// The channel's failure ([`PeeringError::PeerRefused`], [`PeeringError::Io`],
378/// [`PeeringError::Timeout`], …), [`PeeringError::Codec`] for a length past
379/// [`MAX_ARTIFACT_LEN`], or [`PeeringError::Transfer`] when the bytes do not verify.
380#[instrument(skip(client, held), fields(peer = %client.peer().device_id, held = held.len()))]
381pub async fn pull_over_channel(
382    client: &PeerClient,
383    address: &str,
384    len: u64,
385    held: &mut Vec<u8>,
386) -> Result<Vec<u8>, PeeringError> {
387    if len > MAX_ARTIFACT_LEN {
388        return Err(PeeringError::Codec(
389            "the artifact exceeds the pull ceiling".into(),
390        ));
391    }
392    if held.len() as u64 > len {
393        held.clear();
394    }
395    let source = ChannelBlobSource::resuming(client, std::mem::take(held));
396    // The fetch hashes every byte as it passes; the source keeps them, so the sink keeps none.
397    let fetched = RangedFetcher::new(ConnectionClass::Unmetered)
398        .fetch_into(&source, address, len, &mut std::io::sink())
399        .await;
400    let (bytes, failure) = source.into_parts();
401    match fetched {
402        Ok(_) => {
403            tracing::info!(address, len, "peering: artifact pulled and verified");
404            Ok(bytes)
405        }
406        Err(FetchError::IntegrityFailed { .. }) => {
407            tracing::warn!(address, "peering: pulled bytes do not hash to the address");
408            Err(PeeringError::Transfer(format!(
409                "the pulled artifact does not hash to {address}"
410            )))
411        }
412        Err(error) => {
413            *held = bytes;
414            Err(failure.unwrap_or_else(|| PeeringError::Transfer(error.to_string())))
415        }
416    }
417}
418
419// ── In-memory ranged source ───────────────────────────────────────────────────
420
421/// An in-memory [`BlobSource`] that serves an artifact's bytes over `Range` requests — the
422/// deterministic stand-in for the peering channel's ranged `GET`. It records every served range
423/// (so a test can prove **zero duplicate bytes** on resume) and can inject a single mid-transfer
424/// **LAN drop** (a short read) to exercise the resume path.
425#[derive(Clone)]
426pub struct ArtifactBlobSource {
427    bytes: Arc<Vec<u8>>,
428    served: Arc<Mutex<Vec<(u64, u64)>>>,
429    drop_after: Arc<Mutex<Option<u64>>>,
430}
431
432impl ArtifactBlobSource {
433    /// Serve `bytes` with no injected drop.
434    #[must_use]
435    pub fn new(bytes: Vec<u8>) -> Self {
436        Self {
437            bytes: Arc::new(bytes),
438            served: Arc::new(Mutex::new(Vec::new())),
439            drop_after: Arc::new(Mutex::new(None)),
440        }
441    }
442
443    /// Serve `bytes`, but truncate the **first** ranged response to `drop_after` bytes to
444    /// simulate a LAN drop mid-transfer. The next request resumes from the persisted offset.
445    #[must_use]
446    pub fn with_drop_after(bytes: Vec<u8>, drop_after: u64) -> Self {
447        Self {
448            bytes: Arc::new(bytes),
449            served: Arc::new(Mutex::new(Vec::new())),
450            drop_after: Arc::new(Mutex::new(Some(drop_after))),
451        }
452    }
453
454    /// The total artifact length.
455    #[must_use]
456    pub fn len(&self) -> u64 {
457        self.bytes.len() as u64
458    }
459
460    /// Whether the artifact is empty.
461    #[must_use]
462    pub fn is_empty(&self) -> bool {
463        self.bytes.is_empty()
464    }
465
466    /// The `(start, len)` of every range served so far, in order.
467    #[must_use]
468    pub fn served_ranges(&self) -> Vec<(u64, u64)> {
469        self.served.lock().map(|g| g.clone()).unwrap_or_default()
470    }
471}
472
473impl BlobSource for ArtifactBlobSource {
474    async fn get_range(&self, _hash: &str, start: u64, max_len: Option<u64>) -> RangeOutcome {
475        let total = self.bytes.len() as u64;
476        if start >= total {
477            return RangeOutcome::Complete { bytes: Vec::new() };
478        }
479        let remaining = total - start;
480        let mut give = max_len.map_or(remaining, |m| m.min(remaining));
481
482        // Inject a one-time short read (a LAN drop) if configured.
483        let mut partial = false;
484        if let Ok(mut guard) = self.drop_after.lock()
485            && let Some(n) = guard.take()
486            && n < give
487        {
488            give = n;
489            partial = true;
490        }
491
492        let end = start + give;
493        let slice = self.bytes[start as usize..end as usize].to_vec();
494        if let Ok(mut guard) = self.served.lock() {
495            guard.push((start, give));
496        }
497
498        if partial {
499            RangeOutcome::Partial { bytes: slice }
500        } else {
501            RangeOutcome::Complete { bytes: slice }
502        }
503    }
504}