Skip to main content

capsule_core/crypto/keys/
albumstore.rs

1//! The durable album-key store: every album's AMK ledger, write-tier + admin signing seeds,
2//! and attested authority state, sealed at rest under the account master key.
3//!
4//! Album keys used to be **session-scoped** — minted per `Workspace` and dropped on close — so a
5//! reopened library could neither decrypt nor write its own prior assets. This module is the
6//! durable half of the [key chain](https://docs/design/cryptography/keys/#key-chain) the
7//! keystore (`Account`) already provides for device identity keys: `AccountFile` persists
8//! the master key (passphrase-wrapped) and the device private keys (master-sealed);
9//! [`AlbumStore`] persists everything below the master key that an album needs.
10//!
11//! ## On-disk format
12//!
13//! One file, `{root}/.library/albums.cbor`:
14//!
15//! ```text
16//! MasterKey::seal( canonical_cbor(AlbumStore) )     # nonce(12) ‖ AES-256-GCM(ct+tag)
17//! ```
18//!
19//! - **Sealed under [`MasterKey::seal`]** — the same AES-256-GCM **random-nonce** primitive
20//!   `AccountFile` uses for the sealed device seeds. This is deliberately **not**
21//!   `backup::artifact::seal_ledger`, whose nonce is *derived deterministically* from the wrap
22//!   key so that re-exporting a backup is byte-identical. That property is right for a
23//!   write-once artifact and catastrophic here: the store is rewritten on every `create_album`
24//!   and `rotate_epoch`, so a fixed nonce under a fixed key would repeat `(key, nonce)` across
25//!   different plaintexts and leak the keystream.
26//! - **Canonical CBOR, sorted by album id** (and each album's AMK rows by epoch), so the
27//!   plaintext is byte-stable for a given logical state.
28//! - Written **temp-then-rename** by `capsule-library`'s `AlbumStoreFile::save`, so a crash
29//!   mid-write never leaves a half-written keystore where the previous good one was.
30//! - The AMK rows reuse the backup artifact's row shape `(album_id, epoch, amk)`, so
31//!   keystore ↔ backup-ledger conversion is a `map`, not a translation table.
32//!
33//! ## Recovered (read-only) albums
34//!
35//! A backup artifact escrows **AMKs** — read access — but never the write-tier or admin signing
36//! keys, which are MLS-distributed *capabilities*. It does carry each album's **public**
37//! authority, the admin-signed epoch ledger (#468). An album restored from a backup into a
38//! library that never held it therefore lands here with `write_tier_seed64 = None`,
39//! `admin_seed64 = None`, and `authority = Some(Reference(ledger))` (or `None` from a format-1
40//! artifact, which carried no ledger): its photos decrypt, re-export, and verify, but it cannot
41//! author new writes until its signing capability is re-established. That is the honest state,
42//! and the lifecycle surfaces it as a typed error rather than minting a fresh admin key that
43//! attests nothing and no peer trusts. The ledger re-verifies on every load, like any other.
44
45use std::collections::BTreeSet;
46
47use serde::{Deserialize, Serialize};
48use serde_bytes::ByteBuf;
49use thiserror::Error;
50use uuid::Uuid;
51
52use super::hybrid_sig::HybridSigningKey;
53use super::master::MasterKey;
54use crate::cbor;
55use crate::crypto::CryptoError;
56use crate::crypto::authority::{AlbumAuthority, Authority, ReferenceAuthority, SignedEpochLedger};
57
58/// The album store's on-disk format version. Bumped only on a breaking layout change; a store
59/// declaring a higher version is refused rather than misread.
60pub(crate) const ALBUM_STORE_VERSION: u16 = 1;
61
62/// The store's filename beneath `{root}/.library/`.
63pub const ALBUM_STORE_FILE: &str = "albums.cbor";
64
65/// The domain separator an album's server-side key escrow carries ahead of its canonical CBOR,
66/// inside the master-key seal. It keeps an escrowed album from ever opening as any other blob the
67/// master key seals (the keystore file, the sealed identity), and names the format version.
68const ALBUM_KEY_ESCROW_DOMAIN: &[u8] = b"capsule-album-key-escrow/v1\0";
69
70/// How an album key escrow the server holds stands against the album a device holds
71/// ([`PersistedAlbum::escrow_coverage`]). Only [`Superseded`](Self::Superseded) is a state the
72/// device may overwrite: every other one either needs nothing or would lose an epoch.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum EscrowCoverage {
75    /// The escrow is this album's state exactly.
76    Current,
77    /// The escrow holds every epoch this album holds, with the same keys, and more: another
78    /// device rotated further, or the escrow holds a write-tier seed, admin seed or authority
79    /// this album lacks (a read-only device). Every local epoch is covered; replacing it would
80    /// drop the newer epochs or the capability, so it is left alone.
81    Behind,
82    /// This album holds every epoch the escrow holds, with the same keys, and more (or the same
83    /// epochs with other details changed), and every seed and authority the escrow holds:
84    /// replacing the escrow only adds to it.
85    Superseded,
86    /// The two disagree: a shared epoch under different keys, each holds an epoch the other
87    /// lacks, or this album holds an epoch the escrow lacks while the escrow holds a seed or
88    /// authority this album lacks. Neither may replace the other without losing an epoch or a
89    /// capability, so it is left alone and this album's own epochs stay uncovered.
90    Divergent,
91    /// The escrow does not open under this master key as this album — sealed under another
92    /// master key, or not an escrow of it. Left alone: replacing what cannot be read could
93    /// destroy epochs this device cannot see.
94    Unreadable,
95}
96
97/// One escrowed album content key: `(album_id, epoch, amk)`.
98///
99/// Identical to the row shape of the backup artifact's AMK ledger, so moving keys between the
100/// keystore and a backup is a `map` over rows.
101pub type AmkRow = (Uuid, u32, [u8; 32]);
102
103/// Errors from reading, writing, or decoding the album store.
104#[derive(Debug, Error)]
105pub enum AlbumStoreError {
106    /// Filesystem error reading or writing `albums.cbor`.
107    #[error("album store io: {0}")]
108    Io(String),
109    /// The sealed plaintext was not decodable CBOR.
110    #[error("album store cbor: {0}")]
111    Cbor(String),
112    /// The master key did not open the sealed store (wrong key, or tampering).
113    #[error(transparent)]
114    Crypto(#[from] CryptoError),
115    /// The store declares a format version this build does not implement.
116    #[error("album store format version {0} is newer than this build supports")]
117    UnsupportedVersion(u16),
118    /// The store holds an [`OpenMlsAuthority`](crate::crypto::authority::OpenMlsAuthority) state
119    /// blob but this build has no `mls` feature. A typed error, never a panic: the library still
120    /// opens, and the affected album is reported rather than silently dropped.
121    #[error("album {0} has MLS authority state, but this build has no `mls` support")]
122    MlsUnavailable(Uuid),
123    /// Exporting or importing MLS group state failed.
124    #[error("album {album}: mls authority state: {detail}")]
125    MlsState {
126        /// The album whose authority state failed.
127        album: Uuid,
128        /// The backend's own message.
129        detail: String,
130    },
131    /// A persisted reference ledger did not re-verify its admin signature chain — a tampered,
132    /// forged, or rewound ledger. Never repaired silently.
133    #[error("album {0}: persisted authority ledger failed admin-chain verification")]
134    LedgerRejected(Uuid),
135    /// A persisted signing seed was not the expected 64 bytes.
136    #[error("album {0}: persisted signing seed has the wrong length")]
137    MalformedSeed(Uuid),
138    /// An album key escrow opened under the master key but is not one: it lacks the escrow's
139    /// domain separator, so it is some other blob the master key seals.
140    #[error("the blob is not an album key escrow")]
141    NotAnAlbumKeyEscrow,
142    /// An album key escrow was served under one album id and holds another — a server that
143    /// swapped two of an account's escrows. Refused rather than filed under either id.
144    #[error("the album key escrow served for album {expected} holds album {found}")]
145    EscrowAlbumMismatch {
146        /// The album id the escrow was served under.
147        expected: Uuid,
148        /// The album id the escrow holds.
149        found: Uuid,
150    },
151}
152
153type Result<T> = std::result::Result<T, AlbumStoreError>;
154
155/// One album's persisted authority state, behind the
156/// [`AlbumAuthority`] seam.
157///
158/// Both variants exist on **every** build, `mls` or not: a non-mls build must be able to *decode*
159/// an MLS-authority album and report it as [`AlbumStoreError::MlsUnavailable`], which it could not
160/// do if the variant were `cfg`-gated away (the decode itself would fail, indistinguishable from
161/// corruption).
162#[derive(Debug, Clone, Serialize, Deserialize)]
163pub enum PersistedAuthority {
164    /// The offline reference backend's admin-signed epoch ledger. Re-verified on load. Boxed:
165    /// the ledger dwarfs the MLS variant's byte buffer, and this enum is stored per album.
166    Reference(Box<SignedEpochLedger>),
167    /// [`OpenMlsAuthority::export_state`](crate::crypto::authority::OpenMlsAuthority::export_state)
168    /// bytes (its own CBOR envelope, opaque here).
169    OpenMls(ByteBuf),
170}
171
172impl PersistedAuthority {
173    /// Capture an in-memory [`Authority`] for persistence.
174    pub fn capture(authority: &Authority) -> Result<Self> {
175        match authority {
176            Authority::Reference(a) => Ok(Self::Reference(Box::new(a.to_ledger()))),
177            #[cfg(feature = "mls")]
178            Authority::OpenMls(a) => a
179                .export_state()
180                .map(|bytes| Self::OpenMls(ByteBuf::from(bytes)))
181                .map_err(|e| AlbumStoreError::MlsState {
182                    album: authority.album_id(),
183                    detail: e.to_string(),
184                }),
185        }
186    }
187
188    /// Rebuild the live [`Authority`]. `held_epochs` are the epochs whose AMK this device
189    /// actually holds — the reference backend's `amk_present` flags are local-only state and are
190    /// restored from the AMK rows, never from the signed ledger.
191    ///
192    /// A reference ledger whose admin chain does not re-verify is [`LedgerRejected`], and an MLS
193    /// state blob on a build without the `mls` feature is [`MlsUnavailable`]. Neither panics.
194    ///
195    /// [`LedgerRejected`]: AlbumStoreError::LedgerRejected
196    /// [`MlsUnavailable`]: AlbumStoreError::MlsUnavailable
197    pub fn restore(&self, album_id: Uuid, held_epochs: &BTreeSet<u32>) -> Result<Authority> {
198        match self {
199            Self::Reference(ledger) => ReferenceAuthority::from_ledger(ledger, held_epochs)
200                .map(|a| Authority::Reference(Box::new(a)))
201                .ok_or(AlbumStoreError::LedgerRejected(album_id)),
202            #[cfg(feature = "mls")]
203            Self::OpenMls(bytes) => {
204                crate::crypto::authority::OpenMlsAuthority::import_state(bytes.as_ref())
205                    .map(|a| Authority::OpenMls(Box::new(a)))
206                    .map_err(|e| AlbumStoreError::MlsState {
207                        album: album_id,
208                        detail: e.to_string(),
209                    })
210            }
211            #[cfg(not(feature = "mls"))]
212            Self::OpenMls(_) => Err(AlbumStoreError::MlsUnavailable(album_id)),
213        }
214    }
215}
216
217/// One album's persisted key material.
218#[derive(Debug, Clone, Serialize, Deserialize)]
219pub struct PersistedAlbum {
220    /// Album id.
221    pub album_id: Uuid,
222    /// Display name.
223    pub name: String,
224    /// The AMK ledger: one `(album_id, epoch, amk)` row per epoch, kept sorted by epoch.
225    pub amks: Vec<AmkRow>,
226    /// The current (highest) epoch — the one new writes are authored under.
227    pub current_epoch: u32,
228    /// The per-album write-tier signing key's 64-byte hybrid seed (Ed25519 ‖ ML-DSA-65).
229    /// `None` for an album recovered from a backup artifact, which escrows no write capability.
230    pub write_tier_seed64: Option<ByteBuf>,
231    /// The per-album admin signing key's 64-byte hybrid seed. `None` as above.
232    pub admin_seed64: Option<ByteBuf>,
233    /// The attested authority state. For a backup-recovered album, the public ledger the artifact
234    /// carried, or `None` when it carried none.
235    pub authority: Option<PersistedAuthority>,
236}
237
238impl PersistedAlbum {
239    /// A read-only album entry: escrowed AMKs and, when the artifact carried one, the album's
240    /// public authority — but no write or admin capability. This is what a backup restore can
241    /// honestly reconstruct.
242    pub fn recovered(
243        album_id: Uuid,
244        name: &str,
245        amks: Vec<AmkRow>,
246        authority: Option<PersistedAuthority>,
247    ) -> Self {
248        let current_epoch = amks.iter().map(|(_, epoch, _)| *epoch).max().unwrap_or(0);
249        let mut album = Self {
250            album_id,
251            name: name.to_string(),
252            amks,
253            current_epoch,
254            write_tier_seed64: None,
255            admin_seed64: None,
256            authority,
257        };
258        album.normalize();
259        album
260    }
261
262    /// The epochs whose AMK content key this device holds — the input that restores a reference
263    /// authority's local-only `amk_present` flags.
264    pub fn held_epochs(&self) -> BTreeSet<u32> {
265        self.amks.iter().map(|(_, epoch, _)| *epoch).collect()
266    }
267
268    /// Decode the write-tier signing key, if this album carries write capability.
269    pub fn write_tier_key(&self) -> Result<Option<HybridSigningKey>> {
270        self.decode_seed(self.write_tier_seed64.as_ref())
271    }
272
273    /// Decode the admin signing key, if this album carries admin capability.
274    pub fn admin_key(&self) -> Result<Option<HybridSigningKey>> {
275        self.decode_seed(self.admin_seed64.as_ref())
276    }
277
278    fn decode_seed(&self, seed: Option<&ByteBuf>) -> Result<Option<HybridSigningKey>> {
279        seed.map(|bytes| {
280            let seed64: [u8; 64] = bytes
281                .as_ref()
282                .try_into()
283                .map_err(|_| AlbumStoreError::MalformedSeed(self.album_id))?;
284            Ok(HybridSigningKey::from_seed64(&seed64))
285        })
286        .transpose()
287    }
288
289    /// This album's **server-side key escrow**: its canonical CBOR behind
290    /// a versioned domain separator, sealed under the account master key with
291    /// [`MasterKey::seal`].
292    ///
293    /// Everything the album holds travels — every epoch's AMK, the write-tier and admin seeds,
294    /// and the authority — so a device recovered from the master key alone holds the album as
295    /// the device that escrowed it did. It adds no root: only the master key opens it, and the
296    /// master key already opens the keystore file this is a slice of. The seal draws a fresh
297    /// nonce, so two escrows of one state differ in their bytes;
298    /// [`escrow_matches`](Self::escrow_matches) compares what they open to.
299    ///
300    /// # Errors
301    ///
302    /// [`AlbumStoreError::Cbor`] when the album does not encode.
303    pub fn seal_escrow(&self, master: &MasterKey) -> Result<Vec<u8>> {
304        Ok(master.seal(&self.escrow_plaintext()?))
305    }
306
307    /// Open an album key escrow [`seal_escrow`](Self::seal_escrow) produced, served under
308    /// `album_id`.
309    ///
310    /// # Errors
311    ///
312    /// [`AlbumStoreError::Crypto`] when the master key does not open it (another account's, or
313    /// tampered), [`AlbumStoreError::NotAnAlbumKeyEscrow`] when it opens but is another kind of
314    /// sealed blob, [`AlbumStoreError::Cbor`] when it does not decode, and
315    /// [`AlbumStoreError::EscrowAlbumMismatch`] when it holds an album other than `album_id`.
316    pub fn open_escrow(blob: &[u8], master: &MasterKey, album_id: Uuid) -> Result<Self> {
317        let plaintext = master.open(blob)?;
318        let body = plaintext
319            .strip_prefix(ALBUM_KEY_ESCROW_DOMAIN)
320            .ok_or(AlbumStoreError::NotAnAlbumKeyEscrow)?;
321        let mut album: Self =
322            cbor::from_slice(body).map_err(|e| AlbumStoreError::Cbor(e.to_string()))?;
323        if album.album_id != album_id {
324            return Err(AlbumStoreError::EscrowAlbumMismatch {
325                expected: album_id,
326                found: album.album_id,
327            });
328        }
329        album.normalize();
330        Ok(album)
331    }
332
333    /// Whether `blob` is an escrow of exactly this album's current state: it opens under
334    /// `master` as this album, and what it holds encodes to the same canonical bytes. Any
335    /// failure to open is `false`.
336    pub fn escrow_matches(&self, blob: &[u8], master: &MasterKey) -> bool {
337        self.escrow_coverage(blob, master) == EscrowCoverage::Current
338    }
339
340    /// How the escrow `blob` the server holds for this album stands against this album's
341    /// state — and so whether replacing it with this album's escrow can only add to it.
342    ///
343    /// The comparison is per epoch: an escrow is never replaced by one that lacks an epoch it
344    /// holds, or that holds a different key for an epoch they share, because a recovery from the
345    /// replacement would lose that epoch's assets. Nor is it replaced by one that lacks a
346    /// write-tier seed, admin seed or authority it holds: a read-only device (one restored from a
347    /// backup) would otherwise strip the capability every later recovery depends on. See
348    /// [`EscrowCoverage`].
349    pub fn escrow_coverage(&self, blob: &[u8], master: &MasterKey) -> EscrowCoverage {
350        let Ok(escrowed) = Self::open_escrow(blob, master, self.album_id) else {
351            return EscrowCoverage::Unreadable;
352        };
353        let local: std::collections::BTreeMap<u32, [u8; 32]> = self
354            .amks
355            .iter()
356            .map(|(_, epoch, amk)| (*epoch, *amk))
357            .collect();
358        let held: std::collections::BTreeMap<u32, [u8; 32]> = escrowed
359            .amks
360            .iter()
361            .map(|(_, epoch, amk)| (*epoch, *amk))
362            .collect();
363        if local
364            .iter()
365            .any(|(epoch, amk)| held.get(epoch).is_some_and(|other| other != amk))
366        {
367            return EscrowCoverage::Divergent;
368        }
369        let local_only = local.keys().any(|epoch| !held.contains_key(epoch));
370        let held_only = held.keys().any(|epoch| !local.contains_key(epoch));
371        let lacks_held_capability = self.lacks_capability_of(&escrowed);
372        match (local_only, held_only) {
373            (true, true) => EscrowCoverage::Divergent,
374            (false, true) => EscrowCoverage::Behind,
375            (true, false) if lacks_held_capability => EscrowCoverage::Divergent,
376            (true, false) => EscrowCoverage::Superseded,
377            (false, false) if lacks_held_capability => EscrowCoverage::Behind,
378            (false, false) => match (escrowed.escrow_plaintext(), self.escrow_plaintext()) {
379                (Ok(escrowed), Ok(local)) if escrowed == local => EscrowCoverage::Current,
380                _ => EscrowCoverage::Superseded,
381            },
382        }
383    }
384
385    /// Whether `other` holds a write-tier seed, an admin seed or an authority this album does
386    /// not, so that replacing `other` with this album would drop a capability.
387    fn lacks_capability_of(&self, other: &Self) -> bool {
388        (other.write_tier_seed64.is_some() && self.write_tier_seed64.is_none())
389            || (other.admin_seed64.is_some() && self.admin_seed64.is_none())
390            || (other.authority.is_some() && self.authority.is_none())
391    }
392
393    /// The bytes [`seal_escrow`](Self::seal_escrow) seals: the domain separator, then the
394    /// album's canonical CBOR in its normalized form.
395    fn escrow_plaintext(&self) -> Result<Vec<u8>> {
396        let mut album = self.clone();
397        album.normalize();
398        let body =
399            cbor::to_canonical_vec(&album).map_err(|e| AlbumStoreError::Cbor(e.to_string()))?;
400        let mut plaintext = Vec::with_capacity(ALBUM_KEY_ESCROW_DOMAIN.len() + body.len());
401        plaintext.extend_from_slice(ALBUM_KEY_ESCROW_DOMAIN);
402        plaintext.extend_from_slice(&body);
403        Ok(plaintext)
404    }
405
406    /// Sort the AMK rows by epoch and re-derive `current_epoch` as their maximum, so the encoded
407    /// form is byte-stable and the epoch pointer can never drift below a held key.
408    fn normalize(&mut self) {
409        self.amks.sort_unstable_by_key(|(_, epoch, _)| *epoch);
410        self.amks.dedup_by_key(|(_, epoch, _)| *epoch);
411        if let Some(max) = self.amks.iter().map(|(_, epoch, _)| *epoch).max() {
412            self.current_epoch = self.current_epoch.max(max);
413        }
414    }
415}
416
417/// Every album this library holds key material for, sealed at rest under the account master key.
418#[derive(Debug, Clone, Serialize, Deserialize)]
419pub struct AlbumStore {
420    /// On-disk format version.
421    pub version: u16,
422    /// The albums, **sorted by `album_id`** so the canonical encoding is byte-stable.
423    albums: Vec<PersistedAlbum>,
424}
425
426impl Default for AlbumStore {
427    fn default() -> Self {
428        Self::new()
429    }
430}
431
432impl AlbumStore {
433    /// An empty store at the current format version.
434    pub fn new() -> Self {
435        Self {
436            version: ALBUM_STORE_VERSION,
437            albums: Vec::new(),
438        }
439    }
440
441    /// The persisted albums, sorted by id.
442    pub fn albums(&self) -> &[PersistedAlbum] {
443        &self.albums
444    }
445
446    /// One album's persisted material.
447    pub fn get(&self, album_id: &Uuid) -> Option<&PersistedAlbum> {
448        self.albums
449            .binary_search_by_key(album_id, |a| a.album_id)
450            .ok()
451            .map(|i| &self.albums[i])
452    }
453
454    /// Insert or replace one album's entry wholesale (the `create_album` / `rotate_epoch` path,
455    /// where the workspace holds the complete, authoritative material).
456    pub fn upsert(&mut self, mut album: PersistedAlbum) {
457        album.normalize();
458        match self
459            .albums
460            .binary_search_by_key(&album.album_id, |a| a.album_id)
461        {
462            Ok(i) => self.albums[i] = album,
463            Err(i) => self.albums.insert(i, album),
464        }
465    }
466
467    /// Merge escrowed `(album_id, epoch, amk)` rows into the store — the backup-restore path.
468    ///
469    /// An album already present keeps its write capability, admin key, and authority and simply
470    /// gains any epochs it was missing; an unknown album is added as a
471    /// [read-only recovered entry](PersistedAlbum::recovered). An epoch already held is **never
472    /// overwritten**: the local copy is the one the local authority attests, and silently
473    /// swapping a content key underneath it would be a downgrade vector. Returns the number of
474    /// epochs actually added.
475    ///
476    /// `authority` is the album's public authority the artifact carried. It is adopted only by an
477    /// album that holds none — an unknown album, or one recovered earlier from an artifact that
478    /// carried no ledger. A **held authority is never replaced**, for the same downgrade reason.
479    pub fn merge_amks(
480        &mut self,
481        album_id: Uuid,
482        name: &str,
483        rows: impl IntoIterator<Item = AmkRow>,
484        authority: Option<PersistedAuthority>,
485    ) -> usize {
486        let rows: Vec<AmkRow> = rows.into_iter().collect();
487        match self.albums.binary_search_by_key(&album_id, |a| a.album_id) {
488            Ok(i) => {
489                let existing = &mut self.albums[i];
490                if existing.authority.is_none() {
491                    existing.authority = authority;
492                }
493                let held = existing.held_epochs();
494                let mut added = 0;
495                for row in rows {
496                    if !held.contains(&row.1) {
497                        existing.amks.push(row);
498                        added += 1;
499                    }
500                }
501                existing.normalize();
502                added
503            }
504            Err(i) => {
505                let album = PersistedAlbum::recovered(album_id, name, rows, authority);
506                let added = album.amks.len();
507                self.albums.insert(i, album);
508                added
509            }
510        }
511    }
512
513    /// Unseal a store from the bytes its file holds.
514    ///
515    /// Refuses bytes the master key did not seal and a store declaring a newer format version.
516    /// Reading those bytes from `{root}/.library/albums.cbor` is `capsule-library`'s business.
517    #[tracing::instrument(skip_all, fields(sealed_bytes = sealed.len()))]
518    pub fn open_sealed(sealed: &[u8], master: &MasterKey) -> Result<Self> {
519        let plaintext = master.open(sealed)?;
520        let store: Self =
521            cbor::from_slice(&plaintext).map_err(|e| AlbumStoreError::Cbor(e.to_string()))?;
522        if store.version > ALBUM_STORE_VERSION {
523            return Err(AlbumStoreError::UnsupportedVersion(store.version));
524        }
525        tracing::info!(
526            albums = store.albums.len(),
527            epochs = store.albums.iter().map(|a| a.amks.len()).sum::<usize>(),
528            sealed_bytes = sealed.len(),
529            "album store: loaded"
530        );
531        for album in &store.albums {
532            tracing::debug!(
533                album_id = %album.album_id,
534                current_epoch = album.current_epoch,
535                epochs = album.amks.len(),
536                writable = album.write_tier_seed64.is_some(),
537                has_authority = album.authority.is_some(),
538                "album store: album restored"
539            );
540        }
541        Ok(store)
542    }
543
544    /// Seal the store for persistence: canonical CBOR, albums sorted by id and normalized, at the
545    /// current format version, under the master key. Writing the bytes durably is
546    /// `capsule-library`'s business.
547    #[tracing::instrument(skip_all, fields(albums = self.albums.len()))]
548    pub fn seal(&self, master: &MasterKey) -> Result<Vec<u8>> {
549        let mut canonical = self.clone();
550        canonical.version = ALBUM_STORE_VERSION;
551        canonical
552            .albums
553            .sort_unstable_by_key(|album| album.album_id);
554        for album in &mut canonical.albums {
555            album.normalize();
556        }
557        let plaintext =
558            cbor::to_canonical_vec(&canonical).map_err(|e| AlbumStoreError::Cbor(e.to_string()))?;
559        let sealed = master.seal(&plaintext);
560        tracing::debug!(
561            sealed_bytes = sealed.len(),
562            epochs = canonical.albums.iter().map(|a| a.amks.len()).sum::<usize>(),
563            "album store: sealed"
564        );
565        Ok(sealed)
566    }
567}
568
569#[cfg(test)]
570mod tests;