Skip to main content

capsule_core/backup/
artifact.rs

1//! The backup artifact: a deterministic, self-describing, signed tar container
2//! (SSoT: [Backup — Backup Artifact]).
3//!
4//! Layout (entries after the header are sorted by `(album_id, asset_id, blob_role)`):
5//! ```text
6//! VERSION                 # plaintext: format version, crypto_suite_id, wrap salt + params
7//! MANIFEST.cbor           # entry list/hashes + provenance heads; HMAC + hybrid exporter sig
8//! keys/amk-ledger.cbor    # the AMKs needed, sealed under the passphrase-derived wrap key
9//! blobs/{ciphertext_hash} # encrypted asset ciphertext
10//! meta/{asset_id}         # encrypted metadata blob
11//! create-meta/{asset_id}  # encrypted metadata blob the create binds, when an edit superseded it
12//! provenance/{asset_id}   # the full per-asset provenance chain (canonical CBOR)
13//! receipts/{asset_id}     # the asset's custody-receipt log, verbatim (when held)
14//! attestations/{asset_id} # the asset's signed storage-attestation log, verbatim (when held)
15//! authority/{album_id}    # the album's admin-signed epoch ledger (public; canonical CBOR)
16//! library/attestation-keys.cbor # the library's pinned attestation-key history, verbatim (when held)
17//! ```
18//!
19//! The `authority/` entries (format version 2) carry each album's **public** authority — the
20//! admin verifying key and the admin-signed epoch ledger a manifest's write signature is checked
21//! against — so a restored asset verifies, not merely decrypts. No signing seed rides the
22//! artifact: a restored album stays read-only.
23//!
24//! The MANIFEST is authenticated **two ways**: an HMAC under the wrap key (catches
25//! tamper/truncation before any decrypt) and a hybrid exporter signature (defeats a
26//! wrap-key thief who could otherwise re-HMAC). Restore is a **chain reconciliation**, never
27//! a blind overwrite, and **dry-run is the default**.
28//!
29//! [Backup — Backup Artifact]: https://docs/design/backup-recovery/#backup-artifact
30
31use std::borrow::Cow;
32use std::collections::{BTreeMap, BTreeSet};
33use std::io::{self, Read, Write};
34use std::sync::Arc;
35
36use hmac::{Hmac, KeyInit as _, Mac};
37use serde::{Deserialize, Serialize};
38use sha2::Sha256;
39use uuid::Uuid;
40
41use super::{ARTIFACT_FORMAT_VERSION, BackupError};
42use crate::cbor;
43use crate::crypto::authority::{ReferenceAuthority, SignedEpochLedger};
44use crate::crypto::encryption::{blob_ciphertext_hash, decrypt_asset_vec, recover_file_key};
45use crate::crypto::hash::{self, Hash32};
46use crate::crypto::keys::{Amk, HybridVerifyingKey, Signer};
47use crate::crypto::primitives::{Argon2Params, CRYPTO_SUITE_ID, PROTOCOL_VERSION, info};
48use crate::crypto::provenance::ProvenanceRecord;
49use crate::crypto::{kdf, pwkdf, rng};
50
51type HmacSha256 = Hmac<Sha256>;
52
53/// The production Argon2id cost for the backup wrap key: the normal device tier.
54///
55/// The parameters an export actually used are recorded in the artifact's `VERSION` entry, so a
56/// restore reproduces the wrap key from the artifact and never from a constant. That is why
57/// this is a *default* and not a rule: [`export`] and [`export_with_salt`] — the two entry
58/// points a production build has — apply it and take no cost argument, while the `*_with_params`
59/// pair takes the cost from the caller and is compiled only under `cfg(test)` or the non-default
60/// `test-support` feature. [`BackupArtifact::open`] reads the cost back off the artifact either
61/// way.
62///
63/// It is one constant for every build. It used to be forked on `#[cfg(test)]`, which meant
64/// `capsule-core`'s own tests were the only code in the workspace that never exercised the
65/// production cost, while every downstream test paid it in full with no way to opt out.
66pub const WRAP_PARAMS: Argon2Params = Argon2Params {
67    mem_kib: 256 * 1024,
68    t_cost: 3,
69    p_cost: 1,
70};
71
72/// Where an asset's STREAM ciphertext comes from when it is written into an artifact.
73///
74/// A **source**, not a buffer: the export streams each original straight into the artifact's
75/// writer, so exporting holds one STREAM chunk of it rather than the whole library's ciphertext.
76/// The library's sources re-derive the ciphertext from the plaintext on disk
77/// (`OriginalCiphertext`); an in-memory `Vec<u8>` is a
78/// source too, for callers that already hold the bytes.
79pub trait CiphertextSource: std::fmt::Debug + Send + Sync {
80    /// The ciphertext's exact length in bytes — what the artifact's tar header declares before
81    /// a byte of the body is written.
82    fn size(&self) -> u64;
83
84    /// Stream the whole ciphertext into `writer` and return its SHA-256 content address.
85    fn write_to(&self, writer: &mut dyn Write) -> io::Result<Hash32>;
86}
87
88impl CiphertextSource for Vec<u8> {
89    fn size(&self) -> u64 {
90        self.len() as u64
91    }
92
93    fn write_to(&self, writer: &mut dyn Write) -> io::Result<Hash32> {
94        writer.write_all(self)?;
95        Ok(hash::hash_bytes(self))
96    }
97}
98
99/// One asset to back up: its ciphertext, metadata blob, and full provenance chain.
100#[derive(Debug, Clone)]
101pub struct BackupAsset {
102    /// Album the asset belongs to.
103    pub album_id: Uuid,
104    /// The asset id.
105    pub asset_id: Uuid,
106    /// The STREAM ciphertext blob, as a source the export streams from. Its bytes must hash to
107    /// the head manifest's `ciphertext_hash`: the MANIFEST commits to that address before the
108    /// body is written, and an export whose source yields anything else fails.
109    pub ciphertext: Arc<dyn CiphertextSource>,
110    /// Encrypted metadata blob (wire format).
111    pub metadata_blob: Vec<u8>,
112    /// The sealed metadata blob the chain's `create` binds, when a later edit replaced it as
113    /// [`metadata_blob`](Self::metadata_blob) (empty = none: the create binds the current blob,
114    /// or no blob). An upload carries the create, and only these exact bytes answer its
115    /// `metadata_blob_hash`, so a library that has not uploaded the asset yet needs them back.
116    /// Rides the `create-meta/{asset_id}` entry, additive within format 2.
117    pub create_metadata_blob: Vec<u8>,
118    /// The asset's provenance chain (oldest first).
119    pub provenance: Vec<ProvenanceRecord>,
120    /// The asset's custody-receipt log (`{uuid}.receipts.cbor` bytes; empty = none). Evidence,
121    /// not a cache — a server destroying the record of its own liability is the adversary — so
122    /// it rides the artifact verbatim.
123    pub receipts: Vec<u8>,
124    /// The asset's signed storage-attestation log (`{uuid}.attestations.cbor` bytes; empty =
125    /// none). Evidence for the same reason as `receipts` — a signed attestation is how a client
126    /// later proves the server reported a blob lost — so it rides the artifact verbatim.
127    pub attestations: Vec<u8>,
128}
129
130impl BackupAsset {
131    fn head(&self) -> Result<&crate::crypto::provenance::AssetManifest, BackupError> {
132        self.provenance
133            .last()
134            .map(|r| &r.manifest)
135            .ok_or(BackupError::Auth("asset has empty provenance chain"))
136    }
137}
138
139/// Which organization record a [`BackupDoc`] carries.
140#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
141pub enum BackupDocKind {
142    /// An album's `AlbumDocV1` (its labels and name), keyed by `album_id`.
143    Album,
144    /// A stack's `StackDocV1` (its labels), keyed by `stack_id`.
145    Stack,
146}
147
148impl BackupDocKind {
149    fn path_segment(self) -> &'static str {
150        match self {
151            Self::Album => "album",
152            Self::Stack => "stack",
153        }
154    }
155
156    fn from_path_segment(segment: &str) -> Option<Self> {
157        match segment {
158            "album" => Some(Self::Album),
159            "stack" => Some(Self::Stack),
160            _ => None,
161        }
162    }
163}
164
165/// One sealed organization record riding the artifact: `docs/{kind}/{doc_id}`.
166///
167/// The record stays sealed under its album's AMK exactly as it travels between members; the
168/// artifact escrows that AMK in its ledger like any asset's, so a restore opens it with nothing
169/// but the passphrase. An older reader skips the entries.
170#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct BackupDoc {
172    /// Album or stack record.
173    pub kind: BackupDocKind,
174    /// The record's key: the `album_id` or `stack_id`.
175    pub doc_id: Uuid,
176    /// The album whose AMK seals it.
177    pub album_id: Uuid,
178    /// The epoch of that AMK.
179    pub amk_version: u32,
180    /// The sealed record (metadata-blob wire format).
181    pub sealed: Vec<u8>,
182}
183
184/// The on-wire body of a `docs/` entry.
185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
186struct DocEntry {
187    album_id: Uuid,
188    amk_version: u32,
189    #[serde(with = "serde_bytes")]
190    sealed: Vec<u8>,
191}
192
193/// Everything needed to assemble an artifact.
194pub struct BackupInput {
195    /// The assets to include.
196    pub assets: Vec<BackupAsset>,
197    /// The AMK bytes for every `(album_id, amk_version)` an asset references.
198    pub amks: BTreeMap<(Uuid, u32), [u8; 32]>,
199    /// Each album's public authority: the admin-signed epoch ledger its manifests' write
200    /// signatures verify under. Only albums an included asset belongs to are written; an album
201    /// with no entry here (e.g. one itself recovered from a format-1 artifact) exports without
202    /// one, and restores readable but unverifiable.
203    pub authorities: BTreeMap<Uuid, SignedEpochLedger>,
204    /// Sealed album and stack label records. Each one's `(album_id, amk_version)` AMK must be
205    /// in [`amks`](Self::amks); the ledger escrows it.
206    pub docs: Vec<BackupDoc>,
207    /// The library's pinned attestation-key history (`.library/attestation-keys.cbor` bytes;
208    /// empty = none). It rides the artifact verbatim so a restored library keeps checking
209    /// receipts under the keys it pinned, instead of trusting whatever a server publishes first
210    /// after the restore.
211    pub attestation_key_pins: Vec<u8>,
212    /// The exporting device id.
213    pub exporter_device: Uuid,
214    /// Source library version string.
215    pub source_library_version: String,
216    /// RFC3339 export timestamp.
217    pub export_timestamp: String,
218}
219
220/// A manifest entry: a path and the SHA-256 + size of its content.
221#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
222struct EntryRef {
223    path: String,
224    hash: Hash32,
225    size: u64,
226}
227
228/// The signed core of the backup MANIFEST.
229#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230struct ManifestCore {
231    artifact_version: u16,
232    crypto_suite_id: u16,
233    min_protocol_version: String,
234    exporter_device: Uuid,
235    export_timestamp: String,
236    source_library_version: String,
237    entries: Vec<EntryRef>,
238    provenance_heads: Vec<(Uuid, Hash32)>,
239}
240
241#[derive(Debug, Clone, Serialize, Deserialize)]
242struct Manifest {
243    core: ManifestCore,
244    #[serde(with = "serde_bytes")]
245    hmac: Vec<u8>,
246    exporter_sig: crate::crypto::keys::HybridSignature,
247}
248
249/// The AMK ledger plaintext: every AMK needed to decrypt the included assets.
250#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
251struct AmkLedger {
252    /// `(album_id, amk_version) -> amk bytes`.
253    entries: Vec<(Uuid, u32, [u8; 32])>,
254}
255
256/// The artifact entry carrying the library's pinned attestation-key history.
257const ATTESTATION_KEY_PINS_ENTRY: &str = "library/attestation-keys.cbor";
258
259fn blob_role_order(role: &str) -> u8 {
260    match role {
261        "blobs" => 0,
262        "meta" => 1,
263        "provenance" => 2,
264        "receipts" => 3,
265        "authority" => 4,
266        "docs" => 5,
267        "attestations" => 6,
268        "library" => 7,
269        "create-meta" => 8,
270        _ => 9,
271    }
272}
273
274// ── tar I/O (deterministic) ─────────────────────────────────────────────────
275
276/// The tar block size: every entry body is zero-padded to a multiple of it.
277const TAR_BLOCK: u64 = 512;
278
279fn tar_io(e: &io::Error) -> BackupError {
280    BackupError::Format(format!("writing the artifact: {e}"))
281}
282
283/// The deterministic header every entry carries: a regular file, mode 0644, owned by 0:0 at
284/// the epoch, declaring `size` body bytes.
285fn tar_header(size: u64) -> tar::Header {
286    let mut h = tar::Header::new_gnu();
287    h.set_size(size);
288    h.set_mode(0o644);
289    h.set_mtime(0);
290    h.set_uid(0);
291    h.set_gid(0);
292    h.set_entry_type(tar::EntryType::Regular);
293    h
294}
295
296fn tar_append<W: Write>(
297    builder: &mut tar::Builder<W>,
298    path: &str,
299    data: &[u8],
300) -> Result<(), BackupError> {
301    let mut h = tar_header(data.len() as u64);
302    builder
303        .append_data(&mut h, path, data)
304        .map_err(|e| tar_io(&e))
305}
306
307/// Append an entry whose body is streamed from `source` rather than held, byte-identical to
308/// [`tar_append`] over the same bytes.
309///
310/// `tar` takes an entry body only as a [`Read`], and a [`CiphertextSource`] pushes into a
311/// writer, so the entry is written in two halves: `tar` writes the header — with the same path
312/// encoding [`tar_append`] gets — over an empty body (zero bytes copied, so no padding), and the
313/// body and its padding then go straight into the builder's writer. The body must be exactly
314/// the `size` the header declared and hash to `expected`, the address the MANIFEST already
315/// committed to; anything else fails the export, whose output must then be discarded.
316fn tar_append_stream<W: Write>(
317    builder: &mut tar::Builder<W>,
318    path: &str,
319    source: &dyn CiphertextSource,
320    expected: Hash32,
321) -> Result<(), BackupError> {
322    let size = source.size();
323    let mut h = tar_header(size);
324    builder
325        .append_data(&mut h, path, io::empty())
326        .map_err(|e| tar_io(&e))?;
327    let mut body = CountingWriter::new(builder.get_mut());
328    let written_hash = source.write_to(&mut body).map_err(|e| tar_io(&e))?;
329    let written = body.written;
330    if written != size || written_hash != expected {
331        tracing::error!(
332            path,
333            declared_size = size,
334            written,
335            expected = %expected.to_hex(),
336            actual = %written_hash.to_hex(),
337            "backup: a ciphertext source disagrees with its manifest"
338        );
339        return Err(BackupError::Corrupt(format!(
340            "{path}: the source yielded {written} bytes hashing to {}, not the {size} bytes \
341             hashing to {} the manifest commits to",
342            written_hash.to_hex(),
343            expected.to_hex()
344        )));
345    }
346    let padding = (TAR_BLOCK - size % TAR_BLOCK) % TAR_BLOCK;
347    builder
348        .get_mut()
349        .write_all(&[0; TAR_BLOCK as usize][..padding as usize])
350        .map_err(|e| tar_io(&e))
351}
352
353/// A writer that counts what passes through it to `inner`.
354struct CountingWriter<W> {
355    inner: W,
356    written: u64,
357}
358
359impl<W> CountingWriter<W> {
360    fn new(inner: W) -> Self {
361        Self { inner, written: 0 }
362    }
363}
364
365impl<W: Write> Write for CountingWriter<W> {
366    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
367        let n = self.inner.write(buf)?;
368        self.written += n as u64;
369        Ok(n)
370    }
371
372    fn flush(&mut self) -> io::Result<()> {
373        self.inner.flush()
374    }
375}
376
377fn tar_read(bytes: &[u8]) -> Result<Vec<(String, Vec<u8>)>, BackupError> {
378    let mut archive = tar::Archive::new(bytes);
379    let mut out = Vec::new();
380    for entry in archive
381        .entries()
382        .map_err(|e| BackupError::Format(e.to_string()))?
383    {
384        let mut e = entry.map_err(|e| BackupError::Format(e.to_string()))?;
385        let path = e
386            .path()
387            .map_err(|e| BackupError::Format(e.to_string()))?
388            .to_string_lossy()
389            .into_owned();
390        let mut buf = Vec::new();
391        e.read_to_end(&mut buf)
392            .map_err(|e| BackupError::Format(e.to_string()))?;
393        out.push((path, buf));
394    }
395    Ok(out)
396}
397
398/// The plaintext `VERSION` entry. `params` is the cost this export actually derived under, not
399/// a compiled-in default: [`parse_version`] reads it straight back, which is what makes a
400/// restore reproduce the wrap key of an artifact exported at any cost.
401fn version_blob(salt: &[u8; 32], params: Argon2Params) -> Vec<u8> {
402    format!(
403        "artifact_format={ARTIFACT_FORMAT_VERSION}\ncrypto_suite_id={CRYPTO_SUITE_ID}\nmin_protocol_version={PROTOCOL_VERSION}\nwrap_salt={}\nwrap_mem_kib={}\nwrap_t={}\nwrap_p={}\n",
404        hex::encode(salt),
405        params.mem_kib,
406        params.t_cost,
407        params.p_cost,
408    )
409    .into_bytes()
410}
411
412fn parse_version(blob: &[u8]) -> Result<([u8; 32], Argon2Params), BackupError> {
413    let text =
414        std::str::from_utf8(blob).map_err(|_| BackupError::Format("VERSION not utf8".into()))?;
415    let mut salt = None;
416    let (mut mem, mut t, mut p) = (None, None, None);
417    for line in text.lines() {
418        if let Some((k, v)) = line.split_once('=') {
419            match k {
420                "wrap_salt" => {
421                    salt = Hash32::from_hex(v).ok().map(|h| h.0);
422                }
423                "wrap_mem_kib" => mem = v.parse().ok(),
424                "wrap_t" => t = v.parse().ok(),
425                "wrap_p" => p = v.parse().ok(),
426                _ => {}
427            }
428        }
429    }
430    Ok((
431        salt.ok_or(BackupError::Format("VERSION missing wrap_salt".into()))?,
432        Argon2Params {
433            mem_kib: mem.ok_or(BackupError::Format("VERSION missing wrap_mem_kib".into()))?,
434            t_cost: t.ok_or(BackupError::Format("VERSION missing wrap_t".into()))?,
435            p_cost: p.ok_or(BackupError::Format("VERSION missing wrap_p".into()))?,
436        },
437    ))
438}
439
440/// Seal the AMK ledger under the wrap key with a deterministic (key-derived) nonce, so a
441/// re-export with the same salt+content is byte-identical. Production uses a fresh random
442/// salt per export, so the (key, nonce) pair never repeats across distinct plaintexts.
443fn seal_ledger(wrap_key: &[u8; 32], ledger: &AmkLedger) -> Vec<u8> {
444    use aes_gcm::aead::{Aead, KeyInit};
445    use aes_gcm::{Aes256Gcm, Key, Nonce};
446    let plaintext = cbor::to_canonical_vec(ledger).expect("ledger serializes");
447    let nonce_bytes = kdf::derive_key32(wrap_key, b"amk-ledger-nonce", info::METADATA_BLOB_V1);
448    let nonce = &nonce_bytes[..12];
449    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(wrap_key));
450    cipher
451        .encrypt(Nonce::from_slice(nonce), plaintext.as_slice())
452        .expect("ledger seal")
453}
454
455fn open_ledger(wrap_key: &[u8; 32], sealed: &[u8]) -> Result<AmkLedger, BackupError> {
456    use aes_gcm::aead::{Aead, KeyInit};
457    use aes_gcm::{Aes256Gcm, Key, Nonce};
458    let nonce_bytes = kdf::derive_key32(wrap_key, b"amk-ledger-nonce", info::METADATA_BLOB_V1);
459    let nonce = &nonce_bytes[..12];
460    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(wrap_key));
461    let plaintext = cipher
462        .decrypt(Nonce::from_slice(nonce), sealed)
463        .map_err(|_| BackupError::Auth("AMK ledger decryption failed"))?;
464    cbor::from_slice(&plaintext).map_err(|e| BackupError::Format(e.to_string()))
465}
466
467// ── Export ──────────────────────────────────────────────────────────────────
468
469/// Assemble a backup artifact with an explicit wrap salt (deterministic), at the production
470/// [`WRAP_PARAMS`] cost.
471pub fn export_with_salt(
472    input: &BackupInput,
473    passphrase: &[u8],
474    salt: [u8; 32],
475    exporter: &dyn Signer,
476) -> Result<Vec<u8>, BackupError> {
477    let mut out = Vec::new();
478    export_inner(input, passphrase, salt, WRAP_PARAMS, exporter, &mut out)?;
479    Ok(out)
480}
481
482/// Assemble a backup artifact with an explicit wrap salt **and** an explicit Argon2id cost.
483///
484/// `params` is written into the artifact's `VERSION` entry, so whatever cost is chosen here is
485/// the cost [`BackupArtifact::open`] pays to reproduce the wrap key — a caller that exports
486/// cheaply gets a cheap restore, and neither side needs to be told twice.
487///
488/// **Not in a production build.** A weak `params` produces a brute-forceable artifact, and
489/// nothing downstream of here re-checks the cost: [`pwkdf::derive_wrap_key`] accepts anything
490/// `argon2::Params::new` validates. So the entry point that can do it is compiled only under
491/// `cfg(test)` or the non-default `test-support` feature, and weakening a real backup therefore
492/// takes a visible line in a production manifest rather than an unnoticed call. The always-
493/// available [`export`] and [`export_with_salt`] cannot be given a cost at all.
494///
495/// This is the same guard [`escrow_master_key`](super::escrow_master_key) gets from taking a
496/// closed [`DeviceTier`](crate::crypto::primitives::DeviceTier) instead of raw parameters,
497/// reached differently: every `DeviceTier` arm is memory-hard by design, so the tier enum has no
498/// arm a test could use as the fast path.
499#[cfg(any(test, feature = "test-support"))]
500pub fn export_with_salt_and_params(
501    input: &BackupInput,
502    passphrase: &[u8],
503    salt: [u8; 32],
504    params: Argon2Params,
505    exporter: &dyn Signer,
506) -> Result<Vec<u8>, BackupError> {
507    let mut out = Vec::new();
508    export_inner(input, passphrase, salt, params, exporter, &mut out)?;
509    Ok(out)
510}
511
512/// One entry body awaiting its place in the tar: bytes assembled (or borrowed) up front, or a
513/// ciphertext streamed from its source only when the entry is written.
514enum Payload<'a> {
515    Bytes(Cow<'a, [u8]>),
516    Ciphertext {
517        source: &'a dyn CiphertextSource,
518        hash: Hash32,
519    },
520}
521
522/// The one implementation every export entry point delegates to. Private, so the only way to
523/// reach it with a caller-chosen cost is through the gated entry points above.
524///
525/// Writes the artifact into `out` and returns its length. Each original's ciphertext is
526/// streamed from its [`CiphertextSource`] as its entry is written, so the export holds one
527/// STREAM chunk of an original at a time, never the library's ciphertext. Its MANIFEST entry
528/// is the head manifest's `ciphertext_hash` and the source's declared size, known before the
529/// body is read; the write then checks the body against both. On an error `out` holds a
530/// partial artifact the caller must discard.
531fn export_inner(
532    input: &BackupInput,
533    passphrase: &[u8],
534    salt: [u8; 32],
535    params: Argon2Params,
536    exporter: &dyn Signer,
537    out: &mut dyn Write,
538) -> Result<u64, BackupError> {
539    let wrap_key = pwkdf::derive_wrap_key(passphrase, &salt, params)?;
540
541    // Build the AMK ledger, asserting completeness for every referenced epoch.
542    let mut ledger = AmkLedger::default();
543    let mut needed: BTreeSet<(Uuid, u32)> = BTreeSet::new();
544    for a in &input.assets {
545        let head = a.head()?;
546        needed.insert((a.album_id, head.core.amk_version.0));
547    }
548    for doc in &input.docs {
549        needed.insert((doc.album_id, doc.amk_version));
550    }
551    for (album, epoch) in &needed {
552        let amk = input
553            .amks
554            .get(&(*album, *epoch))
555            .ok_or_else(|| BackupError::AmkIncomplete(format!("album {album} epoch {epoch}")))?;
556        ledger.entries.push((*album, *epoch, *amk));
557    }
558    ledger.entries.sort();
559    let sealed_ledger = seal_ledger(&wrap_key, &ledger);
560
561    // Sort assets deterministically by (album_id, asset_id).
562    let mut assets: Vec<&BackupAsset> = input.assets.iter().collect();
563    assets.sort_by_key(|a| (a.album_id, a.asset_id));
564
565    // Collect entries (sorted by album, asset, then blob role) and provenance heads.
566    let mut entries: Vec<EntryRef> = Vec::new();
567    let mut payloads: Vec<(String, Payload<'_>)> = Vec::new();
568    let mut provenance_heads: Vec<(Uuid, Hash32)> = Vec::new();
569
570    entries.push(EntryRef {
571        path: "keys/amk-ledger.cbor".into(),
572        hash: hash::hash_bytes(&sealed_ledger),
573        size: sealed_ledger.len() as u64,
574    });
575
576    // Each included album's public authority, when the exporter holds one. Public data, so it
577    // rides in the clear; the MANIFEST's HMAC and exporter signature cover it like every entry.
578    let albums: BTreeSet<Uuid> = needed.iter().map(|(album, _)| *album).collect();
579    for album in &albums {
580        let Some(ledger) = input.authorities.get(album) else {
581            tracing::warn!(
582                album_id = %album,
583                "backup: album has no reference authority to export; it restores unverifiable"
584            );
585            continue;
586        };
587        if ledger.album_id != *album {
588            return Err(BackupError::Format(format!(
589                "authority ledger for album {album} speaks for album {}",
590                ledger.album_id
591            )));
592        }
593        let path = format!("authority/{album}");
594        let data = cbor::to_canonical_vec(ledger).expect("authority ledger serializes");
595        entries.push(EntryRef {
596            path: path.clone(),
597            hash: hash::hash_bytes(&data),
598            size: data.len() as u64,
599        });
600        payloads.push((path, Payload::Bytes(Cow::Owned(data))));
601    }
602
603    // Album and stack label records, still sealed under their album's AMK.
604    for doc in &input.docs {
605        let path = format!("docs/{}/{}", doc.kind.path_segment(), doc.doc_id);
606        let data = cbor::to_canonical_vec(&DocEntry {
607            album_id: doc.album_id,
608            amk_version: doc.amk_version,
609            sealed: doc.sealed.clone(),
610        })
611        .expect("doc entry serializes");
612        entries.push(EntryRef {
613            path: path.clone(),
614            hash: hash::hash_bytes(&data),
615            size: data.len() as u64,
616        });
617        payloads.push((path, Payload::Bytes(Cow::Owned(data))));
618    }
619
620    // The library's pinned attestation-key history, verbatim. Public keys, so it rides in the
621    // clear under the MANIFEST's HMAC and exporter signature like every entry. Additive: an
622    // older reader hash-checks it as a manifest entry and otherwise ignores it.
623    if !input.attestation_key_pins.is_empty() {
624        let data = input.attestation_key_pins.as_slice();
625        entries.push(EntryRef {
626            path: ATTESTATION_KEY_PINS_ENTRY.into(),
627            hash: hash::hash_bytes(data),
628            size: data.len() as u64,
629        });
630        payloads.push((
631            ATTESTATION_KEY_PINS_ENTRY.into(),
632            Payload::Bytes(Cow::Borrowed(data)),
633        ));
634    }
635
636    for a in &assets {
637        let head = a.head()?;
638        let ct_path = format!("blobs/{}", head.core.ciphertext_hash.to_hex());
639        let meta_path = format!("meta/{}", a.asset_id);
640        let prov_bytes = cbor::to_canonical_vec(&a.provenance).expect("provenance serializes");
641        let prov_path = format!("provenance/{}", a.asset_id);
642
643        // The original's entry is committed to from what is known without reading it: the
644        // address its signed manifest names and the size its source declares. Its bytes are
645        // read once, when the entry is written, and checked against both there.
646        entries.push(EntryRef {
647            path: ct_path.clone(),
648            hash: head.core.ciphertext_hash,
649            size: a.ciphertext.size(),
650        });
651        payloads.push((
652            ct_path,
653            Payload::Ciphertext {
654                source: a.ciphertext.as_ref(),
655                hash: head.core.ciphertext_hash,
656            },
657        ));
658
659        let mut asset_entries: Vec<(String, Cow<'_, [u8]>)> = vec![
660            (meta_path, Cow::Borrowed(&a.metadata_blob)),
661            (prov_path, Cow::Owned(prov_bytes)),
662        ];
663        // The custody-receipt log rides the artifact only when present (absent = no key).
664        if !a.receipts.is_empty() {
665            asset_entries.push((
666                format!("receipts/{}", a.asset_id),
667                Cow::Borrowed(&a.receipts),
668            ));
669        }
670        // The create's superseded metadata blob, likewise, still sealed. Additive: an older
671        // reader hash-checks it as a manifest entry and otherwise ignores it.
672        if !a.create_metadata_blob.is_empty() {
673            asset_entries.push((
674                format!("create-meta/{}", a.asset_id),
675                Cow::Borrowed(&a.create_metadata_blob),
676            ));
677        }
678        // So does the signed storage-attestation log.
679        if !a.attestations.is_empty() {
680            asset_entries.push((
681                format!("attestations/{}", a.asset_id),
682                Cow::Borrowed(&a.attestations),
683            ));
684        }
685        for (path, data) in asset_entries {
686            entries.push(EntryRef {
687                path: path.clone(),
688                hash: hash::hash_bytes(&data),
689                size: data.len() as u64,
690            });
691            payloads.push((path, Payload::Bytes(data)));
692        }
693        let head_rec = a
694            .provenance
695            .last()
696            .expect("provenance chain is never empty")
697            .record_hash();
698        provenance_heads.push((a.asset_id, head_rec));
699    }
700    entries.sort_by(|x, y| {
701        let rank = |p: &str| {
702            let role = p.split('/').next().unwrap_or("");
703            blob_role_order(role)
704        };
705        x.path
706            .split('/')
707            .next()
708            .cmp(&y.path.split('/').next())
709            .then(rank(&x.path).cmp(&rank(&y.path)))
710            .then(x.path.cmp(&y.path))
711    });
712
713    let core = ManifestCore {
714        artifact_version: ARTIFACT_FORMAT_VERSION,
715        crypto_suite_id: CRYPTO_SUITE_ID,
716        min_protocol_version: PROTOCOL_VERSION.into(),
717        exporter_device: input.exporter_device,
718        export_timestamp: input.export_timestamp.clone(),
719        source_library_version: input.source_library_version.clone(),
720        entries,
721        provenance_heads,
722    };
723    let core_bytes = cbor::to_canonical_vec(&core).expect("manifest core serializes");
724    let mut mac = HmacSha256::new_from_slice(&wrap_key).expect("hmac key");
725    mac.update(&core_bytes);
726    let hmac = mac.finalize().into_bytes().to_vec();
727    let exporter_sig = exporter.sign(&core_bytes)?;
728    let manifest = Manifest {
729        core,
730        hmac,
731        exporter_sig,
732    };
733    let manifest_bytes = cbor::to_canonical_vec(&manifest).expect("manifest serializes");
734
735    // Write the tar: VERSION, MANIFEST, ledger, then sorted payloads.
736    let mut builder = tar::Builder::new(CountingWriter::new(out));
737    tar_append(&mut builder, "VERSION", &version_blob(&salt, params))?;
738    tar_append(&mut builder, "MANIFEST.cbor", &manifest_bytes)?;
739    tar_append(&mut builder, "keys/amk-ledger.cbor", &sealed_ledger)?;
740    // Re-sort payloads to match the manifest entry order.
741    payloads.sort_by(|x, y| {
742        x.0.split('/')
743            .next()
744            .cmp(&y.0.split('/').next())
745            .then(x.0.cmp(&y.0))
746    });
747    for (path, payload) in &payloads {
748        match payload {
749            Payload::Bytes(data) => tar_append(&mut builder, path, data)?,
750            Payload::Ciphertext { source, hash } => {
751                tar_append_stream(&mut builder, path, *source, *hash)?;
752            }
753        }
754    }
755    let mut counted = builder.into_inner().map_err(|e| tar_io(&e))?;
756    counted.flush().map_err(|e| tar_io(&e))?;
757    tracing::debug!(
758        assets = assets.len(),
759        entries = payloads.len() + 3,
760        bytes = counted.written,
761        "backup: artifact written"
762    );
763    Ok(counted.written)
764}
765
766/// Assemble a backup artifact in memory, drawing a fresh random wrap salt, at the production
767/// [`WRAP_PARAMS`] cost.
768///
769/// The whole artifact is returned as one buffer, so this suits a caller that needs the bytes
770/// themselves (a peer delta it content-addresses). Exporting a library goes through
771/// [`export_to`], which streams.
772pub fn export(
773    input: &BackupInput,
774    passphrase: &[u8],
775    exporter: &dyn Signer,
776) -> Result<Vec<u8>, BackupError> {
777    export_with_salt(input, passphrase, rng::random_array::<32>(), exporter)
778}
779
780/// Write a backup artifact into `out`, drawing a fresh random wrap salt, at the production
781/// [`WRAP_PARAMS`] cost (production path), and return its length in bytes.
782///
783/// Each asset's ciphertext is streamed from its [`CiphertextSource`] as its entry is written,
784/// so memory stays at one STREAM chunk of an original whatever the library's size. On an error
785/// `out` holds a partial artifact, which the caller must discard.
786///
787/// This is the entry point `Workspace::export_backup`
788/// runs, and it takes no cost argument, so no caller of it can produce a weak artifact.
789pub fn export_to(
790    input: &BackupInput,
791    passphrase: &[u8],
792    exporter: &dyn Signer,
793    out: &mut dyn Write,
794) -> Result<u64, BackupError> {
795    export_inner(
796        input,
797        passphrase,
798        rng::random_array::<32>(),
799        WRAP_PARAMS,
800        exporter,
801        out,
802    )
803}
804
805/// As [`export`] but with an explicit Argon2id cost for the wrap key — the entry point a test
806/// uses instead of reaching for a build-configuration fork.
807///
808/// **Not in a production build**, for the reason given on [`export_with_salt_and_params`].
809#[cfg(any(test, feature = "test-support"))]
810pub fn export_with_params(
811    input: &BackupInput,
812    passphrase: &[u8],
813    params: Argon2Params,
814    exporter: &dyn Signer,
815) -> Result<Vec<u8>, BackupError> {
816    let mut out = Vec::new();
817    export_with_params_to(input, passphrase, params, exporter, &mut out)?;
818    Ok(out)
819}
820
821/// As [`export_to`] but with an explicit Argon2id cost for the wrap key.
822///
823/// **Not in a production build**, for the reason given on [`export_with_salt_and_params`].
824#[cfg(any(test, feature = "test-support"))]
825pub fn export_with_params_to(
826    input: &BackupInput,
827    passphrase: &[u8],
828    params: Argon2Params,
829    exporter: &dyn Signer,
830    out: &mut dyn Write,
831) -> Result<u64, BackupError> {
832    export_inner(
833        input,
834        passphrase,
835        rng::random_array::<32>(),
836        params,
837        exporter,
838        out,
839    )
840}
841
842// ── Restore ─────────────────────────────────────────────────────────────────
843
844/// How aggressively a restore acts. Dry-run is the safe default.
845#[derive(Debug, Clone, Copy, PartialEq, Eq)]
846pub enum RestoreMode {
847    /// Verify structure only; no decrypt, no write.
848    Preview,
849    /// Verify decryption + hashes and compute the diff; **no write** (default).
850    DryRun,
851    /// Apply (the caller writes the returned assets); never a silent overwrite.
852    Commit,
853}
854
855/// A decrypted asset ready to write into a library (returned only on `Commit`).
856#[derive(Debug, Clone)]
857pub struct RestoredAsset {
858    /// Album id.
859    pub album_id: Uuid,
860    /// Asset id.
861    pub asset_id: Uuid,
862    /// Decrypted plaintext bytes.
863    pub plaintext: Vec<u8>,
864    /// The metadata blob (still encrypted; written verbatim).
865    pub metadata_blob: Vec<u8>,
866    /// The sealed metadata blob the chain's `create` binds, when the artifact carried one that
867    /// answers the create's `metadata_blob_hash` (empty otherwise: an artifact from before the
868    /// entry existed, an asset whose create binds its current blob, or a carried blob that did
869    /// not answer, which is dropped with a warning) — kept beside the chain on commit.
870    pub create_metadata_blob: Vec<u8>,
871    /// The provenance chain.
872    pub provenance: Vec<ProvenanceRecord>,
873    /// The asset's custody-receipt log (`{uuid}.receipts.cbor` bytes; empty if the artifact
874    /// carried none) — written back beside the provenance chain on commit.
875    pub receipts: Vec<u8>,
876    /// The asset's signed storage-attestation log (`{uuid}.attestations.cbor` bytes; empty if
877    /// the artifact carried none) — written back beside the receipts on commit.
878    pub attestations: Vec<u8>,
879}
880
881/// The outcome of a restore (chain-reconciliation; newer local state always wins).
882#[derive(Debug, Default)]
883pub struct RestoreReport {
884    /// Entries whose content hash (and, past preview, decryption) verified.
885    pub verified: usize,
886    /// Assets absent locally — applied on commit.
887    pub would_add: Vec<Uuid>,
888    /// Assets already current locally — no-op.
889    pub identical: Vec<Uuid>,
890    /// Assets whose local head differs — not applied (quarantined for explicit merge).
891    pub conflicts: Vec<Uuid>,
892    /// Decrypted assets to write (populated only on `Commit`).
893    pub applied: Vec<RestoredAsset>,
894}
895
896/// A verified, opened backup artifact, ready to restore.
897pub struct BackupArtifact {
898    files: BTreeMap<String, Vec<u8>>,
899    ledger: BTreeMap<(Uuid, u32), [u8; 32]>,
900    authorities: BTreeMap<Uuid, SignedEpochLedger>,
901    docs: Vec<BackupDoc>,
902    attestation_key_pins: Option<Vec<u8>>,
903    core: ManifestCore,
904}
905
906impl BackupArtifact {
907    /// Open and fully verify an artifact: HMAC (wrap key) + exporter signature + per-entry
908    /// content hashes + AMK-ledger completeness. The exporter key is looked up by the caller
909    /// in the user's device directory.
910    pub fn open(
911        bytes: &[u8],
912        passphrase: &[u8],
913        exporter_pub: &HybridVerifyingKey,
914    ) -> Result<Self, BackupError> {
915        let files: BTreeMap<String, Vec<u8>> = tar_read(bytes)?.into_iter().collect();
916        let version = files
917            .get("VERSION")
918            .ok_or(BackupError::Format("missing VERSION".into()))?;
919        let (salt, params) = parse_version(version)?;
920        let wrap_key = pwkdf::derive_wrap_key(passphrase, &salt, params)?;
921
922        let manifest_bytes = files
923            .get("MANIFEST.cbor")
924            .ok_or(BackupError::Format("missing MANIFEST.cbor".into()))?;
925        let manifest: Manifest =
926            cbor::from_slice(manifest_bytes).map_err(|e| BackupError::Format(e.to_string()))?;
927        let core_bytes = cbor::to_canonical_vec(&manifest.core).expect("manifest core serializes");
928
929        // (1) HMAC under the wrap key (catches tamper before any decrypt).
930        let mut mac = HmacSha256::new_from_slice(&wrap_key).expect("hmac key");
931        mac.update(&core_bytes);
932        mac.verify_slice(&manifest.hmac).map_err(|_| {
933            BackupError::Auth("MANIFEST HMAC mismatch (tamper or wrong passphrase)")
934        })?;
935        // (2) Exporter hybrid signature (defeats a wrap-key thief).
936        if !exporter_pub.verify(&core_bytes, &manifest.exporter_sig) {
937            return Err(BackupError::Auth("MANIFEST exporter signature invalid"));
938        }
939        // An authenticated manifest from a newer format is refused rather than half-read.
940        if manifest.core.artifact_version > ARTIFACT_FORMAT_VERSION {
941            return Err(BackupError::Format(format!(
942                "artifact format {} is newer than this build supports ({ARTIFACT_FORMAT_VERSION})",
943                manifest.core.artifact_version
944            )));
945        }
946
947        // (3) Per-entry content hashes.
948        for entry in &manifest.core.entries {
949            let data = files
950                .get(&entry.path)
951                .ok_or_else(|| BackupError::Corrupt(format!("missing entry {}", entry.path)))?;
952            if hash::hash_bytes(data) != entry.hash || data.len() as u64 != entry.size {
953                return Err(BackupError::Corrupt(entry.path.clone()));
954            }
955        }
956
957        // (4) Unseal + load the AMK ledger.
958        let sealed = files
959            .get("keys/amk-ledger.cbor")
960            .ok_or(BackupError::Format("missing AMK ledger".into()))?;
961        let ledger = open_ledger(&wrap_key, sealed)?;
962        let ledger: BTreeMap<(Uuid, u32), [u8; 32]> = ledger
963            .entries
964            .into_iter()
965            .map(|(album, epoch, amk)| ((album, epoch), amk))
966            .collect();
967
968        // (5) Decode + re-verify every album authority the (authenticated) manifest lists.
969        let authorities = load_authorities(&manifest.core, &files)?;
970
971        // (6) Decode every album/stack label record the manifest lists; each must be sealed under
972        // an AMK the ledger escrows.
973        let docs = load_docs(&manifest.core, &files, &ledger)?;
974
975        // (7) The pinned attestation-key history, when the (authenticated) manifest lists one.
976        // Its bytes were hash-checked in (3); the restore decodes them.
977        let attestation_key_pins = manifest
978            .core
979            .entries
980            .iter()
981            .any(|entry| entry.path == ATTESTATION_KEY_PINS_ENTRY)
982            .then(|| files.get(ATTESTATION_KEY_PINS_ENTRY).cloned())
983            .flatten();
984
985        Ok(Self {
986            files,
987            ledger,
988            authorities,
989            docs,
990            attestation_key_pins,
991            core: manifest.core,
992        })
993    }
994
995    /// Restore against a target library's current provenance heads (`asset_id -> head hash`).
996    /// `Preview` checks structure only; `DryRun` (default) also decrypts to verify; `Commit`
997    /// returns the decrypted assets to write. Never overwrites newer local state.
998    pub fn restore(
999        &self,
1000        mode: RestoreMode,
1001        local_heads: &BTreeMap<Uuid, Hash32>,
1002    ) -> Result<RestoreReport, BackupError> {
1003        let mut report = RestoreReport::default();
1004
1005        for (asset_id, head_hash) in &self.core.provenance_heads {
1006            report.verified += 1;
1007
1008            // Reconcile against local state (newer local always wins; no silent overwrite).
1009            match local_heads.get(asset_id) {
1010                Some(local) if local == head_hash => {
1011                    report.identical.push(*asset_id);
1012                    continue;
1013                }
1014                Some(_) => {
1015                    report.conflicts.push(*asset_id);
1016                    continue;
1017                }
1018                None => report.would_add.push(*asset_id),
1019            }
1020
1021            if mode == RestoreMode::Preview {
1022                continue;
1023            }
1024
1025            // Decrypt to verify (DryRun) / to return for writing (Commit).
1026            let restored = self.decrypt_asset(asset_id)?;
1027            if mode == RestoreMode::Commit {
1028                report.applied.push(restored);
1029            }
1030        }
1031        Ok(report)
1032    }
1033
1034    /// Decrypt one asset from the artifact using the ledger AMK + its head manifest.
1035    fn decrypt_asset(&self, asset_id: &Uuid) -> Result<RestoredAsset, BackupError> {
1036        let prov_bytes = self
1037            .files
1038            .get(&format!("provenance/{asset_id}"))
1039            .ok_or_else(|| BackupError::Corrupt(format!("missing provenance {asset_id}")))?;
1040        let provenance: Vec<ProvenanceRecord> =
1041            cbor::from_slice(prov_bytes).map_err(|e| BackupError::Format(e.to_string()))?;
1042        let head = provenance
1043            .last()
1044            .ok_or(BackupError::Auth("empty provenance chain"))?
1045            .manifest
1046            .clone();
1047
1048        let ct = self
1049            .files
1050            .get(&format!("blobs/{}", head.core.ciphertext_hash.to_hex()))
1051            .ok_or_else(|| BackupError::Corrupt(format!("missing ciphertext for {asset_id}")))?;
1052        // Confirm the content hash before decrypting.
1053        if hash::hash_bytes(ct) != head.core.ciphertext_hash {
1054            return Err(BackupError::Corrupt(format!(
1055                "ciphertext hash for {asset_id}"
1056            )));
1057        }
1058
1059        let amk_bytes = self
1060            .ledger
1061            .get(&(head.core.album_id, head.core.amk_version.0))
1062            .ok_or_else(|| {
1063                BackupError::AmkIncomplete(format!(
1064                    "album {} epoch {}",
1065                    head.core.album_id, head.core.amk_version.0
1066                ))
1067            })?;
1068        // Honour the head's `key_mode`: an adopted drop carries its key wrapped, not derived.
1069        let file_key = recover_file_key(&Amk::from_bytes(*amk_bytes), &head.core)
1070            .map_err(|_| BackupError::Auth("asset file key recovery failed"))?;
1071        let plaintext = decrypt_asset_vec(&file_key, &head.core.nonce_prefix, ct)
1072            .map_err(|_| BackupError::Auth("asset decryption failed"))?;
1073
1074        let metadata_blob = self
1075            .files
1076            .get(&format!("meta/{asset_id}"))
1077            .cloned()
1078            .unwrap_or_default();
1079
1080        let create_metadata_blob = self.create_metadata_blob(asset_id, &provenance);
1081
1082        // The custody-receipt log rides the artifact when the exporter held one.
1083        let receipts = self
1084            .files
1085            .get(&format!("receipts/{asset_id}"))
1086            .cloned()
1087            .unwrap_or_default();
1088        // And the signed storage-attestation log, likewise. An artifact from before the log
1089        // existed carries none, which restores as an empty log.
1090        let attestations = self
1091            .files
1092            .get(&format!("attestations/{asset_id}"))
1093            .cloned()
1094            .unwrap_or_default();
1095
1096        Ok(RestoredAsset {
1097            album_id: head.core.album_id,
1098            asset_id: *asset_id,
1099            plaintext,
1100            metadata_blob,
1101            create_metadata_blob,
1102            provenance,
1103            receipts,
1104            attestations,
1105        })
1106    }
1107
1108    /// The `create-meta/{asset_id}` blob, when it answers the `metadata_blob_hash` the chain's
1109    /// `create` signed; empty otherwise.
1110    ///
1111    /// A carried blob that does not answer is dropped with a warning rather than refusing the
1112    /// restore: it only matters to uploading the create, and the asset, its chain and its current
1113    /// metadata restore without it. Checking it against the signed create (not only the
1114    /// manifest's entry hash) keeps a library from ever holding create bytes the server would
1115    /// refuse under that address.
1116    fn create_metadata_blob(&self, asset_id: &Uuid, provenance: &[ProvenanceRecord]) -> Vec<u8> {
1117        let Some(carried) = self.files.get(&format!("create-meta/{asset_id}")) else {
1118            return Vec::new();
1119        };
1120        let bound = provenance
1121            .first()
1122            .and_then(|create| create.manifest.core.metadata_blob_hash);
1123        if bound == Some(blob_ciphertext_hash(carried)) {
1124            tracing::debug!(
1125                asset_id = %asset_id,
1126                bytes = carried.len(),
1127                "backup: the create's kept metadata blob restored"
1128            );
1129            return carried.clone();
1130        }
1131        tracing::warn!(
1132            asset_id = %asset_id,
1133            create_binds_blob = bound.is_some(),
1134            "backup: the carried create metadata blob does not answer the create; dropped, and \
1135             the create cannot be uploaded from this library"
1136        );
1137        Vec::new()
1138    }
1139
1140    /// The escrowed AMK rows this artifact carries: `(album_id, epoch, amk)`.
1141    ///
1142    /// The same row shape the durable album keystore holds
1143    /// ([`AmkRow`](crate::crypto::keys::AmkRow)), so folding a restore's recovered keys into a
1144    /// library's keystore is a `map`, not a translation table. This is the path by which a
1145    /// library that lost its album keys becomes able to read its photos again — the backup path
1146    /// is deliberately independent of the MLS ratchet (SSoT: [Keys]).
1147    ///
1148    /// Note what is *not* here: the write-tier and admin signing keys. Those are MLS-distributed
1149    /// capabilities, not escrowed secrets, so an album restored into a library that never held
1150    /// it is readable but not writable. Its public authority rides separately
1151    /// ([`authority_ledgers`](Self::authority_ledgers)), which is what makes it verifiable.
1152    ///
1153    /// [Keys]: https://docs/design/cryptography/keys/#album-master-keys-amks
1154    pub fn amk_rows(&self) -> Vec<(Uuid, u32, [u8; 32])> {
1155        self.ledger
1156            .iter()
1157            .map(|((album, epoch), amk)| (*album, *epoch, *amk))
1158            .collect()
1159    }
1160
1161    /// Each album's public authority the artifact carries: the admin-signed epoch ledger, keyed
1162    /// by album id. Every ledger here was listed in the authenticated manifest, speaks for the
1163    /// album it is filed under, and re-verified its admin signature chain in [`open`](Self::open).
1164    /// Empty for a format-1 artifact, which carried none.
1165    pub fn authority_ledgers(&self) -> &BTreeMap<Uuid, SignedEpochLedger> {
1166        &self.authorities
1167    }
1168
1169    /// The sealed album and stack label records the artifact carries, each listed in the
1170    /// authenticated manifest and sealed under an AMK [`amk`](Self::amk) returns. Empty for an
1171    /// artifact exported before the records existed.
1172    pub fn docs(&self) -> &[BackupDoc] {
1173        &self.docs
1174    }
1175
1176    /// The library's pinned attestation-key history the artifact carries
1177    /// (`.library/attestation-keys.cbor` bytes, verbatim), listed in the authenticated manifest.
1178    /// `None` for an artifact exported by a library that had pinned nothing, or before the pin
1179    /// rode the artifact; such an artifact restores exactly as it did before.
1180    pub fn attestation_key_pins(&self) -> Option<&[u8]> {
1181        self.attestation_key_pins.as_deref()
1182    }
1183
1184    /// The escrowed AMK for `(album_id, epoch)`, if the ledger holds it.
1185    pub fn amk(&self, album_id: &Uuid, epoch: u32) -> Option<[u8; 32]> {
1186        self.ledger.get(&(*album_id, epoch)).copied()
1187    }
1188
1189    /// The exporter device id recorded in the manifest (provenance: who exported).
1190    pub fn exporter_device(&self) -> Uuid {
1191        self.core.exporter_device
1192    }
1193
1194    /// The `(asset_id, head_hash)` provenance heads the artifact carries — the same list
1195    /// [`restore`](Self::restore) reconciles against local state. Exposed so a chain-aware
1196    /// consumer (LAN peering) can decide *forward-update vs. stale* per asset
1197    /// before restoring, rather than treating every differing head as an opaque conflict.
1198    pub fn provenance_heads(&self) -> &[(Uuid, Hash32)] {
1199        &self.core.provenance_heads
1200    }
1201
1202    /// The full provenance chain (oldest first) the artifact carries for `asset_id`, decoded
1203    /// from its `provenance/{asset_id}` entry. `None` when the artifact carries no such asset.
1204    ///
1205    /// Peering walks this chain to distinguish a **forward** artifact (whose chain contains the
1206    /// receiver's current head as an ancestor — safe to adopt) from a **stale** one (whose head
1207    /// the receiver has already superseded — quarantined, never applied). The per-entry content
1208    /// hashes were already verified by [`open`](Self::open), so the bytes here are authentic.
1209    pub fn provenance_chain(
1210        &self,
1211        asset_id: &Uuid,
1212    ) -> Result<Option<Vec<ProvenanceRecord>>, BackupError> {
1213        match self.files.get(&format!("provenance/{asset_id}")) {
1214            Some(bytes) => {
1215                let chain: Vec<ProvenanceRecord> =
1216                    cbor::from_slice(bytes).map_err(|e| BackupError::Format(e.to_string()))?;
1217                Ok(Some(chain))
1218            }
1219            None => Ok(None),
1220        }
1221    }
1222}
1223
1224/// Decode every `authority/{album_id}` entry the manifest lists (the manifest is authenticated
1225/// by this point, so a file the manifest does not name is ignored, never trusted), and refuse a
1226/// ledger filed under the wrong album or whose admin signature chain does not re-verify.
1227fn load_authorities(
1228    core: &ManifestCore,
1229    files: &BTreeMap<String, Vec<u8>>,
1230) -> Result<BTreeMap<Uuid, SignedEpochLedger>, BackupError> {
1231    let mut out = BTreeMap::new();
1232    for entry in &core.entries {
1233        let Some(album) = entry.path.strip_prefix("authority/") else {
1234            continue;
1235        };
1236        let album_id = Uuid::parse_str(album)
1237            .map_err(|_| BackupError::Format(format!("bad authority entry {}", entry.path)))?;
1238        let bytes = files
1239            .get(&entry.path)
1240            .ok_or_else(|| BackupError::Corrupt(format!("missing entry {}", entry.path)))?;
1241        let ledger: SignedEpochLedger =
1242            cbor::from_slice(bytes).map_err(|e| BackupError::Format(e.to_string()))?;
1243        if ledger.album_id != album_id {
1244            return Err(BackupError::Auth(
1245                "authority ledger filed under another album",
1246            ));
1247        }
1248        if ReferenceAuthority::from_ledger(&ledger, &BTreeSet::new()).is_none() {
1249            return Err(BackupError::Auth(
1250                "authority ledger failed admin-chain verification",
1251            ));
1252        }
1253        tracing::debug!(
1254            album_id = %album_id,
1255            epochs = ledger.entries.len(),
1256            "backup: album authority ledger verified"
1257        );
1258        out.insert(album_id, ledger);
1259    }
1260    Ok(out)
1261}
1262
1263/// Decode every `docs/{kind}/{doc_id}` entry the (authenticated) manifest lists, refusing one
1264/// whose path is malformed or whose sealing AMK the ledger does not escrow.
1265fn load_docs(
1266    core: &ManifestCore,
1267    files: &BTreeMap<String, Vec<u8>>,
1268    ledger: &BTreeMap<(Uuid, u32), [u8; 32]>,
1269) -> Result<Vec<BackupDoc>, BackupError> {
1270    let mut out = Vec::new();
1271    for entry in &core.entries {
1272        let Some(rest) = entry.path.strip_prefix("docs/") else {
1273            continue;
1274        };
1275        let bad = || BackupError::Format(format!("bad doc entry {}", entry.path));
1276        let (kind, id) = rest.split_once('/').ok_or_else(bad)?;
1277        let kind = BackupDocKind::from_path_segment(kind).ok_or_else(bad)?;
1278        let doc_id = Uuid::parse_str(id).map_err(|_| bad())?;
1279        let bytes = files
1280            .get(&entry.path)
1281            .ok_or_else(|| BackupError::Corrupt(format!("missing entry {}", entry.path)))?;
1282        let body: DocEntry =
1283            cbor::from_slice(bytes).map_err(|e| BackupError::Format(e.to_string()))?;
1284        if !ledger.contains_key(&(body.album_id, body.amk_version)) {
1285            return Err(BackupError::AmkIncomplete(format!(
1286                "album {} epoch {} (doc {})",
1287                body.album_id, body.amk_version, entry.path
1288            )));
1289        }
1290        out.push(BackupDoc {
1291            kind,
1292            doc_id,
1293            album_id: body.album_id,
1294            amk_version: body.amk_version,
1295            sealed: body.sealed,
1296        });
1297    }
1298    tracing::debug!(docs = out.len(), "backup: label records loaded");
1299    Ok(out)
1300}
1301
1302#[cfg(test)]
1303mod tests;