capsule_library/lifecycle/backup.rs
1//! The portable backup artifact round-trip — the only `lifecycle` file that reaches
2//! [`capsule_core::backup`].
3
4use std::collections::{BTreeMap, BTreeSet};
5use std::fs;
6use std::path::Path;
7use std::sync::Arc;
8
9use capsule_core::backup::{
10 self, BackupArtifact, BackupAsset, BackupDoc, BackupDocKind, BackupInput, RestoreMode,
11 VerifyOutcome as RecoveryVerdict,
12};
13use capsule_core::crypto::authority::Authority;
14use capsule_core::crypto::encryption::{blob_ciphertext_hash, blob_nonce, open_blob};
15use capsule_core::crypto::hash::{self, Hash32};
16use capsule_core::crypto::keys::albumstore::{AlbumStore, AmkRow, PersistedAuthority};
17use capsule_core::crypto::keys::{Amk, HybridVerifyingKey};
18#[cfg(any(test, feature = "test-support"))]
19use capsule_core::crypto::primitives::Argon2Params;
20use capsule_core::crypto::primitives::{CRYPTO_SUITE_ID, DeviceTier};
21use capsule_core::crypto::provenance::{AssetManifest, ProvenanceChain};
22use capsule_core::crypto::pwkdf::WrappedSecret;
23use capsule_core::metadata::crdt::Lww;
24use capsule_core::sidecar::sidecar_v1::{SIDECAR_SCHEMA_V1, SidecarV1};
25use capsule_core::sidecar::{ALBUM_DOC_SCHEMA_V1, AlbumDocV1, STACK_DOC_SCHEMA_V1, StackDocV1};
26use jiff::Timestamp;
27use uuid::Uuid;
28
29use super::album::{read_doc_file, stack_doc_path};
30use super::{AssetState, LifecycleError, Result, StackPlacement, Workspace, now_rfc3339};
31use crate::album_store::AlbumStoreFile;
32
33/// Display name given to an album that arrives only as escrowed keys in a backup artifact. An
34/// artifact that carries the album's label record replaces it with the album's own name once
35/// that record is merged; only an artifact exported before the records existed leaves it.
36const RECOVERED_ALBUM_NAME: &str = "Recovered album";
37
38/// The assets a peer's delta artifact is cut from ([`Workspace::peer_export`]).
39#[derive(Debug, Clone)]
40pub struct PeerExport {
41 /// Every managed asset, as a backup artifact carries it.
42 pub assets: Vec<BackupAsset>,
43 /// The AMK of each `(album, epoch)` an asset is sealed under.
44 pub amks: BTreeMap<(Uuid, u32), [u8; 32]>,
45}
46
47impl Workspace {
48 /// Wrap this account's master key under `recovery_secret` into the escrow blob a client
49 /// stores server-side (`PUT /backup/escrow`; driven from the SDK by
50 /// `capsule_sdk::recovery`).
51 ///
52 /// The master key **never leaves this workspace**: the raw bytes are handed straight to
53 /// [`backup::escrow_master_key`] and what comes back out is the passphrase-wrapped blob.
54 /// That is the whole reason this verb lives here rather than a `master_key_bytes()`
55 /// accessor — an FFI surface that could read the master key would be a far larger hazard
56 /// than one that can only mint an escrow of it.
57 ///
58 /// `recovery_secret` is the ≥128-bit secret shown to the user exactly once
59 /// (`capsule_sdk::recovery::MintedSecret`); `tier` selects the Argon2id cost, which is
60 /// recorded in the blob so any device can unwrap it.
61 #[tracing::instrument(skip_all, fields(?tier))]
62 pub fn escrow_master_key(
63 &self,
64 recovery_secret: &[u8],
65 tier: DeviceTier,
66 ) -> Result<WrappedSecret> {
67 let blob =
68 backup::escrow_master_key(self.account.master.as_bytes(), recovery_secret, tier)?;
69 tracing::info!("minted a master-key escrow blob under a fresh recovery secret");
70 Ok(blob)
71 }
72
73 /// This account's user identity key sealed under its master key — the blob a new device
74 /// passes to [`create_from_master`](Self::create_from_master) beside the recovered master
75 /// key, so it opens as the same account under the same identity the server has pinned.
76 ///
77 /// Like [`escrow_master_key`](Self::escrow_master_key), the private key never leaves the
78 /// workspace in the clear: only the holder of the master key can open what this returns.
79 pub fn sealed_identity(&self) -> Vec<u8> {
80 tracing::debug!("sealed the user identity key under the master key");
81 self.account.sealed_identity()
82 }
83
84 /// Local, network-free check that `recovery_secret` still opens `blob` **to this device's
85 /// master key** — the derived-tag compare that backs the recovery verification cadence.
86 ///
87 /// Delegates wholesale to [`backup::verify_recovery_secret`]; nothing is compared here, and
88 /// no key bytes are surfaced either way. The stale-cache rule (refresh the blob once before
89 /// recording a genuine failure) belongs to the networked caller, not to this predicate.
90 pub fn verify_escrow(&self, blob: &WrappedSecret, recovery_secret: &[u8]) -> RecoveryVerdict {
91 backup::verify_recovery_secret(blob, recovery_secret, self.account.master.as_bytes())
92 }
93
94 /// The current provenance head hash for each managed asset (for backup reconciliation),
95 /// and for each purged one the head of its kept chain, its final `delete`. A purged asset
96 /// is held at that head, so an import or a peer offer never reads it as absent and
97 /// re-applies an older copy as new.
98 pub fn local_heads(&self) -> BTreeMap<Uuid, Hash32> {
99 let purged = self
100 .purged
101 .iter()
102 .filter_map(|(id, chain)| chain.head().map(|head| (*id, head)));
103 self.assets
104 .iter()
105 .filter_map(|(id, a)| a.chain.head().map(|h| (*id, h)))
106 .chain(purged)
107 .collect()
108 }
109
110 /// Export every managed asset to a portable backup artifact.
111 ///
112 /// The AMK ledger is wrapped at the production Argon2id cost
113 /// ([`backup::WRAP_PARAMS`]) and there is no way to ask for another: this method takes no
114 /// cost argument and [`backup::export`] takes none either, so no caller reachable from a
115 /// production build can write a brute-forceable artifact.
116 #[tracing::instrument(skip_all, fields(out = %out.display()))]
117 pub fn export_backup(&self, out: &Path, passphrase: &[u8]) -> Result<()> {
118 let input = self.backup_input()?;
119 write_artifact(out, |w| {
120 backup::export_to(&input, passphrase, self.device_signer.as_ref(), w)
121 })
122 }
123
124 /// As [`export_backup`](Self::export_backup) but with an explicit Argon2id cost for the
125 /// artifact's wrap key.
126 ///
127 /// The cost is recorded in the artifact, so [`import_backup`](Self::import_backup)
128 /// reproduces the wrap key from what it reads rather than from a constant: exporting cheaply
129 /// makes *both* legs of a backup round trip cheap, and no import-side entry point is needed.
130 ///
131 /// **Not in a production build.** Compiled only under `cfg(test)` or the non-default
132 /// `test-support` feature, because a weak cost here is a brute-forceable backup and nothing
133 /// downstream re-checks it — the same reason
134 /// [`escrow_master_key`](Self::escrow_master_key) takes a closed `DeviceTier` rather than
135 /// raw parameters.
136 #[cfg(any(test, feature = "test-support"))]
137 #[tracing::instrument(skip_all, fields(out = %out.display(), ?params))]
138 pub fn export_backup_with_params(
139 &self,
140 out: &Path,
141 passphrase: &[u8],
142 params: Argon2Params,
143 ) -> Result<()> {
144 let input = self.backup_input()?;
145 write_artifact(out, |w| {
146 backup::export_with_params_to(
147 &input,
148 passphrase,
149 params,
150 self.device_signer.as_ref(),
151 w,
152 )
153 })
154 }
155
156 /// Every managed asset as a backup artifact carries it, with the album key each one is
157 /// sealed under: what a peer's delta artifact is cut from
158 /// (`capsule_sdk::peering::DeltaExport`). The same assets [`export_backup`](Self::export_backup)
159 /// writes, without the library-wide records (album authorities, label records, attestation
160 /// pins) a peer delta does not carry.
161 ///
162 /// # Errors
163 ///
164 /// When an asset's upload bundle cannot be rebuilt or its evidence logs cannot be read: a
165 /// delta silently missing an asset is not offered.
166 #[tracing::instrument(skip_all)]
167 pub fn peer_export(&self) -> Result<PeerExport> {
168 let export = self.backup_assets()?;
169 tracing::debug!(
170 assets = export.assets.len(),
171 epochs = export.amks.len(),
172 "backup: assets collected for a peer delta"
173 );
174 Ok(export)
175 }
176
177 /// Everything the artifact needs about this library, collected once so both export entry
178 /// points read the same state rather than each walking the library themselves.
179 fn backup_input(&self) -> Result<BackupInput> {
180 let PeerExport { assets, mut amks } = self.backup_assets()?;
181
182 // Each exported album's public authority. Only the reference ledger travels: an MLS
183 // authority's exported state holds the group's private secrets, which a backup must not
184 // escrow, so such an album exports unverifiable until its ledger has a public form.
185 let mut authorities = BTreeMap::new();
186 for album_id in amks.keys().map(|(album, _)| *album) {
187 match self.authorities.get(&album_id) {
188 Some(Authority::Reference(a)) => {
189 authorities.insert(album_id, a.to_ledger());
190 }
191 Some(_) => tracing::warn!(
192 album_id = %album_id,
193 "backup: album authority is not a reference ledger; exported without it"
194 ),
195 None => tracing::debug!(
196 album_id = %album_id,
197 "backup: album holds no authority; exported without one"
198 ),
199 }
200 }
201
202 let docs = self.backup_docs(&mut amks)?;
203
204 // The pinned attestation-key history of every server this library pushed to. Like the
205 // evidence logs, a pin that exists and cannot be read or decoded fails the export: an
206 // artifact silently without it restores a library that trusts its servers' next
207 // publication on first use again.
208 let attestation_key_pins = crate::library::read_attestation_key_pins(&self.root)
209 .map_err(backup::BackupError::from)?
210 .unwrap_or_default();
211
212 Ok(BackupInput {
213 assets,
214 amks,
215 authorities,
216 docs,
217 attestation_key_pins,
218 exporter_device: self.account.device.device_id,
219 source_library_version: "1".into(),
220 export_timestamp: now_rfc3339(),
221 })
222 }
223
224 /// Every managed asset as the artifact carries it, and the AMK of each `(album, epoch)` one
225 /// is sealed under.
226 fn backup_assets(&self) -> Result<PeerExport> {
227 let mut assets = Vec::new();
228 let mut amks: BTreeMap<(Uuid, u32), [u8; 32]> = BTreeMap::new();
229
230 for asset in self.assets.values() {
231 // The per-asset re-encrypt (plaintext → the ciphertext the manifest's recorded
232 // nonce prefix pins) is `verified_original`'s job — one copy of that crypto, shared
233 // with `capsule push`'s upload bundle. It also self-checks the re-derived
234 // ciphertext against the manifest's content address. The artifact carries the
235 // whole chain and the latest metadata blob, which the head binds, so it is read
236 // against the head rather than through the upload bundle, which carries the create.
237 let album = self.album(&asset.album_id)?;
238 let head = &asset
239 .chain
240 .records()
241 .last()
242 .expect("provenance chain is never empty")
243 .manifest
244 .core;
245 let original = self.verified_original(asset, album, head)?;
246 let epoch = head.amk_version.0;
247 amks.insert((asset.album_id, epoch), album.amks[&epoch]);
248 // The asset's evidence logs — custody receipts and signed storage attestations — if
249 // the client has persisted them beside the chain. A log that exists and cannot be
250 // read fails the export: an artifact silently missing its evidence is the loss the
251 // artifact exists to prevent.
252 let capture_utc = Some(asset.capture_utc);
253 let receipts = read_evidence_log(&crate::library::receipts_path(
254 &self.root,
255 &asset.asset_id,
256 capture_utc,
257 ))?;
258 let attestations = read_evidence_log(&crate::library::attestations_path(
259 &self.root,
260 &asset.asset_id,
261 capture_utc,
262 ))?;
263 let create_metadata_blob = self.superseded_create_metadata_blob(asset)?;
264 assets.push(BackupAsset {
265 album_id: asset.album_id,
266 asset_id: asset.asset_id,
267 // Export the exact sealed blob the manifest committed to (re-sealing would draw
268 // a fresh nonce and break the `metadata_blob_hash` content address).
269 metadata_blob: asset.metadata_blob.clone(),
270 create_metadata_blob,
271 // The original as a source, not its bytes: the export streams it into the
272 // artifact one STREAM chunk at a time, as a push does, so exporting never holds
273 // the library's ciphertext. `verified_original` has just verified it re-derives
274 // to the manifest's address; the export checks the bytes it writes again.
275 ciphertext: Arc::new(original),
276 provenance: asset.chain.records().to_vec(),
277 receipts,
278 attestations,
279 });
280 }
281 Ok(PeerExport { assets, amks })
282 }
283
284 /// The sealed blob `asset`'s `create` binds, when an edit has replaced it as the asset's
285 /// current blob: the copy kept beside the chain, which an upload of the create needs and the
286 /// head's blob cannot stand in for. Empty when the create binds the current blob or none.
287 ///
288 /// A library edited before it kept that copy has nothing that answers the create; the asset
289 /// exports without it, as it did before, and a warning says its create stays unuploadable.
290 ///
291 /// # Errors
292 ///
293 /// [`LifecycleError::Io`] when the kept copy exists and cannot be read: like the evidence
294 /// logs, an artifact silently missing it would lose the only bytes that upload the create.
295 fn superseded_create_metadata_blob(&self, asset: &AssetState) -> Result<Vec<u8>> {
296 let bound = asset
297 .chain
298 .records()
299 .first()
300 .expect("provenance chain is never empty")
301 .manifest
302 .core
303 .metadata_blob_hash;
304 let Some(bound) = bound else {
305 return Ok(Vec::new());
306 };
307 if blob_ciphertext_hash(&asset.metadata_blob) == bound {
308 return Ok(Vec::new());
309 }
310 match self.create_metadata_blob(asset, Some(bound)) {
311 Ok(kept) => {
312 tracing::debug!(
313 asset_id = %asset.asset_id,
314 bytes = kept.len(),
315 "backup: carrying the create's superseded metadata blob"
316 );
317 Ok(kept)
318 }
319 Err(LifecycleError::CreateMetadataSuperseded(_)) => {
320 tracing::warn!(
321 asset_id = %asset.asset_id,
322 "backup: no kept copy answers the create's metadata blob; exported without it"
323 );
324 Ok(Vec::new())
325 }
326 Err(e) => Err(e),
327 }
328 }
329
330 /// The label records that ride the artifact: every exported album's record (so a restore
331 /// recovers the album's name and labels) and the record of every stack an exported asset
332 /// belongs to that has one. Each is sealed under its album's current-epoch AMK, which is
333 /// added to `amks` so the ledger escrows it.
334 ///
335 /// A record that cannot be read, verified or sealed is left out with a warning rather than
336 /// failing the export, mirroring [`absorb_recovered_docs`](Self::absorb_recovered_docs): the
337 /// assets and keys are what a backup must carry, and a missing record costs a name or a
338 /// label, never data. An album left out restores as `Recovered album`.
339 fn backup_docs(&self, amks: &mut BTreeMap<(Uuid, u32), [u8; 32]>) -> Result<Vec<BackupDoc>> {
340 let mut docs = Vec::new();
341 let mut skipped = 0usize;
342 let current_amk = |album_id: Uuid, amks: &mut BTreeMap<(Uuid, u32), [u8; 32]>| {
343 let album = self.album(&album_id)?;
344 let amk = album.amks[&album.current_epoch];
345 amks.insert((album_id, album.current_epoch), amk);
346 Ok::<_, LifecycleError>((album.current_epoch, Amk::from_bytes(amk)))
347 };
348
349 let albums: BTreeSet<Uuid> = amks.keys().map(|(album, _)| *album).collect();
350 for album_id in albums {
351 let sealed = self.album_doc(&album_id).and_then(|doc| {
352 let (epoch, amk) = current_amk(album_id, amks)?;
353 Ok((epoch, doc.seal(&amk)?))
354 });
355 match sealed {
356 Ok((epoch, sealed)) => docs.push(BackupDoc {
357 kind: BackupDocKind::Album,
358 doc_id: album_id,
359 album_id,
360 amk_version: epoch,
361 sealed,
362 }),
363 Err(e) => {
364 skipped += 1;
365 tracing::warn!(
366 album_id = %album_id,
367 error = %e,
368 "backup: album label record left out of the export"
369 );
370 }
371 }
372 }
373
374 let stacks: BTreeSet<Uuid> = self
375 .assets
376 .values()
377 .filter_map(|a| a.sidecar.stack_membership.get().cloned().flatten())
378 .map(|m| m.stack_id)
379 .collect();
380 for stack_id in stacks {
381 let sealed = read_doc_file(&stack_doc_path(&self.root, &stack_id)).and_then(|file| {
382 if file.is_none() {
383 return Ok(None);
384 }
385 let doc = self.stack_doc(stack_id)?;
386 let (epoch, amk) = current_amk(doc.album_id, amks)?;
387 Ok(Some((doc.album_id, epoch, doc.seal(&amk)?)))
388 });
389 match sealed {
390 Ok(None) => {}
391 Ok(Some((album_id, epoch, sealed))) => docs.push(BackupDoc {
392 kind: BackupDocKind::Stack,
393 doc_id: stack_id,
394 album_id,
395 amk_version: epoch,
396 sealed,
397 }),
398 Err(e) => {
399 skipped += 1;
400 tracing::warn!(
401 stack_id = %stack_id,
402 error = %e,
403 "backup: stack label record left out of the export"
404 );
405 }
406 }
407 }
408 tracing::debug!(
409 docs = docs.len(),
410 skipped,
411 "backup: label records sealed for export"
412 );
413 Ok(docs)
414 }
415
416 /// Open every label record a verified artifact carries with the AMK its ledger escrows, and
417 /// merge it into this library: an album's record brings back its name (and labels), so an
418 /// album new to this library is named as it was rather than `Recovered album`.
419 ///
420 /// The records are trusted on the artifact's own authentication — the manifest HMAC and the
421 /// exporter's signature cover each entry — and are re-signed here under this account's
422 /// identity key as they are merged. A record that does not open is skipped with a warning:
423 /// the assets and keys it travelled with are already restored, and its absence costs a
424 /// name, never data.
425 #[tracing::instrument(skip_all)]
426 fn absorb_recovered_docs(&mut self, artifact: &BackupArtifact) -> Result<()> {
427 let mut merged = 0usize;
428 for doc in artifact.docs() {
429 let Some(amk) = artifact.amk(&doc.album_id, doc.amk_version) else {
430 continue;
431 };
432 let amk = Amk::from_bytes(amk);
433 let outcome = match doc.kind {
434 BackupDocKind::Album => {
435 AlbumDocV1::open_sealed(&doc.sealed, &amk, &doc.doc_id, ALBUM_DOC_SCHEMA_V1)
436 .map_err(LifecycleError::from)
437 .and_then(|remote| self.merge_album_doc(&remote))
438 }
439 BackupDocKind::Stack => {
440 StackDocV1::open_sealed(&doc.sealed, &amk, &doc.doc_id, STACK_DOC_SCHEMA_V1)
441 .map_err(LifecycleError::from)
442 .and_then(|remote| self.merge_stack_doc(&remote))
443 }
444 };
445 match outcome {
446 Ok(()) => merged += 1,
447 Err(e) => tracing::warn!(
448 kind = ?doc.kind,
449 doc_id = %doc.doc_id,
450 error = %e,
451 "backup: label record not restored"
452 ),
453 }
454 }
455 tracing::info!(
456 merged,
457 carried = artifact.docs().len(),
458 "backup: label records restored"
459 );
460 Ok(())
461 }
462
463 /// This device's signing public key (the exporter key a peer verifies a backup against).
464 pub fn exporter_verifying_key(&self) -> HybridVerifyingKey {
465 self.device_signer.verifying_key()
466 }
467
468 /// Open a backup artifact and restore (commit) its assets into this workspace, writing
469 /// decrypted plaintext + provenance into the library. `exporter_pub` is the exporting
470 /// device's signing key (resolved from the user's device directory). Returns the count
471 /// of assets added.
472 #[tracing::instrument(skip_all, fields(archive = %archive.display()))]
473 pub fn import_backup(
474 &mut self,
475 archive: &Path,
476 passphrase: &[u8],
477 exporter_pub: &HybridVerifyingKey,
478 ) -> Result<usize> {
479 let bytes = fs::read(archive).map_err(|e| LifecycleError::Io(e.to_string()))?;
480 let artifact = BackupArtifact::open(&bytes, passphrase, exporter_pub)?;
481 let report = artifact.restore(RestoreMode::Commit, &self.local_heads())?;
482
483 // The pinned attestation-key history first: it is the one step that can refuse on the
484 // library's own state (a pin that diverges from the carried one), and a refusal must
485 // come before anything else is written. Folding it in is a union, so a later failure
486 // leaves a pin that only ever grew by keys this account had already pinned.
487 if let Some(carried) = artifact.attestation_key_pins() {
488 let outcome = crate::library::restore_attestation_key_pins(&self.root, carried)
489 .map_err(backup::BackupError::from)?;
490 tracing::info!(?outcome, "backup: attestation-key pin restored");
491 }
492
493 // Fold the artifact's escrowed AMKs into the durable keystore **before** writing any
494 // asset: this is the step that makes a keyless library whole again, and an asset on disk
495 // whose key was never persisted is exactly the failure the durable album keystore exists
496 // to prevent. An album already known keeps its write capability and authority and simply
497 // gains missing epochs; an unknown album lands read-only with the public authority the artifact carried, since
498 // a backup escrows content keys and the admin-signed ledger but no signing capability.
499 self.absorb_recovered_amks(&artifact)?;
500 // Then the albums' and stacks' label records, which need those keys to open: this is
501 // what names a recovered album.
502 self.absorb_recovered_docs(&artifact)?;
503
504 let mut added = 0;
505 for restored in &report.applied {
506 self.write_restored(restored, SidecarSource::StandIn)?;
507 added += 1;
508 }
509 tracing::info!(added, "backup: import complete");
510 Ok(added)
511 }
512
513 /// Write one asset a peer's delta artifact restored (`capsule_sdk::peering::PeerRestore`'s
514 /// `applied`) into this library: a new asset, or a forward update of one this library holds,
515 /// whose chain extends the local head.
516 ///
517 /// The asset's album, and the epoch its head manifest is sealed under, must already be
518 /// held: a peer delta carries no album authority or label record, so an asset of an album
519 /// this library does not hold would be one it could neither push nor export. A forward
520 /// update keeps the held asset's media path (its extension and date bucket) and stack
521 /// placement, so the original is rewritten in place, and keeps any evidence log this device
522 /// already holds over the peer's copy. The sidecar written is the one the peer's sealed
523 /// metadata blob carries, opened and verified, so the peer's metadata arrives and none of
524 /// what was held before its head is lost.
525 ///
526 /// # Errors
527 ///
528 /// [`LifecycleError::Purged`] for an asset this workspace purged,
529 /// [`LifecycleError::NotFound`] when the album or its epoch is not held, and
530 /// [`LifecycleError::RestoredMetadata`] when the sealed metadata does not stand (nothing is
531 /// written in either case), or the I/O, chain or index failure that stopped the write.
532 #[tracing::instrument(skip_all, fields(asset_id = %restored.asset_id, album_id = %restored.album_id))]
533 pub fn apply_peer_restored(&mut self, restored: &backup::RestoredAsset) -> Result<()> {
534 if self.purged.contains_key(&restored.asset_id) {
535 tracing::warn!(asset_id = %restored.asset_id, "peer: the asset was purged here; refusing to resurrect it");
536 return Err(LifecycleError::Purged(restored.asset_id));
537 }
538 let epoch = restored
539 .provenance
540 .last()
541 .ok_or_else(|| LifecycleError::Cbor("restored provenance is empty".into()))?
542 .manifest
543 .core
544 .amk_version
545 .0;
546 if !self.album(&restored.album_id)?.amks.contains_key(&epoch) {
547 tracing::warn!(
548 epoch,
549 "peer: the asset's album epoch is not held; not writing it"
550 );
551 return Err(LifecycleError::NotFound(format!(
552 "album {} epoch {epoch}",
553 restored.album_id
554 )));
555 }
556 let forward = self.assets.contains_key(&restored.asset_id);
557 self.write_restored(restored, SidecarSource::Sealed)?;
558 tracing::info!(forward, "peer: restored asset written");
559 Ok(())
560 }
561
562 /// Write a restored asset's original, signed artifacts, evidence logs and index rows, and
563 /// hold it in this workspace. An asset already held keeps its media path and stack.
564 fn write_restored(
565 &mut self,
566 restored: &backup::RestoredAsset,
567 source: SidecarSource,
568 ) -> Result<()> {
569 let head = &restored
570 .provenance
571 .last()
572 .ok_or_else(|| LifecycleError::Cbor("restored provenance is empty".into()))?
573 .manifest;
574 let held = self.assets.get(&restored.asset_id);
575 let mut chain = ProvenanceChain::new();
576 for rec in &restored.provenance {
577 chain
578 .append(rec.clone())
579 .map_err(|e| LifecycleError::Cbor(format!("restore chain: {e}")))?;
580 }
581 let sidecar = match source {
582 SidecarSource::Sealed => {
583 self.open_restored_sidecar(restored, head, held.map(|h| &h.sidecar))?
584 }
585 SidecarSource::StandIn => self.stand_in_sidecar(restored, head),
586 };
587 // Keep `capture_utc` and the sidecar's `capture_timestamp` in agreement: a reopened
588 // workspace derives an asset's media directory from that field. A new asset is filed
589 // under its sidecar's capture time (wall-clock "now" would file it under a month its
590 // own sidecar disagrees with); a held one keeps its own, so its original is rewritten
591 // where it already is.
592 let (capture_utc, ext, held_stack) = match held {
593 Some(held) => (held.capture_utc, held.ext.clone(), held.stack.clone()),
594 None => (
595 sidecar
596 .capture_timestamp
597 .parse::<Timestamp>()
598 .or_else(|_| head.core.timestamp.parse::<Timestamp>())
599 .map_or_else(|_| Timestamp::now().as_second(), Timestamp::as_second),
600 "bin".to_string(),
601 None,
602 ),
603 };
604 // The sidecar's signed `stack_membership` register is the durable placement, as a
605 // reopen reads it; an unwritten register keeps the placement already held.
606 let stack = match sidecar.stack_membership.get() {
607 Some(membership) => membership.as_ref().map(StackPlacement::from_membership),
608 None => held_stack,
609 };
610 let asset = AssetState {
611 asset_id: restored.asset_id,
612 album_id: restored.album_id,
613 ext,
614 capture_utc,
615 chain,
616 sidecar,
617 // The artifact preserves the exact sealed blob the manifest committed to.
618 metadata_blob: restored.metadata_blob.clone(),
619 stack,
620 };
621 // The evidence logs the artifact carried go back beside the chain, byte for byte —
622 // and **before** it: the chain on disk is what marks the asset present, and a later
623 // restore skips a present asset, so a crash between the two must leave the logs
624 // written and the asset absent (retried whole), never the reverse.
625 restore_evidence_log(
626 &crate::library::receipts_path(&self.root, &restored.asset_id, Some(capture_utc)),
627 &restored.receipts,
628 )?;
629 restore_evidence_log(
630 &crate::library::attestations_path(&self.root, &restored.asset_id, Some(capture_utc)),
631 &restored.attestations,
632 )?;
633 // The create's superseded metadata blob, for the same reason and in the same place: an
634 // upload of the create needs these bytes, and the chain must not land without them. A
635 // held asset's current blob is offered too: `write_asset_files` is about to overwrite
636 // it, and it may be the last copy that answers the create.
637 self.restore_create_metadata_blob(
638 &asset,
639 &restored.create_metadata_blob,
640 held.map(|h| h.metadata_blob.as_slice()),
641 )?;
642 self.write_asset_files(&asset, &restored.plaintext)?;
643 self.index_asset_with_original(&asset, restored.plaintext.len())?;
644 self.assets.insert(restored.asset_id, asset);
645 Ok(())
646 }
647
648 /// Keep the create's metadata blob at
649 /// [`create_metadata_blob_path`](Self::create_metadata_blob_path) before a restore writes
650 /// `asset` over whatever this workspace held. `carried` is the blob the artifact carried,
651 /// which already answers the create's `metadata_blob_hash`
652 /// ([`backup::RestoredAsset::create_metadata_blob`]); `held_current` is the current blob of
653 /// the asset this workspace already holds, if any.
654 ///
655 /// When the artifact carried none, the held current blob is kept instead if it answers the
656 /// create and the restored head replaces it: a never-edited asset updated by a peer that
657 /// edited it without keeping the create's blob (an older build, or an edit made before the
658 /// blob was kept) would otherwise lose the last copy that uploads its create. Nothing is
659 /// written when neither applies. A copy already on disk that answers the same hash holds the
660 /// same bytes and is left alone; one that does not is replaced.
661 fn restore_create_metadata_blob(
662 &self,
663 asset: &AssetState,
664 carried: &[u8],
665 held_current: Option<&[u8]>,
666 ) -> Result<()> {
667 let blob = if carried.is_empty() {
668 let bound = asset
669 .chain
670 .records()
671 .first()
672 .expect("provenance chain is never empty")
673 .manifest
674 .core
675 .metadata_blob_hash;
676 match (bound, held_current) {
677 (Some(bound), Some(current))
678 if !current.is_empty()
679 && current != asset.metadata_blob.as_slice()
680 && blob_ciphertext_hash(current) == bound =>
681 {
682 tracing::debug!(
683 asset_id = %asset.asset_id,
684 "backup: keeping the held blob the create binds before the restore replaces it"
685 );
686 current
687 }
688 _ => return Ok(()),
689 }
690 } else {
691 carried
692 };
693 let held = fs::read(self.create_metadata_blob_path_of(asset)).ok();
694 if held.is_some_and(|held| blob_ciphertext_hash(&held) == blob_ciphertext_hash(blob)) {
695 tracing::debug!(
696 asset_id = %asset.asset_id,
697 "backup: the create's metadata blob is already kept; keeping it"
698 );
699 return Ok(());
700 }
701 self.write_create_metadata_blob(asset, blob)
702 }
703
704 /// Merge a verified artifact's escrowed `(album_id, epoch, amk)` rows — and each album's
705 /// public authority ledger — into the durable album keystore, persist it, and re-apply it to
706 /// the live workspace so the recovered keys are usable in this session as well as the next.
707 ///
708 /// A ledger is adopted only by an album holding no authority ([`AlbumStore::merge_amks`]),
709 /// and an adopted ledger must re-verify against the epochs now held before anything is
710 /// persisted: an authority that would be dropped at the next open is refused here instead.
711 /// An authority the album already held is not re-checked — see [`merge_album`].
712 ///
713 /// [`AlbumStore::merge_amks`]: capsule_core::crypto::keys::albumstore::AlbumStore::merge_amks
714 #[tracing::instrument(skip_all)]
715 fn absorb_recovered_amks(&mut self, artifact: &BackupArtifact) -> Result<()> {
716 let rows = artifact.amk_rows();
717 if rows.is_empty() {
718 return Ok(());
719 }
720 let mut by_album: BTreeMap<Uuid, Vec<(Uuid, u32, [u8; 32])>> = BTreeMap::new();
721 for row in rows {
722 by_album.entry(row.0).or_default().push(row);
723 }
724
725 let mut store = self.album_store_snapshot()?;
726 let mut recovered_epochs = 0;
727 for (album_id, rows) in by_album {
728 let known = store.get(&album_id).is_some();
729 let name = store
730 .get(&album_id)
731 .map_or_else(|| RECOVERED_ALBUM_NAME.to_string(), |a| a.name.clone());
732 let carried = artifact
733 .authority_ledgers()
734 .get(&album_id)
735 .map(|ledger| PersistedAuthority::Reference(Box::new(ledger.clone())));
736 let carried_authority = carried.is_some();
737 let (added, authority_adopted) =
738 merge_album(&mut store, album_id, &name, rows, carried)?;
739 recovered_epochs += added;
740 tracing::info!(
741 album_id = %album_id,
742 known_album = known,
743 epochs_added = added,
744 carried_authority,
745 authority_adopted,
746 "backup: escrowed album keys absorbed into the keystore"
747 );
748 }
749 store.save(&self.root, &self.account.master)?;
750 self.apply_album_store(&store);
751 tracing::info!(
752 recovered_epochs,
753 "backup: album keystore updated from the artifact"
754 );
755 Ok(())
756 }
757
758 /// The signed sidecar a restored asset's sealed `metadata_blob` carries: bound to the
759 /// latest manifest of its chain that commits to a metadata blob, opened under the album key
760 /// of that manifest's epoch, decoded, and verified under the account's user IK, as
761 /// `apply_remote_entry` admits a server entry. The sidecar is adopted byte for byte, so the
762 /// blob kept beside it still round-trips to the committed hash.
763 ///
764 /// An empty blob is a library written before sealed metadata was durable: a held asset
765 /// keeps its own sidecar, and a new one gets a stand-in from the head manifest.
766 ///
767 /// # Errors
768 ///
769 /// [`LifecycleError::RestoredMetadata`] when the blob is not the one the chain commits to,
770 /// its epoch's key is not held, or it does not open, decode, verify or describe this asset.
771 fn open_restored_sidecar(
772 &self,
773 restored: &backup::RestoredAsset,
774 head: &AssetManifest,
775 held: Option<&SidecarV1>,
776 ) -> Result<SidecarV1> {
777 let refuse = |why: &str| {
778 tracing::warn!(
779 why,
780 "restore: the asset's sealed metadata does not stand; not writing it"
781 );
782 LifecycleError::RestoredMetadata(format!("asset {}: {why}", restored.asset_id))
783 };
784 let blob = restored.metadata_blob.as_slice();
785 if blob.is_empty() {
786 tracing::warn!(
787 held = held.is_some(),
788 "restore: the asset carries no sealed metadata blob; keeping what is held"
789 );
790 return Ok(match held {
791 Some(held) => held.clone(),
792 None => self.stand_in_sidecar(restored, head),
793 });
794 }
795 let Some(binding) = restored
796 .provenance
797 .iter()
798 .rev()
799 .map(|rec| &rec.manifest.core)
800 .find(|core| core.action.binds_metadata_blob())
801 else {
802 return Err(refuse(
803 "no manifest in its chain commits to a metadata blob",
804 ));
805 };
806 if binding.metadata_blob_hash != Some(blob_ciphertext_hash(blob)) {
807 return Err(refuse(
808 "the metadata blob is not the one its chain commits to",
809 ));
810 }
811 let epoch = binding.amk_version.0;
812 let Some(amk) = self.album(&restored.album_id)?.amks.get(&epoch).copied() else {
813 return Err(refuse(
814 "the album key of the metadata blob's epoch is not held",
815 ));
816 };
817 let Some(nonce) = blob_nonce(blob) else {
818 return Err(refuse("the metadata blob is truncated"));
819 };
820 let blob_key = Amk::from_bytes(amk).derive_blob_key(&restored.asset_id, &nonce);
821 let plaintext = open_blob(&blob_key, blob)
822 .map_err(|_| refuse("the metadata blob does not open under its album key"))?;
823 let sidecar = SidecarV1::from_canonical_slice(&plaintext, SIDECAR_SCHEMA_V1)
824 .map_err(|_| refuse("the sealed sidecar does not decode"))?;
825 if !sidecar.verify(&self.user_ik_public()) {
826 return Err(refuse("the sealed sidecar's signature does not verify"));
827 }
828 if sidecar.uuid != restored.asset_id
829 || sidecar.hash != hash::hash_bytes(&restored.plaintext)
830 {
831 return Err(refuse("the sealed sidecar describes another original"));
832 }
833 tracing::debug!(epoch, "restore: sealed sidecar opened and verified");
834 Ok(sidecar)
835 }
836
837 /// A stand-in sidecar from the head manifest, for an asset whose library never persisted
838 /// a sealed metadata blob: no user metadata survives, because none was carried.
839 fn stand_in_sidecar(
840 &self,
841 restored: &backup::RestoredAsset,
842 head: &AssetManifest,
843 ) -> SidecarV1 {
844 let mut sidecar = SidecarV1 {
845 sidecar_schema: SIDECAR_SCHEMA_V1,
846 crypto_suite_id: CRYPTO_SUITE_ID,
847 uuid: restored.asset_id,
848 hash: hash::hash_bytes(&restored.plaintext),
849 capture_timestamp: head.core.timestamp.clone(),
850 capture_timestamp_user: Lww::new(),
851 import_timestamp: now_rfc3339(),
852 content_type: "application/octet-stream".into(),
853 dimensions: None,
854 lqip: None,
855 tags_user: Default::default(),
856 tags_ai: Default::default(),
857 caption: Default::default(),
858 rating: Default::default(),
859 stack_membership: Lww::new(),
860 regions: Default::default(),
861 cull: Lww::new(),
862 hidden: Lww::new(),
863 camera_id: None,
864 device_id: head.core.created_by_device,
865 session_id: Uuid::now_v7(),
866 gps: None,
867 gps_user: Lww::new(),
868 // Mirror the head manifest's prior (the sealing invariant for its action).
869 provenance_chain_hash: head.core.prior_provenance_hash,
870 unknown: BTreeMap::new(),
871 signature: None,
872 };
873 sidecar.sign(&self.account.user_ik);
874 sidecar
875 }
876}
877
878/// Where [`Workspace::write_restored`] takes a restored asset's sidecar from.
879#[derive(Debug, Clone, Copy)]
880enum SidecarSource {
881 /// The sealed metadata blob, opened and verified under this account's user IK: a peer of
882 /// the same account sealed it, so its metadata is facts this library adopts.
883 Sealed,
884 /// A stand-in from the head manifest, re-signed by this library: a backup may come from
885 /// another account, whose sidecar signature this account cannot vouch for.
886 StandIn,
887}
888
889/// Merge one album's escrowed AMK `rows` and the authority the artifact `carried` into `store`.
890/// Returns the epochs added and whether the carried authority was adopted.
891///
892/// Only an **adopted** authority is re-verified, and a failure there refuses the import (the
893/// ledger already re-verified in [`BackupArtifact::open`], so this is defensive). An authority
894/// the album already held is left alone, unchecked: an unusable held authority costs the album
895/// verification and writes, never read access (as in `Workspace::apply_album_store`), so it must
896/// not stop the artifact's content keys from being recovered.
897fn merge_album(
898 store: &mut AlbumStore,
899 album_id: Uuid,
900 name: &str,
901 rows: Vec<AmkRow>,
902 carried: Option<PersistedAuthority>,
903) -> Result<(usize, bool)> {
904 let had_authority = store.get(&album_id).is_some_and(|a| a.authority.is_some());
905 let carried_authority = carried.is_some();
906 let added = store.merge_amks(album_id, name, rows, carried);
907 let adopted = carried_authority && !had_authority;
908 if adopted {
909 let persisted = store
910 .get(&album_id)
911 .expect("merge_amks leaves the album in the store");
912 if let Some(authority) = &persisted.authority {
913 authority.restore(album_id, &persisted.held_epochs())?;
914 }
915 }
916 Ok((added, adopted))
917}
918
919/// An evidence log's bytes for the artifact: empty when the asset has none, an error when one
920/// exists and cannot be read.
921fn read_evidence_log(path: &Path) -> Result<Vec<u8>> {
922 match fs::read(path) {
923 Ok(bytes) => Ok(bytes),
924 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
925 Err(e) => Err(LifecycleError::Io(format!(
926 "evidence log {}: {e}",
927 path.display()
928 ))),
929 }
930}
931
932/// Stream an artifact into `out` through `export`, atomically.
933///
934/// The artifact is written to a sibling temporary file and renamed over `out` only once it is
935/// complete and synced. A streamed export can fail part-way — an original that changed on disk
936/// since its manifest was signed, a full disk — and must then leave neither a truncated artifact
937/// nor a clobbered earlier backup at `out`: the temporary file is removed and `out` is untouched.
938fn write_artifact(
939 out: &Path,
940 export: impl FnOnce(&mut dyn std::io::Write) -> std::result::Result<u64, backup::BackupError>,
941) -> Result<()> {
942 let tmp = crate::library::tmp_path(out);
943 let written = stream_then_rename(&tmp, out, export).inspect_err(|e| {
944 tracing::error!(
945 out = %out.display(),
946 error = %e,
947 "backup: export failed; discarding the partial artifact"
948 );
949 let _ = fs::remove_file(&tmp);
950 })?;
951 tracing::info!(out = %out.display(), bytes = written, "backup: export complete");
952 Ok(())
953}
954
955/// The fallible body of [`write_artifact`]: export into `tmp`, sync it, rename it over `out`.
956fn stream_then_rename(
957 tmp: &Path,
958 out: &Path,
959 export: impl FnOnce(&mut dyn std::io::Write) -> std::result::Result<u64, backup::BackupError>,
960) -> Result<u64> {
961 let io = |e: std::io::Error| LifecycleError::Io(format!("backup {}: {e}", out.display()));
962 let mut writer = std::io::BufWriter::new(fs::File::create(tmp).map_err(io)?);
963 let written = export(&mut writer)?;
964 let file = writer.into_inner().map_err(|e| io(e.into_error()))?;
965 file.sync_all().map_err(io)?;
966 fs::rename(tmp, out).map_err(io)?;
967 Ok(written)
968}
969
970/// Write an evidence log a restore carried back to `path`, verbatim.
971///
972/// Nothing is written when the artifact carried none. A log already on disk is kept, not
973/// overwritten: a restore only adds assets absent locally, so one there is a stray, but it is
974/// still evidence, and the artifact's copy stays in the artifact.
975///
976/// The log is staged in a temporary sibling, flushed, and renamed into place, so a crash leaves
977/// either no log or the whole one — never a torn log a retried restore would then keep.
978fn restore_evidence_log(path: &Path, bytes: &[u8]) -> Result<()> {
979 if bytes.is_empty() {
980 return Ok(());
981 }
982 if path.exists() {
983 tracing::warn!(
984 log = %path.display(),
985 "backup: an evidence log is already on disk; keeping it over the artifact's copy"
986 );
987 return Ok(());
988 }
989 if let Some(parent) = path.parent() {
990 fs::create_dir_all(parent).map_err(|e| LifecycleError::Io(e.to_string()))?;
991 }
992 let io =
993 |e: std::io::Error| LifecycleError::Io(format!("evidence log {}: {e}", path.display()));
994 let tmp = crate::library::tmp_path(path);
995 {
996 let mut file = fs::File::create(&tmp).map_err(io)?;
997 std::io::Write::write_all(&mut file, bytes).map_err(io)?;
998 file.sync_all().map_err(io)?;
999 }
1000 fs::rename(&tmp, path).map_err(io)?;
1001 tracing::debug!(log = %path.display(), bytes = bytes.len(), "backup: evidence log restored");
1002 Ok(())
1003}
1004
1005#[cfg(test)]
1006mod tests;