1use 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
53pub const WRAP_PARAMS: Argon2Params = Argon2Params {
67 mem_kib: 256 * 1024,
68 t_cost: 3,
69 p_cost: 1,
70};
71
72pub trait CiphertextSource: std::fmt::Debug + Send + Sync {
80 fn size(&self) -> u64;
83
84 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#[derive(Debug, Clone)]
101pub struct BackupAsset {
102 pub album_id: Uuid,
104 pub asset_id: Uuid,
106 pub ciphertext: Arc<dyn CiphertextSource>,
110 pub metadata_blob: Vec<u8>,
112 pub create_metadata_blob: Vec<u8>,
118 pub provenance: Vec<ProvenanceRecord>,
120 pub receipts: Vec<u8>,
124 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
141pub enum BackupDocKind {
142 Album,
144 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#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct BackupDoc {
172 pub kind: BackupDocKind,
174 pub doc_id: Uuid,
176 pub album_id: Uuid,
178 pub amk_version: u32,
180 pub sealed: Vec<u8>,
182}
183
184#[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
193pub struct BackupInput {
195 pub assets: Vec<BackupAsset>,
197 pub amks: BTreeMap<(Uuid, u32), [u8; 32]>,
199 pub authorities: BTreeMap<Uuid, SignedEpochLedger>,
204 pub docs: Vec<BackupDoc>,
207 pub attestation_key_pins: Vec<u8>,
212 pub exporter_device: Uuid,
214 pub source_library_version: String,
216 pub export_timestamp: String,
218}
219
220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
222struct EntryRef {
223 path: String,
224 hash: Hash32,
225 size: u64,
226}
227
228#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
251struct AmkLedger {
252 entries: Vec<(Uuid, u32, [u8; 32])>,
254}
255
256const 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
274const TAR_BLOCK: u64 = 512;
278
279fn tar_io(e: &io::Error) -> BackupError {
280 BackupError::Format(format!("writing the artifact: {e}"))
281}
282
283fn 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
307fn 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
353struct 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
398fn 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
440fn 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
467pub 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#[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
512enum Payload<'a> {
515 Bytes(Cow<'a, [u8]>),
516 Ciphertext {
517 source: &'a dyn CiphertextSource,
518 hash: Hash32,
519 },
520}
521
522fn 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 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 let mut assets: Vec<&BackupAsset> = input.assets.iter().collect();
563 assets.sort_by_key(|a| (a.album_id, a.asset_id));
564
565 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 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 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 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 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 if !a.receipts.is_empty() {
665 asset_entries.push((
666 format!("receipts/{}", a.asset_id),
667 Cow::Borrowed(&a.receipts),
668 ));
669 }
670 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 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 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 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
766pub 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
780pub 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#[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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
846pub enum RestoreMode {
847 Preview,
849 DryRun,
851 Commit,
853}
854
855#[derive(Debug, Clone)]
857pub struct RestoredAsset {
858 pub album_id: Uuid,
860 pub asset_id: Uuid,
862 pub plaintext: Vec<u8>,
864 pub metadata_blob: Vec<u8>,
866 pub create_metadata_blob: Vec<u8>,
871 pub provenance: Vec<ProvenanceRecord>,
873 pub receipts: Vec<u8>,
876 pub attestations: Vec<u8>,
879}
880
881#[derive(Debug, Default)]
883pub struct RestoreReport {
884 pub verified: usize,
886 pub would_add: Vec<Uuid>,
888 pub identical: Vec<Uuid>,
890 pub conflicts: Vec<Uuid>,
892 pub applied: Vec<RestoredAsset>,
894}
895
896pub 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 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 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 if !exporter_pub.verify(&core_bytes, &manifest.exporter_sig) {
937 return Err(BackupError::Auth("MANIFEST exporter signature invalid"));
938 }
939 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 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 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 let authorities = load_authorities(&manifest.core, &files)?;
970
971 let docs = load_docs(&manifest.core, &files, &ledger)?;
974
975 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 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 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 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 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 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 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 let receipts = self
1084 .files
1085 .get(&format!("receipts/{asset_id}"))
1086 .cloned()
1087 .unwrap_or_default();
1088 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 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 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 pub fn authority_ledgers(&self) -> &BTreeMap<Uuid, SignedEpochLedger> {
1166 &self.authorities
1167 }
1168
1169 pub fn docs(&self) -> &[BackupDoc] {
1173 &self.docs
1174 }
1175
1176 pub fn attestation_key_pins(&self) -> Option<&[u8]> {
1181 self.attestation_key_pins.as_deref()
1182 }
1183
1184 pub fn amk(&self, album_id: &Uuid, epoch: u32) -> Option<[u8; 32]> {
1186 self.ledger.get(&(*album_id, epoch)).copied()
1187 }
1188
1189 pub fn exporter_device(&self) -> Uuid {
1191 self.core.exporter_device
1192 }
1193
1194 pub fn provenance_heads(&self) -> &[(Uuid, Hash32)] {
1199 &self.core.provenance_heads
1200 }
1201
1202 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
1224fn 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
1263fn 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;